itext实现pdf模板生成报表
思路很简单:定义pdf表单作为模板,调用itext api填充表单并输出报表。
由于比较简单,就不多描述,直接贴上Demo代码。
1 package com.itextpdf; 2 3 import java.io.ByteArrayOutputStream; 4 import java.io.FileOutputStream; 5 import java.io.IOException; 6 import java.io.OutputStream; 7 8 import com.itextpdf.text.Document; 9 import com.itextpdf.text.DocumentException; 10 import com.itextpdf.text.pdf.AcroFields; 11 import com.itextpdf.text.pdf.PdfCopy; 12 import com.itextpdf.text.pdf.PdfPTable; 13 import com.itextpdf.text.pdf.PdfReader; 14 import com.itextpdf.text.pdf.PdfStamper; 15 import com.itextpdf.text.pdf.PdfWriter; 16 17 public class Test { 18 19 public static void main(String[] args) throws DocumentException, IOException { 20 //填充表单 21 PdfReader reader = new PdfReader("c:/tmpl.pdf"); 22 ByteArrayOutputStream tempBaos = new ByteArrayOutputStream(); 23 PdfStamper stamp = new PdfStamper(reader, tempBaos); 24 AcroFields form = stamp.getAcroFields(); 25 fillForm(form); 26 stamp.setFormFlattening(true); 27 stamp.close(); 28 29 //可能除了输出模板外,还需要加入其它元素。 30 int totalPage = 1; 31 Document detailDoc = new Document(reader.getPageSize(1)); 32 ByteArrayOutputStream detaialBaos = new ByteArrayOutputStream(); 33 PdfWriter writer = PdfWriter.getInstance(detailDoc, detaialBaos); 34 detailDoc.open(); 35 PdfPTable pTable = genOtherTable(); 36 detailDoc.newPage(); 37 detailDoc.add(pTable); 38 detailDoc.close(); 39 totalPage += writer.getPageNumber() - 1; 40 41 // 合并模板与其它页,并生成最后报表 42 OutputStream outputStream = new FileOutputStream("c:/result.pdf"); 43 Document doc = new Document(reader.getPageSize(1)); 44 PdfCopy copy = new PdfCopy(doc, outputStream); 45 doc.open(); 46 doc.newPage(); 47 copy.addPage(copy.getImportedPage(new PdfReader(tempBaos.toByteArray()), 1)); 48 doc.resetPageCount(); 49 50 for (int i = 1; i <= totalPage - 1; i++) { 51 doc.newPage(); 52 copy.addPage(copy.getImportedPage(new PdfReader(detaialBaos.toByteArray()), i)); 53 doc.resetPageCount(); 54 } 55 56 doc.close(); 57 } 58 59 private static PdfPTable genOtherTable() { 60 PdfPTable table = new PdfPTable(2); 61 table.addCell("11111111"); 62 table.addCell("22222222"); 63 64 return table; 65 } 66 67 private static void fillForm(AcroFields form) throws IOException, 68 DocumentException { 69 form.setField("name", "jeffreyzhang"); 70 form.setField("sex", "boy"); 71 72 } 73 74 }