Search code examples
javapdfbox

How to move image to the top of the PDF page using Apache PDFBox?


I am using PDFBox to generate reports in Java. One of my requirements is to create a PDF document which contains the company logo at the top of the page. I am not able to find the way to accomplish that.

I have the following method in a Java class:

public void createPdf() {   

        PDDocument document = null;

        PDPage page = null;

        ServletContext servletContext = (ServletContext) FacesContext
                .getCurrentInstance().getExternalContext().getContext();

        try {

            File f = new File("Afiliado_2.pdf");

            if (f.exists() && !f.isDirectory()) {
                document = PDDocument.load(new File("Afiliado_2.pdf"));

                page = document.getPage(0);
            } else {

                document = new PDDocument();

                page = new PDPage();

                document.addPage(page);
            }

            PDImageXObject pdImage = PDImageXObject.createFromFile(
                    servletContext.getRealPath("/resources/images/logo.jpg"),
                    document);

            PDPageContentStream contentStream = new PDPageContentStream(
                    document, page, AppendMode.APPEND, true);


            contentStream.drawImage(pdImage, 0, 0);

            // Make sure that the content stream is closed:
            contentStream.close();

            // Save the results and ensure that the document is properly closed:
            document.save("Afiliado_2.pdf");
            document.close();

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

The image is currently appearing in the bottom of the PDF. I know the line I need to modify is contentStream.drawImage(pdImage, 0, 0); but what coordinates do I need to specify so that is appears in the top of the page?


Solution

  • Typically the coordinate system for a page in PDF starts at the lower left corner. So with

    contentStream.drawImage(pdImage, 0, 0);
    

    you are drawing your image at that point. You can get the boundaries of your page using

    page.getMediaBox();
    

    and use that to position your image e.g.

    PDRectangle mediaBox = page.getMediaBox();
    
    // draw with the starting point 1 inch to the left
    // and 2 inch from the top of the page
    contentStream.drawImage(pdImage, 72, mediaBox.getHeight() - 2 * 72);
    

    where PDF files normally specify 72 points to 1 physical inch.