簡體   English   中英

無法使用 PDFBox 將圖像添加到 pdf

[英]Can't add an image to a pdf using PDFBox

我正在編寫一個 Java 應用程序,它使用 pdfbox 庫從頭開始創建 pdf。
我需要在其中一個頁面中放置一個 jpg 圖像。

我正在使用此代碼:

PDDocument document = new PDDocument();
PDPage page = new PDPage(PDPage.PAGE_SIZE_A4);
document.addPage(page); 
PDPageContentStream contentStream = new PDPageContentStream(document, page);

/* ... */ 
/* code to add some text to the page */
/* ... */

InputStream in = new FileInputStream(new File("c:/myimg.jpg"));
PDJpeg img = new PDJpeg(document, in);
contentStream.drawImage(img, 100, 700);
contentStream.close();
document.save("c:/mydoc.pdf");

當我運行代碼時,它成功終止,但是如果我使用 Acrobat Reader 打開生成的 pdf 文件,頁面完全是白色的,並且圖像沒有放置在其中。
而是將文本正確放置在頁面中。

關於如何將我的圖像放入 pdf 的任何提示?

絕對將頁面添加到文檔中。 你會想要這樣做,但我也注意到如果你在 PDJpeg 之前創建 PDPageContentStream,PDFBox 不會寫出圖像。 無法解釋為什么會這樣,但是如果您仔細查看 ImageToPDF 的來源,他們就是這樣做的。 在 PDJpeg 之后創建 PDPageContentStream 並且它神奇地工作。

...
PDJpeg img = new PDJpeg(document, in);
PDPageContentStream stream = new PDPageContentStream( doc, page );
...

看起來您只缺少一個document.addPage(page)調用。

有關一些示例代碼,另請參閱 PDFBox 中的ImageToPDF示例類。

這是PDPageContentStream 的默認構造函數的樣子:

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

問題是 AppendMode.OVERWRITE 對我來說使用另一個帶有參數PDPageContentStream.AppendMode.APPEND 的構造函數解決了一個問題

對我來說這有效:

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

暫無
暫無

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

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