使用 OpenOffice 和 iText 生成 PDF
此文譯自這里。
之前我接到一個使用模板來動態創建 PDF 文檔的任務,最終選擇了 iText 和 OpenOffice Draw 來生成模板化的 PDF。
下面是介紹如何使用 OpenOffice Draw 創建 PDF 表單
Save PDF to folder where you have your program or just change path for input source in program
然后使用以下代碼通過 iText 來填充 PDF 中的變量
package com.linkwithweb.reports; import java.io.ByteArrayOutputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import com.lowagie.text.DocumentException; import com.lowagie.text.pdf.PdfReader; import com.lowagie.text.pdf.PdfStamper; /** * @author Ashwin Kumar * */ public class ITextStamperSample { /** * @param args * @throws IOException * @throws DocumentException */ public static void main(String[] args) throws IOException, DocumentException { // createSamplePDF(); generateAshwinFriends(); } /** * */ private static void generateAshwinFriends() throws IOException, FileNotFoundException, DocumentException { PdfReader pdfTemplate = new PdfReader("mytemplate.pdf"); FileOutputStream fileOutputStream = new FileOutputStream("test.pdf"); ByteArrayOutputStream out = new ByteArrayOutputStream(); PdfStamper stamper = new PdfStamper(pdfTemplate, fileOutputStream); stamper.setFormFlattening(true); stamper.getAcroFields().setField("name", "Ashwin Kumar"); stamper.getAcroFields().setField("id", "1\n2\n3\n"); stamper.getAcroFields().setField("friendname", "kumar\nsirisha\nsuresh\n"); stamper.getAcroFields().setField("relation", "self\nwife\nfriend\n"); stamper.close(); pdfTemplate.close(); } }
接下來是 pom.xml
4.0.0 com.linkwithweb.reports ReportTemplateTutorial 0.0.1-SNAPSHOT ReportTemplateTutorial ReportTemplateTutorial com.lowagie itext 2.1.7
最終生成 test.pdf 如下
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!