This will only work if you flatten the form. I've written a proof of concept where I have a PDF form src
that has a field named "body"
:
public void manipulatePdf(String src, String dest) throws DocumentException, IOException {
PdfReader reader = new PdfReader(src);
Rectangle pagesize = reader.getPageSize(1);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
Paragraph p = new Paragraph();
p.add(new Chunk("Hello "));
p.add(new Chunk("World", new Font(FontFamily.HELVETICA, 12, Font.BOLD)));
AcroFields form = stamper.getAcroFields();
Rectangle rect = form.getFieldPositions("body").get(0).position;
int status;
PdfImportedPage newPage = null;
ColumnText column = new ColumnText(stamper.getOverContent(1));
column.setSimpleColumn(rect);
int pagecount = 1;
for (int i = 0; i < 100; ) {
i++;
column.addElement(new Paragraph("Hello " + i));
column.addElement(p);
status = column.go();
if (ColumnText.hasMoreText(status)) {
newPage = loadPage(newPage, reader, stamper);
triggerNewPage(stamper, pagesize, newPage, column, rect, ++pagecount);
}
}
stamper.setFormFlattening(true);
stamper.close();
reader.close();
}
public PdfImportedPage loadPage(PdfImportedPage page, PdfReader reader, PdfStamper stamper) {
if (page == null) {
return stamper.getImportedPage(reader, 1);
}
return page;
}
public void triggerNewPage(PdfStamper stamper, Rectangle pagesize, PdfImportedPage page, ColumnText column, Rectangle rect, int pagecount) throws DocumentException {
stamper.insertPage(pagecount, pagesize);
PdfContentByte canvas = stamper.getOverContent(pagecount);
canvas.addTemplate(page, 0, 0);
column.setCanvas(canvas);
column.setSimpleColumn(rect);
column.go();
}
As you can see, we create a PdfImportedPage
instance and we insert a new page with this page as background. We add the content at the position defined by the field using ColumnText
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…