我正在编写一个使用pdfbox库从头开始创建pdf的Java应用程序.
我需要在页面中放置一个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");
Run Code Online (Sandbox Code Playgroud)
当我运行代码时,它会成功终止,但是如果我使用Acrobat Reader打开生成的pdf文件,页面将完全为白色,并且图像不会放入其中.
而是将文本正确放置在页面中.
有关如何将我的图像放入pdf的任何提示?
chu*_*ubs 52
绝对将页面添加到文档中.你会想要这样做,但我也注意到如果你在PDJpeg之前创建PDPageContentStream,PDFBox将不会写出图像.没有解释为什么会这样,但如果你仔细观察ImageToPDF的来源就是他们所做的.在PDJpeg之后创建PDPageContentStream,它神奇地起作用.
...
PDJpeg img = new PDJpeg(document, in);
PDPageContentStream stream = new PDPageContentStream( doc, page );
...
Run Code Online (Sandbox Code Playgroud)