【问题标题】:Flattening PDF fields removes formatting拼合 PDF 字段会删除格式
【发布时间】:2019-08-20 08:53:50
【问题描述】:

我尝试在包含富文本的 pdf 中展平表单字段 (PDAcroForm.flatten())。 这样做时,格式(粗体、斜体、颜色、大小)会丢失。

已经不能吃了,不过格式也没有了。

    String inputFileName = "test.pdf";

    String val = "<?xml version=\"1.0\"?>"
            + "<body xmlns=\"http://www.w3.org/1999/xhtml\">"
            +   "<p style=\"color:#FF0000;font-size:8pt;\">"
            +       "<i>Small</i> <b>Red</b>&#13;"
            +   "</p>"
            +   "<p style=\"color:#00FF00;font-size:20pt;\">"
            +       "<i>Big</i> <b>Green</b>&#13;"
            +   "</p>"
            + "</body>";
    String valNoFormat = "Small Red\rBig Green\r";

    PDDocument pdf_document = PDDocument.load(new File(inputFileName));
    PDAcroForm acroForm = pdf_document.getDocumentCatalog().getAcroForm();
    PDTextField acroField = (PDTextField)acroForm.getField("example_field_number_one");

    acroField.setValue(valNoFormat);
    acroField.setRichTextValue(val);

    acroForm.setNeedAppearances(true);
    pdf_document.save(new File("output01.pdf"));

    List<PDField> the_fields = new ArrayList<PDField>();
    for (PDField field: pdf_document.getDocumentCatalog().getAcroForm().getFieldTree()) {
        the_fields.add(field);
    }
    System.out.println("Flattening fields: " + Arrays.stream(the_fields.toArray()).map(field -> ((PDField)field).getFullyQualifiedName()).collect(Collectors.joining(", ","[","]")));
    acroForm.setNeedAppearances(true);
    pdf_document.getDocumentCatalog().getAcroForm().flatten(the_fields, true);
    pdf_document.save(new File("output02.pdf"));

通过表单菜单使用Adobe Acrobat Pro10.1.1 创建该表单元素,并将pdf 保存为test.pdf

为了完整起见,我在 github 上上传了所有内容:

问题是,如何删除输入字段并将其展平,同时保持内容的样式以及字段中的自动大小等首选功能?

【问题讨论】:

  • PDFBox 不支持富文本,所以你会得到“便宜”的外观。
  • @TilmanHausherr 是否有任何可行的解决方法和/或项目?或者我可以贡献的任何已经完成的工作?
  • 不在 PDFBox 上...您可以查看 openhtmltopdf 项目 (github.com/danfickle/openhtmltopdf),然后尝试使用该代码填充外观流。但这不会在几分钟内完成。

标签: java pdf pdfbox acrofields flatten-pdf


【解决方案1】:

也许删除可编辑状态就足够了:

for (PDField field: pdf_document.getDocumentCatalog().getAcroForm().getFieldTree()) {
    field.setReadOnly(true);
}

【讨论】:

  • 似乎字段中的格式不会被所有查看器显示,即浏览器内置的。
  • 例如在 Chrome 的 pdf 查看器中,output01.pdf 看起来像 output02.pdf。没有颜色,也没有样式。
  • Maybe it suffices to remove the editable state - 不,它没有。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-25
  • 2016-04-02
相关资源
最近更新 更多