經過網上搜索大概有三種方式:PDF模板數據填充,html代碼轉換pdf,借用wkhtmltopdf工具
一 .PDF模板數據填充
1.新建word,在word中做出和表單一樣的布局的空表單,然后另存為pdf;
2.用pdf編輯工具,用准備表單這個工具在需要填充動態數據的地方設置文本框或圖像框,起好標簽名。
3.根據標簽名向pdf中插入數據,並將PDF導出在指定位置。
String rootPath="d:/";
String path=rootPath+"dzyjjsdjd.pdf"; System.out.println("電子文件移交與接收登記單模板位置:"+path); SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");//設置日期格式 String newPath=rootPath+df.format(new Date())+"dzyjjsdjd.pdf"; //讀入pdf表單 PdfReader reader = new PdfReader(path); //根據表單生成一個新的pdf PdfStamper ps = new PdfStamper(reader,new FileOutputStream(newPath)); //獲取pdf表單 AcroFields s = ps.getAcroFields(); //給表單添加中文字體 這里采用系統字體。不設置的話,中文可能無法顯示 BaseFont bf = BaseFont.createFont("C:/WINDOWS/Fonts/SIMSUN.TTC,1",BaseFont.IDENTITY_H, BaseFont.EMBEDDED); s.addSubstitutionFont(bf); //遍歷pdf表單表格,同時給表格賦值 Map<String,String> paraMap=getMapData(accept);//自己的數據,按模板中設置的表單標簽封裝進map for (String key : paraMap.keySet()) { if(key.equals("yz1")){//獲取標簽為yz1的pdf標簽,設置其值 String value = paraMap.get(key); tempImgPath1=rootPath+"yz1.png"; insertImage(ps, tempImgPath1,"yz1",s); //圖片插入后需要去除掉設置的這個圖片框,否則會遮當前插入的圖片 s.removeField("yz1"); }else{ String value = paraMap.get(key); s.setField(key, value); // 為字段賦值,注意字段名稱是區分大小寫的 } } ps.setFormFlattening(true); // 這句不能少 ps.close(); reader.close();
/** * 向pdf中插入圖片 * @param ps pdf對象 * @param img 需要插入的圖片路徑 * @param col 需要插入圖片的pdf字段標簽名 * @param s pdf字段 */ public void insertImage(PdfStamper ps, String img,String col,AcroFields s){ try{ List<AcroFields.FieldPosition> list = s.getFieldPositions(col); Rectangle signRect = list.get(0).position; Image image = Image.getInstance(img); PdfContentByte under = ps.getOverContent(1); //要插入圖片的頁數,現在只有1頁 float x = signRect.getLeft(); float y = signRect.getBottom(); System.out.println(x); System.out.println(y); image.setAbsolutePosition(x, y); image.scaleToFit(signRect.getWidth(), signRect.getHeight()); under.addImage(image); } catch (Exception e){ // TODO Auto-generated catch block e.printStackTrace(); } }
/** * 插入文本 * * @return * @author WangMeng * @date 2016年6月16日 */ public static void insertText(PdfStamper ps, AcroFields s) { List<AcroFields.FieldPosition> list = s.getFieldPositions("CONNECT_NAME"); Rectangle rect = list.get(0).position; PdfContentByte cb = ps.getOverContent(1); PdfPTable table = new PdfPTable(1); float tatalWidth = rect.getRight() - rect.getLeft() - 1; table.setTotalWidth(tatalWidth); PdfPCell cell = new PdfPCell(new Phrase(CreateChunk())); cell.setFixedHeight(rect.getTop() - rect.getBottom() - 1); cell.setBorderWidth(0); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setLeading(0, (float) 1.1); table.addCell(cell); table.writeSelectedRows(0, -1, rect.getLeft(), rect.getTop(), cb); }
第二種:將html代碼轉換為pdf
import java.io.ByteArrayInputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import com.itextpdf.text.Document; import com.itextpdf.text.PageSize; import com.itextpdf.text.pdf.PdfWriter; import com.itextpdf.tool.xml.XMLWorkerHelper; public class HtmlToPDF { public static void main(String[] args) { try { Document document = new Document(PageSize.LETTER); PdfWriter pdfWriter = PdfWriter.getInstance(document, new FileOutputStream("c://temp//testpdf.pdf")); document.open(); document.addAuthor("ysjiang"); document.addCreator("ysjiang"); document.addSubject("test"); document.addCreationDate(); document.addTitle("XHTML to PDF"); XMLWorkerHelper worker = XMLWorkerHelper.getInstance(); String str = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">" + "<html xmlns=\"http://www.w3.org/1999/xhtml\">" + "<head>" + "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />" + "<title>HTML 2 PDF</title>" + "<style type=\"text/css\">" + "<!--" + "body {" + " margin: 20px;" + "}" + "-->" + "</style>" + "</head>" + "<body>" + "<div style=\"width:90%; height:160px;\">多情浪漫的人,其實內心的情感是非常脆弱的,感情的末梢,有那么一點兒敏感,還有那么一點兒想入非非。所以和浪漫多情的人在一起,言語一定要斯文,說話不能像火炮,態度一定要溫柔、語氣也要婉轉。遇到對方的一個眼神,也許有些人並沒發現什么端倪,但是放在懂得浪漫的人身上,就會體會出萬種滋味,百般柔情來。" + "</div>" + "<hr/>" + "<table cellspacing=\"0\" cellpadding=\"0\" style=\"width:100%; border:1px;\">" + " <tr>" + " <td style=\"width:30%\">table中的中文顯示及換行" + " </td>" + " <td>多情浪漫的人,其實內心的情感是非常脆弱的,感情的末梢,有那么一點兒敏感,還有那么一點兒想入非非。所以和浪漫多情的人在一起,言語一定要斯文,說話不能像火炮,態度一定要溫柔、語氣也要婉轉。遇到對方的一個眼神,也許有些人並沒發現什么端倪,但是放在懂得浪漫的人身上,就會體會出萬種滋味,百般柔情來。" + " </td>" + " </tr>" + " <tr>" + " <td colspan=\"2\">" + " <img src=\"0.jpg\" />" + " </td>" + " </tr>" + "</table>" + "</body>" + "</html>"; // worker.parseXHtml(pdfWriter, document, new FileInputStream("C:\\tmp\\a.htm"), null, new AsianFontProvider()); String url="G:/workProject_ces/zjdzyjjsxt/WebRoot/module/receive/register/input.jsp?pid=4&sign=0&tagg=undo&workitemId=149982394754705&activityName=rk&returnReason=&activityId=receive&time=Mon Jul 17 2017 14:25:49 GMT+0800 (ä¸å½æ åæ¶é´)"; worker.parseXHtml(pdfWriter, document, new ByteArrayInputStream(str.getBytes()), null, new AsianFontProvider()); XMLWorkerHelper.getInstance().parseXHtml(pdfWriter, document, new FileInputStream(url)); document.close(); System.out.println("Done."); } catch (Exception e) { e.printStackTrace(); } } }
第三種參照http://blog.csdn.net/zhangkezhi_471885889/article/details/52184700,因為要借助外部工具,所以部署時候會稍微麻煩點,根據需要選自己的方式