我有一个预定义的模板,我想创建表并将其添加到模板的第3页。是否可以这样做?使用itext创建新的pdf有很多选项,但我没有看到任何修改现有pdf并向其添加表的示例。代码示例将受到高度赞赏。
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();
}`
答案 0 :(得分:4)
您使用PdfStamper
。代码如下:
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();