0

在我的应用程序中,我必须将条形码图像添加到现有的 PDF 文档中。我可以用零字节编写修改后的 PDF。我是 iText 的新手。我无法在此代码中找到问题,也没有时间分析使其正常工作。

PdfReader reader = null ;
PdfStamper pdfStamper = null ;
PdfWriter writer = null ;

reader = new PdfReader("....\\barcode.pdf");
pdfStamper = new PdfStamper(reader, new FileOutputStream();

Barcode128 code128 = new Barcode128();
String barcodeValue = "" ;
code128.setCode(barcodeValue);
PdfContentByte contentByte = null ;

for(int i = 1 ; i <= reader.getNumberOfPages() ; i ++){
      contentByte = pdfStamper.getUnderContent(i);
      code128.setAltText("");
      code128.setBarHeight((float) (10));

      Image image = code128.createImageWithBarcode(contentByte, null, null);
      image.setAbsolutePosition(23f, 20f);
      image.setBackgroundColor(CMYKColor.WHITE);

      image.setWidthPercentage(75);
      contentByte.fill();
      contentByte.addImage(image);
      contentByte.fill();
}
PdfDocument pdfDocument = contentByte.getPdfDocument();
writer = PdfWriter.getInstance(pdfDocument, new FileOutputStream());

reader.close();
pdfStamper.close();
writer.close();
4

1 回答 1

4

确实很明显,您没有时间做任何努力来编写代码,因为它充满了错误。连你的问题都错了!您问“如何将图像添加到现有 PDF?” 但是,在阅读您的代码时,您实际上希望在现有 PDF 的每一页上添加一个条形码。您创建一个条形码,然后将其转换为图像。为什么不将条形码添加为 Form XObject?此外,完全不清楚您为什么使用contentByte.fill(). 此外,您正在将图像添加到硬编码位置。那是明智的吗?

我编写了一个示例,为 16 页 PDF 的每一页添加条形码:StampBarcode

PdfReader reader = new PdfReader(src);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
int n = reader.getNumberOfPages();
Rectangle pagesize;
for (int i = 1; i <= n; i++) {
    PdfContentByte over = stamper.getOverContent(i);
    pagesize = reader.getPageSize(i);
    float x = pagesize.getLeft() + 10;
    float y = pagesize.getTop() - 50;       
    BarcodeEAN barcode = new BarcodeEAN();
    barcode.setCodeType(Barcode.EAN8);
    String s = String.valueOf(i);
    s = "00000000".substring(s.length()) + s; 
    barcode.setCode(s);
    PdfTemplate template =
            barcode.createTemplateWithBarcode(over, BaseColor.BLACK, BaseColor.BLACK);
    over.addTemplate(template, x, y);
}
stamper.close();
reader.close();

如您所见,我使用了显示页码的 EAN8 条形码(用零填充)。我根据要添加条形码的页面的页面大小来计算x和值。y我不创建Image对象。相反,我使用一个PdfTemplate对象。

这是生成的 PDF:add_barcode.pdf

如您所见,每页的左上角都有一个条形码。

额外说明:

有人有勇气否决这个答案。我不明白为什么。我能想到的唯一原因是我的答案太好了,因为我解释了如何添加条形码而不是图像。请允许我解释一下这是如何做到的。addTemplate()用方法替换方法就足够了addImage()

for (int i = 1; i <= n; i++) {
    PdfContentByte over = stamper.getOverContent(i);
    pagesize = reader.getPageSize(i);
    float x = pagesize.getLeft() + 10;
    float y = pagesize.getTop() - 50;
    Image img = Image.getInstance("image" + i + ".jpg");
    img.setAbsolutePosition(x, y);
    over.addImage(img);
}
于 2014-10-12T17:30:39.660 回答