2016-07-05 87 views
0

我想从barcode4j库(code128bean,其他条码豆)生成条码,并尝试添加到现有的PDF。条形码图像使用下面的代码在本地创建。如何使用pdfbox(1.8.12)将barcode4j库添加到现有的pdf中Code128 Barcode图像?

//Create the barcode bean 
Code128Bean code128Bean = new Code128Bean(); 
final int dpi = 150; 
code128Bean.setModuleWidth(UnitConv.in2mm(1.0f/dpi)); //makes the narrow bar 
//width exactly one pixel 
//bean.setCodeset(2); 
code128Bean.doQuietZone(false); 

//Open output file 
File outputFile = new File("D:/barcode4jcod128.png"); //I dont want to create it 
OutputStream code128Stream = new FileOutputStream(outputFile); 
try { 
    //Set up the canvas provider for monochrome PNG output 
    BitmapCanvasProvider canvas1 = new BitmapCanvasProvider(
      code128Stream, "image/x-png", dpi, BufferedImage.TYPE_BYTE_BINARY, false, 0); 

    //Generate the barcode 
    code128Bean.generateBarcode(canvas1, "123456"); 

    //Signal end of generation 
    canvas1.finish(); 
} finally { 
    code128Stream.close(); 
} 
  1. 我的问题是,我不希望创建一个图像,并保存到本地文件系统中,然后将其作为图像添加到PDF。我只是想创建动态我的意思是动态创建条码图像并将其添加到PDF。
  2. 如何设置页面大小的(如PDPage.PAGE_SIZE_A4),而我从catalog.getAllPages()方法检索,像(List<PDPage> pages = catalog.getAllPages();

有人可以在此帮助现有PDPages?

非常感谢你的帮助Tilman。这是我做的

public static BufferedImage geBufferedImageForCode128Bean(String barcodeString) { 
    Code128Bean code128Bean = new Code128Bean(); 
    final int dpi = 150; 
    code128Bean.setModuleWidth(UnitConv.in2mm(1.0f/dpi)); //makes the narrow bar 
    code128Bean.doQuietZone(false); 
    BitmapCanvasProvider canvas1 = new BitmapCanvasProvider(
     dpi, BufferedImage.TYPE_BYTE_BINARY, false, 0 
    ); 
    //Generate the barcode 
    code128Bean.generateBarcode(canvas1, barcodeString); 
    return canvas1.getBufferedImage(); 
} 

// main code 
PDDocument finalDoc = new PDDocument(); 
BufferedImage bufferedImage = geBufferedImageForCode128Bean("12345"); 
PDXObjectImage pdImage = new PDPixelMap(doc, bufferedImage); 
PDPageContentStream contentStream = new PDPageContentStream(
    finalDoc, pdPage, true, true, true 
); 
contentStream.drawXObject(pdImage, 100, 600, 50, 20); 
contentStream.close(); 
finalDoc.addPage(pdPage); 
finalDoc.save(new File("D:/Test75.pdf")); 

条码正在创建,但它是以垂直方式创建的。我想以水平方式看到。再次感谢你的帮助。

+0

这是kindof无糖否,编辑问题以添加新问题。此外,无论如何,我在评论中回答了这个问题。 –

回答

0

1)的图像添加到现有页面,同时保持内容:

BitmapCanvasProvider canvas1 = new BitmapCanvasProvider(
    dpi, BufferedImage.TYPE_BYTE_BINARY, false, 0 
); 
code128Bean.generateBarcode(canvas1, "123456"); 
canvas1.finish(); 
BufferedImage bim = canvas1.getBufferedImage(); 

PDXObjectImage img = new PDPixelMap(doc, bim); 
PDPageContentStream contents = new PDPageContentStream(doc, page, true, true, true); 
contents.drawXObject(img, 100, 600, bim.getWidth(), bim.getHeight()); 
contents.close(); 

2)设置媒体框A4现有页面上:

page.setMediaBox(PDPage.PAGE_SIZE_A4); 
+0

非常感谢你的帮助。根据代码中的line1,canvas1对象仍使用输出流,输出流intern由outputfile创建。 – venkata

+0

@venkata对不起!我错过了。我调整了我的答案,还有另一个构造函数。 –

+0

我找到了另一个构造函数。有什么办法可以在水平模式下制作条形码吗? – venkata

相关问题