PDFBox:调整大小时,PDJpeg会以错误的颜色绘制 - > Adobe Reader - > Windows XP& 7

时间:2013-04-03 14:19:39

标签: java swing pdf bufferedimage pdfbox

使用PDFBox创建PDF并向其绘制PDJpegs时,在将PDJpeg绘制为PDF之前调整PDJpeg的大小时,图像的颜色会发生变化/反转。此问题仅在Windows XP和Windows 7上可见,例如使用Adobe Reader。在Mac上预览或Windows 8中的新PDF预览版本不会受此影响。

示例:

Screenshot PDF in Adobe Reader
Same PDF in Mac Preview

这就是我在代码中所做的事情:

  • 创建PDDocument
  • 创建PDJpegs的HashMap(用于缓存目的):
    • 通过ImageIO.read()
    • 初始化的BufferedImage创建PDJpegs
    • 通过调用PDJpegs上的setHeight()和setWidth()来调整PDJpegs的大小
    • 将PDJpeg添加到HashMap
  • 创建PDPage并将其添加到PDDocument
  • 创建PDPageContentStream
  • 在PDPa​​ge上绘制一些PDJpegs
  • 关闭PDPageContentStream
  • 保存PDDocument
  • 关闭PDDocument

调整PDJpegs大小的方法:

private void preparePDFIconCache(List<AbstractDataItem> list) throws IOException {

    iconCache = new HashMap<String, PDJpeg>();

    for (AbstractDataItem item : list) {
        String iconResourcePath = "/com/graphics/icons/" + item.getIconName();
        URL iconURL = this.getClass().getResource(iconResourcePath);

        BufferedImage icon = null;
        if (iconURL != null) {

            icon = ImageIO.read(iconURL);

        } else {

            String myIconResourcePath = SettingsDataModel.getInstance().getMyIconsPath() + File.separator + item.getIconName();

            File iconFile = new File(myIconResourcePath);
            if (iconFile.exists()) {

                URL myIconURL = iconFile.toURI().toURL();

                if (myIconURL != null) {

                    icon = ImageIO.read(myIconURL);
                }
            }

        }
        if (icon != null) {

            PDJpeg pdfIcon = new PDJpeg(currentDocument, icon);

            pdfIcon.setHeight(iconWidthXHeight);
            pdfIcon.setWidth(iconWidthXHeight);

            iconCache.put(item.getIconName(), pdfIcon);
        }
    }
}

private void preparePDFIconCache(List<AbstractDataItem> list) throws IOException { iconCache = new HashMap<String, PDJpeg>(); for (AbstractDataItem item : list) { String iconResourcePath = "/com/graphics/icons/" + item.getIconName(); URL iconURL = this.getClass().getResource(iconResourcePath); BufferedImage icon = null; if (iconURL != null) { icon = ImageIO.read(iconURL); } else { String myIconResourcePath = SettingsDataModel.getInstance().getMyIconsPath() + File.separator + item.getIconName(); File iconFile = new File(myIconResourcePath); if (iconFile.exists()) { URL myIconURL = iconFile.toURI().toURL(); if (myIconURL != null) { icon = ImageIO.read(myIconURL); } } } if (icon != null) { PDJpeg pdfIcon = new PDJpeg(currentDocument, icon); pdfIcon.setHeight(iconWidthXHeight); pdfIcon.setWidth(iconWidthXHeight); iconCache.put(item.getIconName(), pdfIcon); } } }

如果在初始化PDJpegs之前调整了BufferedImages的大小,一切正常,但它们看起来并不那么尖锐。

有没有人有一个好的解决方案或遇到同样的问题?

1 个答案:

答案 0 :(得分:1)

使用PDPageContentStream绘制图像#drawXObject并在此方法中设置高度宽度解决了这个问题。