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

标签 java pdf pdf-generation 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;

    }
}

最佳答案

我这样修改了你的代码:

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

关于java - IText7 仅在新文档上创建表单/小部件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40369160/

相关文章:

java - 如何为 PDFPTable 中的 PDF 单元定义不同的字体样式

java - 检查所有订单的运行时间是多少?

java - 将 Ant builder 集成到 Eclipse 中 : Relative paths for refresh scope working set

python - 表格-py ImportError : cannot import name 'read_pdf'

forms - 从PDF创建可填充的PDF

pdf - 分离 PDF 文件中的图层

python - Reportlab PDF版本生成问题

java - 为什么 java.lang.Runtime 是单例的?单例要求?

Java odftoolkit,如何将从纯字符串创建的节点添加到odf文档中

javascript - 在同一浏览器的新标签页中阅读 PDF 文件