IText7仅在新文档上创建窗体/窗口小部件
当运行此代码时,PdfDocument没有读取源,它可以正常工作。当我尝试从预制的pdf中读取时,它会停止创建窗体/窗口小部件,但仍按预期方式添加段落。没有错误给出。有谁明白为什么会发生这种情况?IText7仅在新文档上创建窗体/窗口小部件
这里是我运行代码:
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;
}
你会注意到两个变化:
- 我改变Y字段的偏移量(
525
而不是753
)。现在该字段被添加到页面的可见区域内。在您的代码中,该字段已添加,但不可见。 - 我通过添加
pdf.getPage(1)
作为addField()
方法的第二个参数来定义在哪个页面上需要添加字段。
以上是 IText7仅在新文档上创建窗体/窗口小部件 的全部内容, 来源链接: utcz.com/qa/261919.html