How to exactly position an Image inside an existing PDF page using PDFBox?

NiTiN picture NiTiN · Feb 17, 2012 · Viewed 21k times · Source

I am able to insert an Image inside an existing pdf document, but the problem is,

  1. The image is placed at the bottom of the page
  2. The page becomes white with the newly added text showing on it.

I am using following code.

List<PDPage> pages = pdDoc.getDocumentCatalog().getAllPages();

if(pages.size() > 0){
    PDJpeg img = new PDJpeg(pdDoc, in);
    PDPageContentStream stream = new PDPageContentStream(pdDoc,pages.get(0));
    stream.drawImage(img, 60, 60);
    stream.close();
}

I want the image on the first page.

Answer

ipavlic picture ipavlic · Feb 23, 2012

PDFBox is a low-level library to work with PDF files. You are responsible for more high-level features. So in this example, you are placing your image at (60, 60) starting from lower-left corner of your document. That is what stream.drawImage(img, 60, 60); does.

If you want to move your image somewhere else, you have to calculate and provide the wanted location (perhaps from dimensions obtained with page.findCropBox(), or manually input your location).

As for the text, PDF document elements are absolutely positioned. There are no low-level capabilities for re-flowing text, floating or something similar. If you write your text on top of your image, it will be written on top of your image.

Finally, for your page becoming white -- you are creating a new content stream and so overwriting the original one for your page. You should be appending to the already available stream.

The relevant line is:

PDPageContentStream stream = new PDPageContentStream( pdDoc, pages.get(0));

What you should do is call it like this:

PDPageContentStream stream = new PDPageContentStream( pdDoc, pages.get(0), true, true);

The first true is whether to append content, and the final true (not critical here) is whether to compress the stream.

Take a look at AddImageToPDF sample available from PDFBox sources.