我正在使用 PDFBox将图像写入pdf。该图像只是一个纯红色的矩形。
图像是:
我的代码是:
PDDocument doc = new PDDocument();
PDRectangle pageSize = new PDRectangle(CARD_WIDTH, CARD_HEIGHT);
PDPage page1 = new PDPage(pageSize);
doc.addPage(page1);
File imageFile = getRedImageFile();
PDXObjectImage pdImage = new PDPixelMap(doc, ImageIO.read(imageFile));
// write front image
PDPageContentStream contentStream = null;
try {
contentStream = new PDPageContentStream(doc, page1);
pdImage = parseImage(backImage, doc);
contentStream.drawXObject(pdImage, 0, 0, CARD_WIDTH / 2, CARD_HEIGHT / 2);
} finally {
if (contentStream != null) {
contentStream.close();
}
}
最终图像是:
看不清楚,放大再上传一张:
为什么会有这么奇怪的像素点?
最佳答案
这是由于内容流错误。您可能可以通过在写入图像后关闭然后再次打开流来绕过它,但这可能会导致更多错误(例如覆盖所有字体)。
我使用的解决方法是在每个页面开始时在页面右侧 50000 像素处放置一个占位符图像。由于此图像已损坏而不是其他图像,所以一切都很好。
关于java - 用PDFBox写图片到pdf,发现左上角有一些奇怪的像素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12914059/