Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
317 views
in Technique[技术] by (71.8m points)

.net - How to continue field output on a second page?

I have generated a PDF from a template. The PDF has a field in the middle of it that is of variable length. I am trying to work it so that if the field's content overflows, then the program will use a second instance template as a second page and continue in the same field there. Is this possible?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...