How to add Content to a PDF using iText PdfStamper

天大地大妈咪最大 提交于 2019-12-22 04:48:07

问题


I'm developing a System in which I have to add some images to an existing PDF Document.

This works great with iText 5.1.3, but for some reason in a PDF that contains a scanned image it won't add any of the images.

Here's the link to the PDF Document that can't be modified with PdfStamper

and here's the code

  PdfReader reader = new PdfReader("Registro celular_OR.pdf");
  PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("DocStamped.pdf"));
  Image img = Image.getInstance("someImage.jpg");
  img.setAbsolutePosition(0, 0);
  img.scaleAbsolute(50f, 50f);
  PdfContentByte over = null;

  int total = reader.getNumberOfPages() + 1;
  for(int i = 1; i < total; i++) {
    System.out.println("Procesando Pagina: " + i);
    over = stamper.getOverContent(i);
    over.addImage(img);

    over.beginText();
    BaseFont bf_times = BaseFont.createFont(BaseFont.TIMES_ROMAN, "Cp1252", false);
    over.setFontAndSize(bf_times, 8);
    over.showTextAligned(PdfContentByte.ALIGN_CENTER, "TEXTO PRUEBA", 50, 50, 0);
    over.endText();
  }
  stamper.close();

回答1:


A PDF page does not need to have its lower left corner at (0, 0). It can be anywhere in the coordinate system. So an A4 page can be (0, 0, 595, 842), but it might as well be (1000, 2000, 1595, 2842).

You are positioning the image at (0, 0):

img.setAbsolutePosition(0, 0);

But the page of this document is defined as (0, 15366, 469, 15728). The image is actually added to the output document, but it's outside the visible area of the page.

You have to get the coordinates of the page to position the image. Inside the loop, do this:

img.setAbsolutePosition(reader.getPageSize(i).getLeft(), reader.getPageSize(i).getBottom());


来源:https://stackoverflow.com/questions/8176780/how-to-add-content-to-a-pdf-using-itext-pdfstamper

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!