有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java展平PDF字段将删除格式设置

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

pdfs It's not edible any longer, but the formatting is also gone.

    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 Pro{}创建表单元素,并将PDF保存为test.pdf

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

问题是,我如何删除输入字段并将其展平,同时保持内容的风格,以及自动调整大小等更好的功能


共 (1) 个答案

  1. # 1 楼答案

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

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