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

关联产品

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

方法1

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

代码示例

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");

方法2

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

代码示例

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");

查看原文

 

转载于:https://my.oschina.net/u/3006003/blog/907634

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值