IText - How to stamp an image in an existing PDF file and create a binding

I have an existing document on which I would like to mark the image in absolute position. I can do this, but I would also like to make this image clickable: when the user clicks on the image, I would like the PDF file to move to the last page of the document.

Here is my code:

PdfReader readerOriginalDoc = new PdfReader("src/main/resources/test.pdf"); PdfStamper stamper = new PdfStamper(readerOriginalDoc,new FileOutputStream("NewStamper.pdf")); PdfContentByte content = stamper.getOverContent(1); Image image = Image.getInstance("src/main/resources/images.jpg"); image.scaleAbsolute(50, 20); image.setAbsolutePosition(100, 100); image.setAnnotation(new Annotation(0, 0, 0, 0, 3)); content.addImage(image); stamper.close(); 

Any idea how to do this?

+5
source share
1 answer

You use a technique that only works when creating documents from scratch.

Please see the AddImageLink example to find out how to add an image and link to make this image clickable for an existing document:

 public void manipulatePdf(String src, String dest) throws IOException, DocumentException { PdfReader reader = new PdfReader(src); PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest)); Image img = Image.getInstance(IMG); float x = 10; float y = 650; float w = img.getScaledWidth(); float h = img.getScaledHeight(); img.setAbsolutePosition(x, y); stamper.getOverContent(1).addImage(img); Rectangle linkLocation = new Rectangle(x, y, x + w, y + h); PdfDestination destination = new PdfDestination(PdfDestination.FIT); PdfAnnotation link = PdfAnnotation.createLink(stamper.getWriter(), linkLocation, PdfAnnotation.HIGHLIGHT_INVERT, reader.getNumberOfPages(), destination); link.setBorder(new PdfBorderArray(0, 0, 0)); stamper.addAnnotation(link, 1); stamper.close(); } 

You already have a portion of the right to add an image. Please note that I am creating parameters for the position of the image, as well as its dimensions:

 float x = 10; float y = 650; float w = img.getScaledWidth(); float h = img.getScaledHeight(); 

I use these values ​​to create a Rectangle object:

 Rectangle linkLocation = new Rectangle(x, y, x + w, y + h); 

This is the place to annotate the link that we create with the PdfAnnotation class. You must add this annotation separately using the addAnnotation() method.

You can see the result here: link_image.pdf If you click on the i icon, you will be taken to the last page of the document.

+6
source

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


All Articles