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

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

问题描述:

下午好.我有一个 JAR 文件,我将一些图像作为资源附加到一个名为 logos 的文件夹中.由于安全限制,我被告知要这样做(我们不希望图像文件与 JAR 在同一文件夹中公开).我首先尝试加载这些图像,就好像它们是 File 对象一样,但这显然不起作用.我现在正在尝试使用 InputStream 将图像加载到所需的 PDImageXObject 中,但图像没有渲染到 PDF 中.这是我正在使用的代码片段:

Good afternoon. I have a JAR file to which I have attached some images as resources in a folder called 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). I first tried to load these images in as if they were a File object, but that obviously doesn't work. 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. 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);

请注意,我已验证资源是否正确加载,因为使用 logoFileAsStream.available() 会为各种徽标返回不同的值.运行此代码后,实际上并没有在 PDF 上绘制图像,并且在打开它时,会出现错误消息此页面上存在错误.Acrobat 可能无法正确显示页面.请联系创建 PDF 文档的人员以更正问题."出现.有人可以帮我弄清楚该代码片段/将我的图像作为资源从 JAR 加载的不同解决方案有什么问题吗?非常感谢.如果需要更多细节/澄清,请告诉我.

Note that I have verified that the resource is getting loaded in correctly, as using logoFileAsStream.available() returns a different value for various logos. 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." 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? Thanks so much. Let me know if more details are needed/clarification.

此 PDImageXObject 构造函数仅供内部 PDFBox 使用.你可以使用

This PDImageXObject constructor is for internal PDFBox use only. You can use

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

为了最大的灵活性,或者如果您知道它始终是一个 PNG 文件

for maximum flexibility, or if you know it is always a PNG file

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

不要忘记关闭 logoFileAsStream 和 contentStream.

don't forget to close logoFileAsStream and contentStream.