Problem with empty page when using Apache PDFBox to add image to PDF










1















I am using this code: https://www.tutorialspoint.com/pdfbox/pdfbox_inserting_image.htm



To help me add an image to an existing PDF. The problem is that the file it creates is a blank page with only the image on it.



Here is my code:



public void signPDF(PdfDTO pdfDTO) throws IOException
//Loading an existing document
File file = new File(getAbsolutePdfPath(pdfDTO));
PDDocument doc = PDDocument.load(file);

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

//a test to ensure the doc is loading correctly
PDDocument testDoc = new PDDocument();
testDoc.addPage(page);
testDoc.save("C:" + File.separator + "Users" + File.separator + "kdotson" + File.separator + "Documents" + File.separator + "test.pdf");
testDoc.close(); //this file is good so I know the doc is loading correctly

//Creating PDImageXObject object
PDImageXObject pdImage = PDImageXObject.createFromFile("C://test_images/signature.pdf", doc);

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

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

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

//Saving the document
doc.save(new File(getSignedPdfLocation(pdfDTO))); //the created file has the image on it, so I know the image is loading correctly

//Closing the document
doc.close();



As far as I can tell, what I'm doing should work, and I don't get any errors, so what gives?










share|improve this question






















  • Likely duplicate of stackoverflow.com/questions/27919436 . Please try that first and if it doesn't work, please link to your PDF.

    – Tilman Hausherr
    Nov 14 '18 at 5:07






  • 1





    @TilmanHausherr Not a duplicate but closely related. The issue here is failure due to use of new PDPageContentStream(doc, page) and the solution is to use a constructor with at least the third (append) parameter. The issue in the question you link to is failure do to use of new PDPageContentStream(doc, page, true, true) and the solution is to use a constructor with the fifth (resetContext) parameter. One might consider creating a canonical answer for all questions about which PDPageContentStream constructor to use.

    – mkl
    Nov 14 '18 at 14:19
















1















I am using this code: https://www.tutorialspoint.com/pdfbox/pdfbox_inserting_image.htm



To help me add an image to an existing PDF. The problem is that the file it creates is a blank page with only the image on it.



Here is my code:



public void signPDF(PdfDTO pdfDTO) throws IOException
//Loading an existing document
File file = new File(getAbsolutePdfPath(pdfDTO));
PDDocument doc = PDDocument.load(file);

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

//a test to ensure the doc is loading correctly
PDDocument testDoc = new PDDocument();
testDoc.addPage(page);
testDoc.save("C:" + File.separator + "Users" + File.separator + "kdotson" + File.separator + "Documents" + File.separator + "test.pdf");
testDoc.close(); //this file is good so I know the doc is loading correctly

//Creating PDImageXObject object
PDImageXObject pdImage = PDImageXObject.createFromFile("C://test_images/signature.pdf", doc);

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

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

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

//Saving the document
doc.save(new File(getSignedPdfLocation(pdfDTO))); //the created file has the image on it, so I know the image is loading correctly

//Closing the document
doc.close();



As far as I can tell, what I'm doing should work, and I don't get any errors, so what gives?










share|improve this question






















  • Likely duplicate of stackoverflow.com/questions/27919436 . Please try that first and if it doesn't work, please link to your PDF.

    – Tilman Hausherr
    Nov 14 '18 at 5:07






  • 1





    @TilmanHausherr Not a duplicate but closely related. The issue here is failure due to use of new PDPageContentStream(doc, page) and the solution is to use a constructor with at least the third (append) parameter. The issue in the question you link to is failure do to use of new PDPageContentStream(doc, page, true, true) and the solution is to use a constructor with the fifth (resetContext) parameter. One might consider creating a canonical answer for all questions about which PDPageContentStream constructor to use.

    – mkl
    Nov 14 '18 at 14:19














1












1








1








I am using this code: https://www.tutorialspoint.com/pdfbox/pdfbox_inserting_image.htm



To help me add an image to an existing PDF. The problem is that the file it creates is a blank page with only the image on it.



Here is my code:



public void signPDF(PdfDTO pdfDTO) throws IOException
//Loading an existing document
File file = new File(getAbsolutePdfPath(pdfDTO));
PDDocument doc = PDDocument.load(file);

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

//a test to ensure the doc is loading correctly
PDDocument testDoc = new PDDocument();
testDoc.addPage(page);
testDoc.save("C:" + File.separator + "Users" + File.separator + "kdotson" + File.separator + "Documents" + File.separator + "test.pdf");
testDoc.close(); //this file is good so I know the doc is loading correctly

//Creating PDImageXObject object
PDImageXObject pdImage = PDImageXObject.createFromFile("C://test_images/signature.pdf", doc);

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

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

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

//Saving the document
doc.save(new File(getSignedPdfLocation(pdfDTO))); //the created file has the image on it, so I know the image is loading correctly

//Closing the document
doc.close();



As far as I can tell, what I'm doing should work, and I don't get any errors, so what gives?










share|improve this question














I am using this code: https://www.tutorialspoint.com/pdfbox/pdfbox_inserting_image.htm



To help me add an image to an existing PDF. The problem is that the file it creates is a blank page with only the image on it.



Here is my code:



public void signPDF(PdfDTO pdfDTO) throws IOException
//Loading an existing document
File file = new File(getAbsolutePdfPath(pdfDTO));
PDDocument doc = PDDocument.load(file);

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

//a test to ensure the doc is loading correctly
PDDocument testDoc = new PDDocument();
testDoc.addPage(page);
testDoc.save("C:" + File.separator + "Users" + File.separator + "kdotson" + File.separator + "Documents" + File.separator + "test.pdf");
testDoc.close(); //this file is good so I know the doc is loading correctly

//Creating PDImageXObject object
PDImageXObject pdImage = PDImageXObject.createFromFile("C://test_images/signature.pdf", doc);

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

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

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

//Saving the document
doc.save(new File(getSignedPdfLocation(pdfDTO))); //the created file has the image on it, so I know the image is loading correctly

//Closing the document
doc.close();



As far as I can tell, what I'm doing should work, and I don't get any errors, so what gives?







java apache pdf pdfbox






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 13 '18 at 22:21









Katie.SunKatie.Sun

587114




587114












  • Likely duplicate of stackoverflow.com/questions/27919436 . Please try that first and if it doesn't work, please link to your PDF.

    – Tilman Hausherr
    Nov 14 '18 at 5:07






  • 1





    @TilmanHausherr Not a duplicate but closely related. The issue here is failure due to use of new PDPageContentStream(doc, page) and the solution is to use a constructor with at least the third (append) parameter. The issue in the question you link to is failure do to use of new PDPageContentStream(doc, page, true, true) and the solution is to use a constructor with the fifth (resetContext) parameter. One might consider creating a canonical answer for all questions about which PDPageContentStream constructor to use.

    – mkl
    Nov 14 '18 at 14:19


















  • Likely duplicate of stackoverflow.com/questions/27919436 . Please try that first and if it doesn't work, please link to your PDF.

    – Tilman Hausherr
    Nov 14 '18 at 5:07






  • 1





    @TilmanHausherr Not a duplicate but closely related. The issue here is failure due to use of new PDPageContentStream(doc, page) and the solution is to use a constructor with at least the third (append) parameter. The issue in the question you link to is failure do to use of new PDPageContentStream(doc, page, true, true) and the solution is to use a constructor with the fifth (resetContext) parameter. One might consider creating a canonical answer for all questions about which PDPageContentStream constructor to use.

    – mkl
    Nov 14 '18 at 14:19

















Likely duplicate of stackoverflow.com/questions/27919436 . Please try that first and if it doesn't work, please link to your PDF.

– Tilman Hausherr
Nov 14 '18 at 5:07





Likely duplicate of stackoverflow.com/questions/27919436 . Please try that first and if it doesn't work, please link to your PDF.

– Tilman Hausherr
Nov 14 '18 at 5:07




1




1





@TilmanHausherr Not a duplicate but closely related. The issue here is failure due to use of new PDPageContentStream(doc, page) and the solution is to use a constructor with at least the third (append) parameter. The issue in the question you link to is failure do to use of new PDPageContentStream(doc, page, true, true) and the solution is to use a constructor with the fifth (resetContext) parameter. One might consider creating a canonical answer for all questions about which PDPageContentStream constructor to use.

– mkl
Nov 14 '18 at 14:19






@TilmanHausherr Not a duplicate but closely related. The issue here is failure due to use of new PDPageContentStream(doc, page) and the solution is to use a constructor with at least the third (append) parameter. The issue in the question you link to is failure do to use of new PDPageContentStream(doc, page, true, true) and the solution is to use a constructor with the fifth (resetContext) parameter. One might consider creating a canonical answer for all questions about which PDPageContentStream constructor to use.

– mkl
Nov 14 '18 at 14:19













1 Answer
1






active

oldest

votes


















1














Please also have a look at the JavaDocs and sources of the library you try to work with. You create a PDPageContentStream:



PDPageContentStream contents = new PDPageContentStream(doc, page);


This conductor is documented to overwrite all existing content streams of this page:



/**
* Create a new PDPage content stream. This constructor overwrites all existing content streams
* of this page.
*
* @param document The document the page is part of.
* @param sourcePage The page to write the contents to.
* @throws IOException If there is an error writing to the page contents.
*/
public PDPageContentStream(PDDocument document, PDPage sourcePage) throws IOException


Thus, you have to use a different constructor which keeps the current page contents, e.g.



/**
* Create a new PDPage content stream.
*
* @param document The document the page is part of.
* @param sourcePage The page to write the contents to.
* @param appendContent Indicates whether content will be overwritten, appended or prepended.
* @param compress Tell if the content stream should compress the page contents.
* @param resetContext Tell if the graphic context should be reset. This is only relevant when
* the appendContent parameter is set to @link AppendMode#APPEND. You should use this when
* appending to an existing stream, because the existing stream may have changed graphic
* properties (e.g. scaling, rotation).
* @throws IOException If there is an error writing to the page contents.
*/
public PDPageContentStream(PDDocument document, PDPage sourcePage, AppendMode appendContent,
boolean compress, boolean resetContext) throws IOException


Thus



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


should make your code work as desired.



Alternatively, if you want the image in the background, try



PDPageContentStream contents = new PDPageContentStream(doc, page, AppendMode.PREPEND, true, true);


Beware, though, in certain cases the image won't be visible in the background, e.g. if the existing content starts with an instruction to fill the whole page area in white. In such a case watermarks must be applied with some kind of transparency atop existing content.






share|improve this answer






















    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53290401%2fproblem-with-empty-page-when-using-apache-pdfbox-to-add-image-to-pdf%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    Please also have a look at the JavaDocs and sources of the library you try to work with. You create a PDPageContentStream:



    PDPageContentStream contents = new PDPageContentStream(doc, page);


    This conductor is documented to overwrite all existing content streams of this page:



    /**
    * Create a new PDPage content stream. This constructor overwrites all existing content streams
    * of this page.
    *
    * @param document The document the page is part of.
    * @param sourcePage The page to write the contents to.
    * @throws IOException If there is an error writing to the page contents.
    */
    public PDPageContentStream(PDDocument document, PDPage sourcePage) throws IOException


    Thus, you have to use a different constructor which keeps the current page contents, e.g.



    /**
    * Create a new PDPage content stream.
    *
    * @param document The document the page is part of.
    * @param sourcePage The page to write the contents to.
    * @param appendContent Indicates whether content will be overwritten, appended or prepended.
    * @param compress Tell if the content stream should compress the page contents.
    * @param resetContext Tell if the graphic context should be reset. This is only relevant when
    * the appendContent parameter is set to @link AppendMode#APPEND. You should use this when
    * appending to an existing stream, because the existing stream may have changed graphic
    * properties (e.g. scaling, rotation).
    * @throws IOException If there is an error writing to the page contents.
    */
    public PDPageContentStream(PDDocument document, PDPage sourcePage, AppendMode appendContent,
    boolean compress, boolean resetContext) throws IOException


    Thus



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


    should make your code work as desired.



    Alternatively, if you want the image in the background, try



    PDPageContentStream contents = new PDPageContentStream(doc, page, AppendMode.PREPEND, true, true);


    Beware, though, in certain cases the image won't be visible in the background, e.g. if the existing content starts with an instruction to fill the whole page area in white. In such a case watermarks must be applied with some kind of transparency atop existing content.






    share|improve this answer



























      1














      Please also have a look at the JavaDocs and sources of the library you try to work with. You create a PDPageContentStream:



      PDPageContentStream contents = new PDPageContentStream(doc, page);


      This conductor is documented to overwrite all existing content streams of this page:



      /**
      * Create a new PDPage content stream. This constructor overwrites all existing content streams
      * of this page.
      *
      * @param document The document the page is part of.
      * @param sourcePage The page to write the contents to.
      * @throws IOException If there is an error writing to the page contents.
      */
      public PDPageContentStream(PDDocument document, PDPage sourcePage) throws IOException


      Thus, you have to use a different constructor which keeps the current page contents, e.g.



      /**
      * Create a new PDPage content stream.
      *
      * @param document The document the page is part of.
      * @param sourcePage The page to write the contents to.
      * @param appendContent Indicates whether content will be overwritten, appended or prepended.
      * @param compress Tell if the content stream should compress the page contents.
      * @param resetContext Tell if the graphic context should be reset. This is only relevant when
      * the appendContent parameter is set to @link AppendMode#APPEND. You should use this when
      * appending to an existing stream, because the existing stream may have changed graphic
      * properties (e.g. scaling, rotation).
      * @throws IOException If there is an error writing to the page contents.
      */
      public PDPageContentStream(PDDocument document, PDPage sourcePage, AppendMode appendContent,
      boolean compress, boolean resetContext) throws IOException


      Thus



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


      should make your code work as desired.



      Alternatively, if you want the image in the background, try



      PDPageContentStream contents = new PDPageContentStream(doc, page, AppendMode.PREPEND, true, true);


      Beware, though, in certain cases the image won't be visible in the background, e.g. if the existing content starts with an instruction to fill the whole page area in white. In such a case watermarks must be applied with some kind of transparency atop existing content.






      share|improve this answer

























        1












        1








        1







        Please also have a look at the JavaDocs and sources of the library you try to work with. You create a PDPageContentStream:



        PDPageContentStream contents = new PDPageContentStream(doc, page);


        This conductor is documented to overwrite all existing content streams of this page:



        /**
        * Create a new PDPage content stream. This constructor overwrites all existing content streams
        * of this page.
        *
        * @param document The document the page is part of.
        * @param sourcePage The page to write the contents to.
        * @throws IOException If there is an error writing to the page contents.
        */
        public PDPageContentStream(PDDocument document, PDPage sourcePage) throws IOException


        Thus, you have to use a different constructor which keeps the current page contents, e.g.



        /**
        * Create a new PDPage content stream.
        *
        * @param document The document the page is part of.
        * @param sourcePage The page to write the contents to.
        * @param appendContent Indicates whether content will be overwritten, appended or prepended.
        * @param compress Tell if the content stream should compress the page contents.
        * @param resetContext Tell if the graphic context should be reset. This is only relevant when
        * the appendContent parameter is set to @link AppendMode#APPEND. You should use this when
        * appending to an existing stream, because the existing stream may have changed graphic
        * properties (e.g. scaling, rotation).
        * @throws IOException If there is an error writing to the page contents.
        */
        public PDPageContentStream(PDDocument document, PDPage sourcePage, AppendMode appendContent,
        boolean compress, boolean resetContext) throws IOException


        Thus



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


        should make your code work as desired.



        Alternatively, if you want the image in the background, try



        PDPageContentStream contents = new PDPageContentStream(doc, page, AppendMode.PREPEND, true, true);


        Beware, though, in certain cases the image won't be visible in the background, e.g. if the existing content starts with an instruction to fill the whole page area in white. In such a case watermarks must be applied with some kind of transparency atop existing content.






        share|improve this answer













        Please also have a look at the JavaDocs and sources of the library you try to work with. You create a PDPageContentStream:



        PDPageContentStream contents = new PDPageContentStream(doc, page);


        This conductor is documented to overwrite all existing content streams of this page:



        /**
        * Create a new PDPage content stream. This constructor overwrites all existing content streams
        * of this page.
        *
        * @param document The document the page is part of.
        * @param sourcePage The page to write the contents to.
        * @throws IOException If there is an error writing to the page contents.
        */
        public PDPageContentStream(PDDocument document, PDPage sourcePage) throws IOException


        Thus, you have to use a different constructor which keeps the current page contents, e.g.



        /**
        * Create a new PDPage content stream.
        *
        * @param document The document the page is part of.
        * @param sourcePage The page to write the contents to.
        * @param appendContent Indicates whether content will be overwritten, appended or prepended.
        * @param compress Tell if the content stream should compress the page contents.
        * @param resetContext Tell if the graphic context should be reset. This is only relevant when
        * the appendContent parameter is set to @link AppendMode#APPEND. You should use this when
        * appending to an existing stream, because the existing stream may have changed graphic
        * properties (e.g. scaling, rotation).
        * @throws IOException If there is an error writing to the page contents.
        */
        public PDPageContentStream(PDDocument document, PDPage sourcePage, AppendMode appendContent,
        boolean compress, boolean resetContext) throws IOException


        Thus



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


        should make your code work as desired.



        Alternatively, if you want the image in the background, try



        PDPageContentStream contents = new PDPageContentStream(doc, page, AppendMode.PREPEND, true, true);


        Beware, though, in certain cases the image won't be visible in the background, e.g. if the existing content starts with an instruction to fill the whole page area in white. In such a case watermarks must be applied with some kind of transparency atop existing content.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 14 '18 at 5:28









        mklmkl

        54.5k1168146




        54.5k1168146





























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53290401%2fproblem-with-empty-page-when-using-apache-pdfbox-to-add-image-to-pdf%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Use pre created SQLite database for Android project in kotlin

            Darth Vader #20

            Ondo