Can't add an image to a pdf using PDFBox

后端 未结 3 1577
再見小時候
再見小時候 2020-12-10 10:45

I\'m writing a java app that creates a pdf from scratch using the pdfbox library.
I need to place a jpg image in one of the page.

I\'m using this code:



        
相关标签:
3条回答
  • 2020-12-10 10:55

    Looks like you're missing just a document.addPage(page) call.

    See also the ImageToPDF example class in PDFBox for some sample code.

    0 讨论(0)
  • 2020-12-10 10:55

    this is how default constructor for PDPageContentStream looks like:

    public PDPageContentStream(PDDocument document, PDPage sourcePage) throws IOException
    {
        this(document, sourcePage, AppendMode.OVERWRITE, true, false);
    }
    

    Problem is AppendMode.OVERWRITE for me using another constructor with parameter PDPageContentStream.AppendMode.APPEND resolved a problem

    For me this worked:

    PDPageContentStream contentStream =
            new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true, false);
    
    0 讨论(0)
  • 2020-12-10 11:09

    Definitely add the page to the document. You'll want to do that, but I've also noticed that PDFBox won't write out the image if you create the PDPageContentStream BEFORE the PDJpeg. It's unexplained why this is so, but if you look close at the source of ImageToPDF that's what they do. Create the PDPageContentStream after PDJpeg and it magically works.

    ...
    PDJpeg img = new PDJpeg(document, in);
    PDPageContentStream stream = new PDPageContentStream( doc, page );
    ...
    
    0 讨论(0)
提交回复
热议问题