简体   繁体   English

PDFBox:将图像从 JAR 资源加载到 PDF 中

[英]PDFBox: Loading an Image Into PDF From a JAR Resource

Good afternoon.下午好。 I have a JAR file to which I have attached some images as resources in a folder called logos.我有一个 JAR 文件,我将一些图像作为资源附加到一个名为 logos 的文件夹中。 I am being told to do this due to security restrictions (we don't want the image files to be exposed in the same folder as the JAR).由于安全限制,我被告知要这样做(我们不希望图像文件与 JAR 在同一文件夹中公开)。 I first tried to load these images in as if they were a File object, but that obviously doesn't work.我首先尝试加载这些图像,就好像它们是 File 对象一样,但这显然不起作用。 I am now trying to use an InputStream to load the image into the required PDImageXObject, but the images are not rendering into the PDF.我现在正在尝试使用 InputStream 将图像加载到所需的 PDImageXObject 中,但图像没有渲染到 PDF 中。 Here is a snippet of the code which I am using:这是我正在使用的代码片段:

String logoName = "aLogoName.png";
PDDocument document = new PDDocument(); 

// the variable "generator" is an object used for operations in generating the PDF
InputStream logoFileAsStream = generator.getClass().getResourceAsStream("/" + logoName);
PDStream logoStream = new PDStream(document, logoFileAsStream);
PDImageXObject logoImage = new PDImageXObject(logoStream, new PDResources());

PDPage page = new PDPage(new PDRectangle(PDRectangle.A4.getHeight(), PDRectangle.A4.getWidth()));
document.addPage(page);
PDPageContentStream contentStream = new PDPageContentStream(document, page);
contentStream.drawImage(logoImage, 500, 100);

Note that I have verified that the resource is getting loaded in correctly, as using logoFileAsStream.available() returns a different value for various logos.请注意,我已验证资源是否正确加载,因为使用 logoFileAsStream.available() 会为各种徽标返回不同的值。 After running this code, the image does not actually get drawn on the PDF, and upon opening it, the error message "An error exists on this page. Acrobat may not display the page correctly. Please contact the person who created the PDF document to correct the problem."运行此代码后,实际上并没有在 PDF 上绘制图像,并且在打开它时,出现错误消息“此页面上存在错误。Acrobat 可能无法正确显示该页面。请联系创建 PDF 文档的人员以纠正问题。” appears.出现。 Could someone please help me figure what's wrong with that code snippet/a different solution to load my images in as a resource from the JAR?有人可以帮我弄清楚该代码片段/将我的图像作为资源从 JAR 加载的不同解决方案有什么问题吗? Thanks so much.非常感谢。 Let me know if more details are needed/clarification.让我知道是否需要更多细节/澄清。

This PDImageXObject constructor is for internal PDFBox use only.此 PDImageXObject 构造函数仅供内部 PDFBox 使用。 You can use您可以使用

PDImageXObject.createFromByteArray(document, IOUtils.toByteArray(logoFileAsStream), logoName /* optional, can be null */)

for maximum flexibility, or if you know it is always a PNG file以获得最大的灵活性,或者如果您知道它始终是一个 PNG 文件

LosslessFactory.createFromImage(document, ImageIO.read(logoFileAsStream))

don't forget to close logoFileAsStream and contentStream.不要忘记关闭 logoFileAsStream 和 contentStream。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM