You can add barcodes to PDF documents with jPDFProcess in a couple of ways:

  • You can use a barcode font, a font whose characters look like the barcode, and then add text to the document using this font.  When the document is displayed, it will show the barcode (drawn using the font), and will have the added advantage of keeping the barcode value in the text content as well. You will need the free3of9.ttf file in the same folder that you run from. This file is a TrueType Code39 font, the sample program embeds this font into the PDF and then uses it to draw a string.
    String barcodeMSG = "0123456789";
     
    // Create a blank document and add a page
    PDFDocument pdf = new PDFDocument();
    PDFPage newPage = pdf.appendNewPage(8.5 * 72, 11 * 72);
    Graphics2D pageG2 = newPage.createGraphics();
     
    // Embed the font
    Font code39Font = pdf.embedFont("free3of9.ttf", Font.TRUETYPE_FONT);		
    pageG2.setFont(code39Font.deriveFont(64f));
    pageG2.drawString(barcodeMSG, 72, 108);
     
    // Save the document
    pdf.saveDocument("barcode.pdf");
  • You can also use a Barcode library to create an image of the barcode, and then use jPDFProcess to draw that image onto the PDF. You will need the barcode4j.jar file is an open source library that implements a number of barcode generation classes, including Code 39.  The sample program uses the classes in this jar file to generate an image of the barcode and then adds the image to the PDF document.
    String barcodeMSG = "0123456789";
     
    // Create a blank document and add a page
    PDFDocument pdf = new PDFDocument();
    PDFPage newPage = pdf.appendNewPage(8.5 * 72, 11 * 72);
    Graphics2D pageG2 = newPage.createGraphics();
     
    // This code creates a barcode image using Barcode39 and then adds the image to the page
    Code39Bean code39 = new Code39Bean();
    code39.setModuleWidth(2);
    code39.setBarHeight(50);
    code39.setWideFactor(2);
    BarcodeDimension dim = code39.calcDimensions(barcodeMSG);
     
    BufferedImage barcodeImage = new BufferedImage((int)dim.getWidth(), (int)dim.getHeight(), BufferedImage.TYPE_INT_RGB);
    Graphics2D imageG2 = barcodeImage.createGraphics();
    imageG2.setColor(Color.white);
    imageG2.fillRect(0, 0, barcodeImage.getWidth(), barcodeImage.getHeight());
    imageG2.setColor(Color.black);
    code39.generateBarcode(new Java2DCanvasProvider(imageG2, 0), "0123456789");
     
    // Add the image to the page
    pageG2.drawImage(barcodeImage, posX, posY, null);
     
    // Save the document
    pdf.saveDocument("barcode.pdf");

Download AddBarcode.java Full Java Sample Program showing how to add a barcode to a PDF document using the 2 ways discussed above.

Tagged: