有 Java 编程相关的问题?

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

java IText7仅在新文档上创建表单/小部件

在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;

    }
}

共 (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()方法的第二个参数来定义需要将字段添加到哪个页面