簡體   English   中英

如何使用 Apache PDFBox 將圖像移動到 PDF 頁面的頂部?

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

我正在使用PDFBox在 Java 中生成報告。 我的要求之一是創建一個 PDF 文檔,該文檔在頁面頂部包含公司徽標。 我無法找到實現這一目標的方法。

我在 Java 類中有以下方法:

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 物理英寸。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM