Adding an image to an existing file

This is a code example of iText PDF, discover more.

31st October 2016
iText PDF

Switch code for this example

AddImageWithId.java
  1. /**
  2.  * Example written by Bruno Lowagie in answer to the following question:
  3.  * http://stackoverflow.com/questions/40336813/
  4.  */
  5. package sandbox.stamper;
  6.  
  7. import com.itextpdf.text.DocumentException;
  8. import com.itextpdf.text.Image;
  9. import com.itextpdf.text.pdf.PdfContentByte;
  10. import com.itextpdf.text.pdf.PdfImage;
  11. import com.itextpdf.text.pdf.PdfIndirectObject;
  12. import com.itextpdf.text.pdf.PdfName;
  13. import com.itextpdf.text.pdf.PdfReader;
  14. import com.itextpdf.text.pdf.PdfStamper;
  15. import java.io.File;
  16. import java.io.FileOutputStream;
  17. import java.io.IOException;
  18.  
  19. /**
  20.  * @author Bruno Lowagie (iText Software)
  21.  */
  22. public class AddImageWithId {
  23.     public static final String SRC = "resources/pdfs/hello.pdf";
  24.     public static final String DEST = "results/stamper/hello_with_image_id.pdf";
  25.     public static final String IMG = "resources/images/bruno.jpg";
  26.    
  27.     public static void main(String[] args) throws IOException, DocumentException {
  28.         File file = new File(DEST);
  29.         file.getParentFile().mkdirs();
  30.         new AddImageWithId().manipulatePdf(SRC, DEST);
  31.     }
  32.  
  33.     public void manipulatePdf(String src, String dest) throws IOException, DocumentException {
  34.         PdfReader reader = new PdfReader(src);
  35.         PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
  36.         Image image = Image.getInstance(IMG);
  37.         PdfImage stream = new PdfImage(image, "", null);
  38.         stream.put(new PdfName("ITXT_SpecialId"), new PdfName("123456789"));
  39.         PdfIndirectObject ref = stamper.getWriter().addToBody(stream);
  40.         image.setDirectReference(ref.getIndirectReference());
  41.         image.setAbsolutePosition(36, 400);
  42.         PdfContentByte over = stamper.getOverContent(1);
  43.         over.addImage(image);
  44.         stamper.close();
  45.         reader.close();
  46.     }
  47.    
  48. }
Contact

Still have questions? 

We're happy to answer your questions. Reach out to us and we'll get back to you shortly.

Contact us
Stay updated

Join 11,000+ subscribers and become an iText PDF expert by staying up to date with our new products, updates, tips, technical solutions and happenings.

Subscribe Now