使用iText填充pdf表單
阿新 • • 發佈:2018-12-18
1、先用word只做好模板,另存為pdf格式,然後用pdf開啟,啟用表單編輯功能,設定好表單域。如下:
2、把模板放入專案中
3、jar包
<dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>5.5.9</version> </dependency> <dependency> <groupId>com.itextpdf.tool</groupId> <artifactId>xmlworker</artifactId> <version>5.5.9</version> </dependency> <dependency> <groupId>com.itextpdf</groupId> <artifactId>itext-asian</artifactId> <version>5.2.0</version> </dependency>
程式碼:
工具類::
public class GeneratePDFUtil { /** * @param response * @param filePath 生成檔案的路徑 * @param showFileName 顯示的檔名 * @throws IOException */ protected static void previewpdf(HttpServletResponse response, String filePath, String showFileName) throws IOException { File f = new File(filePath); if (!f.isFile() || !f.exists()) {// 檔案異常 throw new FileNotFoundException("檔案異常,請檢查檔案是否正確:" + filePath); } // 獲取檔案流 InputStream fis = new BufferedInputStream(new FileInputStream(filePath)); byte[] buffer = new byte[fis.available()]; fis.read(buffer); fis.close(); // 清空response response.reset(); // 設定response的Header response.setCharacterEncoding("UTF-8"); //response.setContentType("application/octet-stream;charset=UTF-8"); //response.addHeader("Content-Disposition", "attachment1;filename=" + new String(showFileName.getBytes("gb2312"), "ISO8859-1")); response.setContentType("application/pdf;charset=UTF-8"); // 下載檔名處理 response.addHeader("Content-Disposition", "inline;filename=" + new String(showFileName.getBytes("gb2312"), "ISO8859-1")); response.addHeader("Content-Length", "" + f.length()); // 檔案流處理 OutputStream toClient = new BufferedOutputStream(response.getOutputStream()); toClient.write(buffer); toClient.flush(); toClient.close(); //刪除臨時檔案 File file=new File(filePath); file.delete(); } /** * * @param templatePath 模板路徑 * @param newPDFPath 新檔案路徑 * @param map * @throws IOException */ public static void interviewReportPDF(HttpServletResponse response,String templatePath,String newPDFPath,Map<String, String> map,String showFileName) throws IOException { PdfReader reader; FileOutputStream out; ByteArrayOutputStream bos; PdfStamper stamper; try { out = new FileOutputStream(newPDFPath);// 輸出流 reader = new PdfReader(templatePath);// 讀取pdf模板 bos = new ByteArrayOutputStream(); stamper = new PdfStamper(reader, bos); AcroFields form = stamper.getAcroFields(); // 給表單新增中文字型 這裡採用系統字型。不設定的話,中文可能無法顯示 BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED); /*BaseFont bf = BaseFont.createFont(UtilPath.getRootPath() + "fonts/simsun.ttc,0", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);*/ form.addSubstitutionFont(bf); //遍歷map裝入資料 for (Entry<String, String> entry : map.entrySet()) { form.setField(entry.getKey(), entry.getValue()); } stamper.setFormFlattening(true);// 如果為false那麼生成的PDF檔案還能編輯,一定要設為true stamper.close(); Document doc = new Document(); PdfCopy copy = new PdfCopy(doc, out); doc.open(); PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), 1); copy.addPage(importPage); doc.close(); } catch (IOException e) { } catch (DocumentException e) { } //到頁面上進行展示 previewpdf(response,newPDFPath,showFileName); }
controller:
@RequestMapping(value = "", method = RequestMethod.POST) public void feeOrderTemplate(HttpServletRequest request,HttpServletResponse response,@RequestParam("orderId") String orderId) throws IOException { Map<String,String> map = new HashMap<String,String>(); /** * 把資訊放進map */ //模板路徑 String templatePath=request.getServletContext().getRealPath("/")+"static\\template\\order\\你的模板名字"; //生成檔案的路徑 String filePath=request.getServletContext().getRealPath("/")+"static\\template\\order\\"+System.currentTimeMillis()+".pdf"; GeneratePDFUtil.interviewReportPDF(response, templatePath, filePath, map,"展示時顯示的名字.pdf"); }
頁面:
function fyTemplate(id){
var myform = $("<form></form>");
myform.attr('method', 'post');
myform.attr('target', 'hiddenIframe');
myform.attr('action', "你的controller路徑?orderId="+id);
myform.appendTo('body').submit();
myform.remove();
}
<iframe id="hiddenIframe" height="0" width="0"></iframe>
加iframe是為了新跳一個頁面展示,而不是在原來的頁面直接跳