2

I'm trying to save an image into an existing pdf using apache PDFBOX,but my contents are getting deleted and i get blank document when I place the image on top of the pdf,Is there a solution to the problem?

My Code Looks like this.

    public class TestPdfImage {
        public static void main(String args[]) throws Exception {
              //Loading an existing document
              File file = new File("...../mydoc.pdf");
              PDDocument doc = PDDocument.load(file);

              //Retrieving the page
              PDPage page = doc.getPage(0);

              //Creating PDImageXObject object
              PDImageXObject pdImage = PDImageXObject.createFromFile("...../sample.png",doc);

              //creating the PDPageContentStream object
              PDPageContentStream contents = new PDPageContentStream(doc, page);

              //Drawing the image in the PDF document
              contents.drawImage(pdImage, 70, 250);

              System.out.println("Image inserted");

              //Closing the PDPageContentStream object
              contents.close();     

              //Saving the document
              doc.save(".../sample.pdf");

              //Closing the document
              doc.close();

           }

    }
Raj
  • 23
  • 3
  • Please try the five parameter constructor `new PDPageContentStream(doc, page, AppendMode.APPEND, true, true);` (this is a duplicate of some other question) – Tilman Hausherr Mar 27 '19 at 08:37

1 Answers1

5

Try to use the append-mode

//creating the PDPageContentStream object
PDPageContentStream contents = new PDPageContentStream(doc, page, AppendMode.APPEND, true);

Edit

TilmanHausherr mentioned

new PDPageContentStream(doc, page, AppendMode.APPEND, true, true);

Thats why

Wulf
  • 712
  • 5
  • 25