How to add content to PDF using iText PdfStamper

I am developing a System in which I have to add some images to an existing PDF document.

This works fine with iText 5.1.3, but for some reason it will not add any images to the PDF file that contains the scanned image.

Here is a link to a PDF document that cannot be modified using PdfStamper

and here is 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(); 
+5
source share
1 answer

The PDF page should not have a bottom left corner at (0, 0) . It can be anywhere in the coordinate system. Thus, an A4 page can be (0, 0, 595, 842) , but it can also be (1000, 2000, 1595, 2842) .

You position 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 outside the visible area of ​​the page.

You need to get the page coordinates to place the image. Inside the loop do the following:

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

Source: https://habr.com/ru/post/901775/


All Articles