如何使用 Apache PDFBox 将图像移动到 PDF 页面的顶部?

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

我正在使用 PDFBox 在 Java 中生成报告。我的要求之一是创建一个 PDF 文档,其中在页面顶部包含公司徽标。我找不到实现该目标的方法。

我在 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();
        }

    }

图像当前出现在 PDF 的底部。我知道我需要修改的行是 contentStream.drawImage(pdImage, 0, 0); 但我需要指定什么坐标才能显示在页面顶部?

通常,PDF 中页面的坐标系从左下角开始。所以用

contentStream.drawImage(pdImage, 0, 0);

此时您正在绘制图像。您可以使用

获取页面的边界
page.getMediaBox();

并使用它来定位您的图片,例如

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);

其中 PDF 文件通常将 72 磅指定为 1 物理英寸。