使用PDFBox渲染带有填充表单字段的文档适用于1.8.2,但不适用于2.0.2

时间:2016-08-02 15:21:25

标签: java forms pdf pdfbox

我的目标是打开PDF文档,填写一些表单字段,然后将其渲染为图像。我正在使用带有Java的PDFBox来完成它。我开始使用2.0.2版(最新版)并填写表单字段。当我保存它然后用PDF阅读器打开它时,表单字段有值。但是当我将它渲染到图像时,表单字段有黑色边框,里面没有文字。然后我用1.8.12尝试了相同的东西,它的工作原理。但是,我真的想使用2.x中的新功能。

  • PDF只有AcroForms,没有XFA(或者至少我认为是这样)。当我调用PDAcroForm.getXFA()时,它返回null。
  • 使用2.0.2,如果我使用setValue渲染某些内容,则渲染看起来会破碎。但是,使用Adobe Reader渲染填充的内容有效。这两种情况都使用1.8。
  • 使用2.0.2我尝试了PDAcroForm.refreshAppearances()和/或PDAcroForm.setNeedAppearances(true)的任意组合。 1.8中没有这些方法。

我用于使用1.8.12渲染的代码:

public class Main {
    public static void main(String[] args) throws Exception {
        PDDocument doc = PDDocument.loadNonSeq(new File("test.pdf"), null);
        doc.setAllSecurityToBeRemoved(true);
        PDDocumentCatalog cat = doc.getDocumentCatalog();
        PDAcroForm form = cat.getAcroForm();
        for (Object _field : form.getFields()) {
            PDField field = (PDField) _field;
            System.out.println(field.getFullyQualifiedName());
            field.setValue(field.getFullyQualifiedName());
        }

        List<PDPage> pdPages = doc.getDocumentCatalog().getAllPages();
        int page = 0;
        for (PDPage pdPage : pdPages) {
            ++page;
            BufferedImage bim = pdPage.convertToImage(BufferedImage.TYPE_INT_RGB, 96);
            ImageIOUtil.writeImage(bim, "rendered" + "-" + page + ".png", 96);
        }
        doc.close();
    }
}

我用于使用2.0.2渲染的代码:

public class Main {
    public static void main(String[] args) throws Exception {
        PDDocument doc = PDDocument.load(new File("test.pdf"));
        doc.setAllSecurityToBeRemoved(true);
        PDDocumentCatalog cat = doc.getDocumentCatalog();
        PDAcroForm form = cat.getAcroForm();
        for (PDField field : form.getFields()) {
            System.out.println(field.getFullyQualifiedName());
            if (field instanceof PDTextField) {
                field.setValue(field.getFullyQualifiedName());
            }
        }
        // Doesn't work with or without these
        form.setNeedAppearances(true);
        form.refreshAppearances();

        PDDocument renderDoc = doc;
        PDFRenderer pdfRenderer = new PDFRenderer(renderDoc);
        for (int page = 0; page < renderDoc.getNumberOfPages(); ++page) {
            BufferedImage bim = pdfRenderer.renderImageWithDPI(page, 96,     ImageType.RGB);
            ImageIOUtil.writeImage(bim, "rendered" + "-" + (page + 1) +     ".png", 96);
        }
    }
}

使用1.8.12正确呈现的版本:Correct rendering with 1.8.12

使用2.0.2呈现的错误版本:Bad version rendering with 2.0.2

1 个答案:

答案 0 :(得分:1)

这是PDFBox 2.0.2中的一个错误。它在2.0.4中得到解决,因此解决方案是将版本升级到最新版本。