1

当使用没有读取源的 PdfDocument 运行此代码时,它可以正常工作。当我尝试从预制的 pdf 中阅读时,它会停止创建表单/小部件,但仍会按预期添加段落。没有给出错误。有谁明白为什么会这样?

这是我正在运行的代码:

public class HelloWorld {

    public static final String DEST = "sampleOutput.pdf";
    public static final String SRC = "sample.pdf";
    public static void main(String args[]) throws IOException {
        File file = new File(DEST);

        new HelloWorld().createPdf(SRC, DEST);
    }

    public void createPdf(String src, String dest) throws IOException {
        //Initialize PDF reader and writer
        PdfReader reader = new PdfReader(src);
        PdfWriter writer = new PdfWriter(dest);

        //Initialize PDF document
        PdfDocument pdf = new PdfDocument(writer); //if i do (reader, writer) the widget isn't added to the first page anymore.

        // Initialize document
        Document document = new Document(pdf);

        HelloWorld.addAcroForm(pdf, document);

        //Close document
        document.close();
    }

    public static PdfAcroForm addAcroForm(PdfDocument pdf, Document doc) throws IOException {
        Paragraph title = new Paragraph("Test Form")
                .setTextAlignment(TextAlignment.CENTER)
                .setFontSize(16);
        doc.add(title);
        doc.add(new Paragraph("Full name:").setFontSize(12));

        //Add acroform
        PdfAcroForm form = PdfAcroForm.getAcroForm(doc.getPdfDocument(), true);
        //Create text field
        PdfTextFormField nameField = PdfFormField.createText(doc.getPdfDocument(),
                new Rectangle(99, 753, 425, 15), "name", "");

        form.addField(nameField);
        return form;

    }
}
4

1 回答 1

1

我像这样修改了您的代码:

public static PdfAcroForm addAcroForm(PdfDocument pdf, Document doc) throws IOException {
    Paragraph title = new Paragraph("Test Form")
            .setTextAlignment(TextAlignment.CENTER)
            .setFontSize(16);
    doc.add(title);
    doc.add(new Paragraph("Full name:").setFontSize(12));

    PdfAcroForm form = PdfAcroForm.getAcroForm(pdf, true);
    PdfTextFormField nameField = PdfFormField.createText(pdf,
            new Rectangle(99, 525, 425, 15), "name", "");
    form.addField(nameField, pdf.getPage(1));
    return form;
}

你会注意到两个变化:

  1. 我更改了字段的 Y 偏移量(525而不是753)。现在该字段已添加到页面的可见区域内。在您的代码中,该字段已添加,但不可见。
  2. 我通过添加pdf.getPage(1)作为该addField()方法的第二个参数来定义需要将字段添加到哪个页面。
于 2016-11-02T15:00:13.537 回答