【教程】将Java条形码添加到PDF文档的两种方法

来源:互联网 发布:淘宝联盟点击赚钱 编辑:程序博客网 时间:2024/06/04 18:48

jPDFProcess是用于PDF文件的Java库,可用作向用户传递自定义PDF内容或者对引入的PDF内容进行处理和操作。本教程演示了使用jPDFProcess将Java条形码添加到PDF文档的两种方法。

关联产品
  • jPDFProcess

通过jPDFProcess,将PDF文档添加到PDF文档中的方法:

方法1

使用条形码字体,其字符看起来像条形码,然后使用此字体向文档添加文本。当显示文档时,它将显示条形码(使用字体绘制),并具有将条形码值保持在文本内容中的附加优势。 这时候需要在运行的同一文件夹中的free3of9.ttf文件,该文件是TrueType Code39字体,示例程序将此字体嵌入到PDF中,然后使用它来绘制字符串。

代码示例

String barcodeMSG = "0123456789"; // Create a blank document and add a pagePDFDocument pdf = new PDFDocument();PDFPage newPage = pdf.appendNewPage(8.5 * 72, 11 * 72);Graphics2D pageG2 = newPage.createGraphics(); // Embed the fontFont code39Font = pdf.embedFont("free3of9.ttf", Font.TRUETYPE_FONT);pageG2.setFont(code39Font.deriveFont(64f));pageG2.drawString(barcodeMSG, 72, 108); // Save the documentpdf.saveDocument("barcode.pdf");

方法2

第二种方法是使用条形码库创建条形码图像,然后使用jPDFProcess将该图像绘制到PDF上。 barcode4j.jar文件是一个开放源代码库,它实现了许多条形码生成类,包括代码39.样例程序使用这个jar文件中的类来生成条形码图像,然后将图像添加到 PDF文件。

代码示例

String barcodeMSG = "0123456789"; // Create a blank document and add a pagePDFDocument 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 pageCode39Bean 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 pagepageG2.drawImage(barcodeImage, posX, posY, null); // Save the documentpdf.saveDocument("barcode.pdf");

查看原文


原创粉丝点击