简体   繁体   English

如何使用Itext创建表格并将其添加到预定义的pdf模板?

[英]How to create and add table to predefined pdf template using Itext?

I have a predefined Template and i want to create and add table to 3rd page of template. 我有一个预定义的模板,我想创建表格并将其添加到模板的第三页。 Is it possible to do so?There are lot of option for creating new pdf using itext but i haven't seen any example where modifying existing pdf and adding table to it is provided. 有很多选择可以使用itext创建新的pdf,但是我还没有看到提供修改现有pdf并为其添加表格的任何示例。 Code example will be highly appreciated. 代码示例将不胜感激。

    PdfReader reader = new PdfReader("BCC Statements-Template.pdf");
    FileOutputStream fileOutputStream = new FileOutputStream("test.pdf");
    try {   

        PdfStamper stamper= new PdfStamper(reader, fileOutputStream);           
        PdfContentByte overContentByte = stamper.getOverContent(3);
        PdfPTable pdfPTable = new PdfPTable(4);
         pdfPTable.setTotalWidth(40);
            //Create cells
            PdfPCell pdfPCell1 = new PdfPCell(new Paragraph("Cell 1"));
            PdfPCell pdfPCell2 = new PdfPCell(new Paragraph("Cell 2"));
            PdfPCell pdfPCell3 = new PdfPCell(new Paragraph("Cell 3"));
            PdfPCell pdfPCell4 = new PdfPCell(new Paragraph("Cell 4"));
            //Add cells to table
            pdfPTable.addCell(pdfPCell1);
            pdfPTable.addCell(pdfPCell2);
            pdfPTable.addCell(pdfPCell3);
            pdfPTable.addCell(pdfPCell4);
            pdfPTable.writeSelectedRows(1, 1, 110, 150, overContentByte);
            stamper.close();
        reader.close();
    } catch (DocumentException e) {
        e.printStackTrace();
    }`

You use PdfStamper for that. 为此,您可以使用PdfStamper The code goes like this: 代码如下:

PdfReader reader = new PdfReader(src);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
PdfContentByte canvas = stamper.getOverContent(1);
PdfPTable table = ...;
//add data to table
table.writeSelectedRows(... , canvas);
stamper.close();
reader.close();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM