PDF笔记(二):Itext 实际项目案例

一、PDF打印的思路:

(一)、输出生成: PDFPractise.java

[java]  view plain  copy
  1. package pdf.practise;  
  2.   
  3. import java.io.FileOutputStream;  
  4. import java.io.IOException;  
  5.   
  6. import com.itextpdf.text.BaseColor;  
  7. import com.itextpdf.text.Chunk;  
  8. import com.itextpdf.text.Document;  
  9. import com.itextpdf.text.DocumentException;  
  10. import com.itextpdf.text.Element;  
  11. import com.itextpdf.text.Font;  
  12. import com.itextpdf.text.Image;  
  13. import com.itextpdf.text.PageSize;  
  14. import com.itextpdf.text.Paragraph;  
  15. import com.itextpdf.text.Phrase;  
  16. import com.itextpdf.text.Rectangle;  
  17. import com.itextpdf.text.pdf.BaseFont;  
  18. import com.itextpdf.text.pdf.PdfPCell;  
  19. import com.itextpdf.text.pdf.PdfPTable;  
  20. import com.itextpdf.text.pdf.PdfWriter;  
  21.   
  22. /** 
  23.  *  
  24.  * @Title: 单纯输出PDF报表 
  25.  * @Description: 
  26.  * @Copyright: Copyright (c) 2014 
  27.  * @Company: SinoSoft 
  28.  *  
  29.  * @author: ShaoMin 
  30.  * @version: 1.0 
  31.  * @CreateDate:Nov 5, 2014 
  32.  */  
  33. public class PDFPractise {  
  34.   
  35.     /** 
  36.      * @author ShaoMin 
  37.      * @param args 
  38.      */  
  39.     public static void main(String[] args) {  
  40.   
  41.         PDFPractise tPDFPractise = new PDFPractise();  
  42.         try {  
  43.             tPDFPractise.createPdfFile();  
  44.   
  45.             // tPDFPractise.createPDFFile();  
  46.   
  47.         } catch (Exception e) {  
  48.             e.printStackTrace();  
  49.         }  
  50.     }  
  51.   
  52.     /** 
  53.      * 创建PDF 
  54.      *  
  55.      * @author ShaoMin 
  56.      * @throws Exception 
  57.      */  
  58.     public void createPdfFile() throws Exception {  
  59.         Document doc = new Document();  
  60.         FileOutputStream out = new FileOutputStream("temp/pdf/practisePdfFile.pdf");  
  61.         PdfWriter.getInstance(doc, out);  
  62.         doc.open();  
  63.   
  64.         BaseFont bfChinese = BaseFont.createFont("STSongStd-Light""UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);  
  65.         Font titleFont = new Font(bfChinese, 16, Font.BOLD);// 标题  
  66.         Font tableTitleFont = new Font(bfChinese, 12, Font.BOLD);// 表格标题  
  67.         Font conyentFont = new Font(bfChinese, 12, Font.NORMAL);// 内容  
  68.   
  69.         Paragraph title = new Paragraph("受理材料收取凭证", titleFont);  
  70.         title.setAlignment(Rectangle.ALIGN_CENTER);// 居中  
  71.         doc.add(title);  
  72.   
  73.         StringBuffer strBuff = new StringBuffer();  
  74.         strBuff.append("兹收到客户  " + "SAM-SHO");  
  75.         strBuff.append("(先生/女士)提交的保单号为    " + "123456789009876");  
  76.         strBuff.append("     的申请材料,共   " + " 2 " + "  张保单。");  
  77.   
  78.         Paragraph content = new Paragraph(strBuff.toString(), conyentFont);  
  79.         content.setAlignment(Rectangle.ALIGN_JUSTIFIED);  
  80.         content.setFirstLineIndent(15f);// 首行缩进  
  81.         content.setSpacingBefore(30f);// 上留白  
  82.         doc.add(content);  
  83.   
  84.         String cont2 = "申请保全项目    " + " CM-退保";  
  85.         content = new Paragraph(cont2, conyentFont);  
  86.         content.setAlignment(Rectangle.ALIGN_JUSTIFIED);  
  87.         content.setFirstLineIndent(15f);// 首行缩进  
  88.         content.setSpacingBefore(15f);// 上留白  
  89.         doc.add(content);  
  90.   
  91.         String cont3 = "所提供材料明细如下:";  
  92.         content = new Paragraph(cont3, conyentFont);  
  93.         content.setAlignment(Rectangle.ALIGN_JUSTIFIED);  
  94.         content.setFirstLineIndent(15f);// 首行缩进  
  95.         content.setSpacingBefore(15f);// 上留白  
  96.         content.setSpacingAfter(15f);// 下留白  
  97.         doc.add(content);  
  98.   
  99.         // 表格的处理是难点,特别是表格的跨行跨列  
  100.         // 可以使用跨行也可以使用表格嵌套  
  101.         int tCol = 5;  
  102.         PdfPTable table = new PdfPTable(tCol);  
  103.         table.setHorizontalAlignment(Element.ALIGN_LEFT);  
  104.         table.setTotalWidth(500f);  
  105.         table.setWidths(new float[] { 0.4f, 0.25f, 0.25f, 0.25f, 0.25f });  
  106.         table.setWidthPercentage(100);  
  107.         table.setLockedWidth(true);  
  108.   
  109.         String strTableTitle = "申请材料名称";  
  110.         Paragraph tableTitle = new Paragraph(strTableTitle, tableTitleFont);  
  111.         PdfPCell cell = new PdfPCell(tableTitle);  
  112.         cell.setHorizontalAlignment(Element.ALIGN_CENTER);// 水平居中  
  113.         cell.setVerticalAlignment(Element.ALIGN_MIDDLE);// 垂直居中  
  114.         cell.setRowspan(2);// 跨2行  
  115.         table.addCell(cell);  
  116.   
  117.         strTableTitle = "申请材料类型";  
  118.         tableTitle = new Paragraph(strTableTitle, tableTitleFont);  
  119.         cell = new PdfPCell(tableTitle);  
  120.         cell.setHorizontalAlignment(Element.ALIGN_CENTER);// 水平居中  
  121.         cell.setVerticalAlignment(Element.ALIGN_MIDDLE);// 垂直居中  
  122.         cell.setColspan(2);// 跨2列  
  123.         table.addCell(cell);  
  124.   
  125.         strTableTitle = "收取页数/份数";  
  126.         tableTitle = new Paragraph(strTableTitle, tableTitleFont);  
  127.         cell = new PdfPCell(tableTitle);  
  128.         cell.setHorizontalAlignment(Element.ALIGN_CENTER);// 水平居中  
  129.         cell.setVerticalAlignment(Element.ALIGN_MIDDLE);// 垂直居中  
  130.         cell.setRowspan(2);// 跨2行  
  131.         table.addCell(cell);  
  132.   
  133.         strTableTitle = "备注";  
  134.         tableTitle = new Paragraph(strTableTitle, tableTitleFont);  
  135.         cell = new PdfPCell(tableTitle);  
  136.         cell.setHorizontalAlignment(Element.ALIGN_CENTER);// 水平居中  
  137.         cell.setVerticalAlignment(Element.ALIGN_MIDDLE);// 垂直居中  
  138.         cell.setRowspan(2);// 跨2行  
  139.         table.addCell(cell);  
  140.   
  141.         // 这边属于第二行的表格  
  142.         // 思路上,这点很关键  
  143.         strTableTitle = "原件";  
  144.         tableTitle = new Paragraph(strTableTitle, tableTitleFont);  
  145.         cell = new PdfPCell(tableTitle);  
  146.         cell.setHorizontalAlignment(Element.ALIGN_CENTER);// 水平居中  
  147.         cell.setVerticalAlignment(Element.ALIGN_MIDDLE);// 垂直居中  
  148.         table.addCell(cell);  
  149.   
  150.         strTableTitle = "复印件";  
  151.         tableTitle = new Paragraph(strTableTitle, tableTitleFont);  
  152.         cell = new PdfPCell(tableTitle);  
  153.         cell.setHorizontalAlignment(Element.ALIGN_CENTER);// 水平居中  
  154.         cell.setVerticalAlignment(Element.ALIGN_MIDDLE);// 垂直居中  
  155.         table.addCell(cell);  
  156.   
  157.         String[] arrTitle = { "保险合同""保险合同收据或发票""保单贷款申请书""保全变更申请书""被保险人变更清单""健康及财务告知""授权委托书""投保人身份证件""被保险人身份证件""身故受益人身份证件""受托人身份证件""投保人账号""被保险人/监护人账号 ""生存证明""关系证明 ",  
  158.                 "其他受理材料 " };  
  159.         int tRow = arrTitle.length;  
  160.   
  161.         for (int i = 0; i < tRow; i++) {  
  162.             for (int j = 0; j < tCol; j++) {  
  163.                 if (j == 0) {  
  164.                     // 左侧标题  
  165.                     strTableTitle = arrTitle[i];  
  166.                     tableTitle = new Paragraph(strTableTitle, conyentFont);  
  167.                     cell = new PdfPCell(tableTitle);  
  168.                     cell.setHorizontalAlignment(Element.ALIGN_LEFT);// 水平居中  
  169.                     cell.setVerticalAlignment(Element.ALIGN_MIDDLE);// 垂直居中  
  170.                     table.addCell(cell);  
  171.                 } else {  
  172.                     strTableTitle = i + "--" + j;  
  173.                     tableTitle = new Paragraph(strTableTitle, conyentFont);  
  174.                     cell = new PdfPCell(tableTitle);  
  175.                     cell.setHorizontalAlignment(Element.ALIGN_CENTER);// 水平居中  
  176.                     cell.setVerticalAlignment(Element.ALIGN_MIDDLE);// 垂直居中  
  177.                     table.addCell(cell);  
  178.                 }  
  179.             }  
  180.         }  
  181.         table.setSpacingAfter(15f);// 下留白  
  182.         doc.add(table);  
  183.   
  184.         // 所有的都要指定中文,不然显示不出来  
  185.         // Phrase没有位置的操作,但是空格会被保留  
  186.         // 也可以使用表格处理,隐藏边框即可  
  187.         Phrase tPhrase = new Phrase("    申请人:                                     " + "                                         " + "                                         " + "保全试算金额:",  
  188.                 conyentFont);  
  189.         Paragraph tParagraph = new Paragraph(tPhrase);  
  190.         doc.add(tParagraph);  
  191.   
  192.         // 尾部表格处理  
  193.         PdfPTable footTable = new PdfPTable(2);  
  194.         footTable.setTotalWidth(760f);  
  195.         footTable.setWidths(new float[] { 4.6f, 1f });  
  196.         footTable.setHorizontalAlignment(Element.ALIGN_LEFT);  
  197.   
  198.         strTableTitle = "   申请日期:";  
  199.         tableTitle = new Paragraph(strTableTitle, conyentFont);  
  200.         cell = new PdfPCell(tableTitle);  
  201.         cell.setHorizontalAlignment(Element.ALIGN_LEFT);// 水平居中  
  202.         cell.setVerticalAlignment(Element.ALIGN_MIDDLE);// 垂直居中  
  203.         cell.setBorderWidth(0);  
  204.         footTable.addCell(cell);  
  205.   
  206.         strTableTitle = "受理人:";  
  207.         tableTitle = new Paragraph(strTableTitle, conyentFont);  
  208.         cell = new PdfPCell(tableTitle);  
  209.         cell.setHorizontalAlignment(Element.ALIGN_LEFT);// 水平居中  
  210.         cell.setVerticalAlignment(Element.ALIGN_MIDDLE);// 垂直居中  
  211.         cell.setBorderWidth(0);  
  212.         footTable.addCell(cell);  
  213.   
  214.         strTableTitle = "   申请人电话:";  
  215.         tableTitle = new Paragraph(strTableTitle, conyentFont);  
  216.         cell = new PdfPCell(tableTitle);  
  217.         cell.setHorizontalAlignment(Element.ALIGN_LEFT);//  
  218.         cell.setVerticalAlignment(Element.ALIGN_MIDDLE);// 垂直居中  
  219.         cell.setBorderWidth(0);  
  220.         footTable.addCell(cell);  
  221.   
  222.         strTableTitle = "受理日期:";  
  223.         tableTitle = new Paragraph(strTableTitle, conyentFont);  
  224.         cell = new PdfPCell(tableTitle);  
  225.         cell.setHorizontalAlignment(Element.ALIGN_LEFT);//  
  226.         cell.setVerticalAlignment(Element.ALIGN_MIDDLE);// 垂直居中  
  227.         cell.setBorderWidth(0);  
  228.         footTable.addCell(cell);  
  229.   
  230.         doc.add(footTable);  
  231.           
  232.         tParagraph = new Paragraph();  
  233.         Chunk tChunk = new Chunk("   说明:  ",conyentFont);  
  234.         tParagraph.add(tChunk);  
  235.           
  236.         tChunk = new Chunk("                                                                               ",conyentFont);  
  237.         tChunk.setUnderline(0.1f, -2f);  
  238.         tParagraph.add(tChunk);  
  239.         tChunk = new Chunk("                                                                           ",conyentFont);  
  240.         tChunk.setUnderline(0.1f, -2f);  
  241.         tParagraph.add(tChunk);  
  242.         tChunk = new Chunk("                                                                        ",conyentFont);  
  243.         tChunk.setUnderline(0.1f, -2f);  
  244.         tParagraph.add(tChunk);  
  245.           
  246.         tParagraph.setLeading(30f);  
  247.         tChunk = new Chunk("                                                                          ",conyentFont);  
  248.         tChunk.setUnderline(0.1f, -2f);  
  249.         tParagraph.add(tChunk);  
  250.         tChunk = new Chunk("                                                                          ",conyentFont);  
  251.         tChunk.setUnderline(0.1f, -2f);  
  252.         tParagraph.add(tChunk);  
  253.           
  254.         doc.add(tParagraph);  
  255.           
  256.         doc.close();  
  257.         System.out.println("结束.....");  
  258.     }  
  259.   
  260.     /** 
  261.      *  
  262.      * @author ShaoMin 
  263.      *  
  264.      */  
  265.     public void createPDFFile() {  
  266.   
  267.         Document document = new Document(PageSize.A4, 80792045); // A4纸大小,//  
  268.                                                                        // 左、右、上、下  
  269.         try {  
  270.             // 中文处理  
  271.             BaseFont bfChinese = BaseFont.createFont("STSongStd-Light""UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);  
  272.   
  273.             Font FontChinese = new Font(bfChinese, 14, Font.COURIER); // 其他所有文字字体  
  274.             Font BoldChinese = new Font(bfChinese, 14, Font.BOLD); // 粗体  
  275.             Font titleChinese = new Font(bfChinese, 20, Font.BOLD); // 模板抬头的字体  
  276.             Font moneyFontChinese = new Font(bfChinese, 8, Font.COURIER); // 币种和租金金额的小一号字体  
  277.             Font subBoldFontChinese = new Font(bfChinese, 8, Font.BOLD); // 币种和租金金额的小一号字体  
  278.   
  279.             // 使用PDFWriter进行写文件操作  
  280.             PdfWriter.getInstance(document, new FileOutputStream("temp/pdf/pdfFile.pdf"));  
  281.             document.open(); // 打开文档  
  282.   
  283.             // ------------开始写数据-------------------  
  284.             Paragraph title = new Paragraph("起租通知书", titleChinese);// 抬头  
  285.             title.setAlignment(Element.ALIGN_CENTER); // 居中设置  
  286.             title.setLeading(1f);// 设置行间距//设置上面空白宽度  
  287.             document.add(title);  
  288.   
  289.             title = new Paragraph("致:XXX公司", BoldChinese);// 抬头  
  290.             title.setSpacingBefore(25f);// 设置上面空白宽度  
  291.             document.add(title);  
  292.   
  293.             title = new Paragraph("         贵我双方签署的编号为 XXX有关起租条件已满足,现将租赁合同项下相关租赁要素明示如下:", FontChinese);  
  294.             title.setLeading(22f);// 设置行间距  
  295.             document.add(title);  
  296.   
  297.             float[] widths = { 10f, 25f, 30f, 30f };// 设置表格的列宽和列数 默认是4列  
  298.   
  299.             PdfPTable table = new PdfPTable(widths);// 建立一个pdf表格  
  300.             table.setSpacingBefore(20f);// 设置表格上面空白宽度  
  301.             table.setTotalWidth(500);// 设置表格的宽度  
  302.             table.setWidthPercentage(100);// 设置表格宽度为%100  
  303.             // table.getDefaultCell().setBorder(0);//设置表格默认为无边框  
  304.   
  305.             String[] tempValue = { "1""2011-07-07""2222元""233元""2014-12-22""3000元""9999元" }; // 租金期次列表  
  306.             int rowCount = 1// 行计数器  
  307.             PdfPCell cell = null;  
  308.             // ---表头  
  309.             cell = new PdfPCell(new Paragraph("期次", subBoldFontChinese));// 描述  
  310.             cell.setFixedHeight(20);  
  311.             cell.setHorizontalAlignment(Element.ALIGN_CENTER);// 设置内容水平居中显示  
  312.             cell.setVerticalAlignment(Element.ALIGN_MIDDLE); // 设置垂直居中  
  313.             table.addCell(cell);  
  314.             cell = new PdfPCell(new Paragraph("租金日", subBoldFontChinese));// 描述  
  315.             cell.setFixedHeight(20);  
  316.             cell.setHorizontalAlignment(Element.ALIGN_CENTER);// 设置内容水平居中显示  
  317.             cell.setVerticalAlignment(Element.ALIGN_MIDDLE); // 设置垂直居中  
  318.             table.addCell(cell);  
  319.             cell = new PdfPCell(new Paragraph("各期租金金额", subBoldFontChinese));// 描述  
  320.             cell.setFixedHeight(20);  
  321.             cell.setHorizontalAlignment(Element.ALIGN_CENTER);// 设置内容水平居中显示  
  322.             cell.setVerticalAlignment(Element.ALIGN_MIDDLE); // 设置垂直居中  
  323.             table.addCell(cell);  
  324.   
  325.             cell = new PdfPCell(new Paragraph("各期租金后\n剩余租金", subBoldFontChinese));// 描述  
  326.             cell.setHorizontalAlignment(Element.ALIGN_CENTER);// 设置内容水平居中显示  
  327.             cell.setVerticalAlignment(Element.ALIGN_MIDDLE); // 设置垂直居中  
  328.             cell.setFixedHeight(20);  
  329.             table.addCell(cell);  
  330.   
  331.             for (int j = 1; j < tempValue.length; j++) {  
  332.                 if (j % 2 == 1) { // 第一列 日期  
  333.                     cell = new PdfPCell(new Paragraph(rowCount + "", moneyFontChinese));// 描述  
  334.                     cell.setFixedHeight(20);  
  335.                     cell.setHorizontalAlignment(Element.ALIGN_CENTER);// 设置内容水平居中显示  
  336.                     cell.setVerticalAlignment(Element.ALIGN_MIDDLE); // 设置垂直居中  
  337.                     table.addCell(cell);  
  338.                     rowCount++;  
  339.                 }  
  340.                 cell = new PdfPCell(new Paragraph(tempValue[j], moneyFontChinese));// 描述  
  341.                 cell.setFixedHeight(20);  
  342.                 cell.setHorizontalAlignment(Element.ALIGN_CENTER);// 设置内容水平居中显示  
  343.                 cell.setVerticalAlignment(Element.ALIGN_MIDDLE); // 设置垂直居中  
  344.                 table.addCell(cell);  
  345.             }  
  346.             document.add(table);  
  347.   
  348.             title = new Paragraph("                租金总额:XXX", FontChinese);  
  349.             title.setLeading(22f);// 设置行间距  
  350.             document.add(title);  
  351.             title = new Paragraph("         特此通知!", FontChinese);  
  352.             title.setLeading(22f);// 设置行间距  
  353.             document.add(title);  
  354.             // -------此处增加图片和日期,因为图片会遇到跨页的问题,图片跨页,图片下方的日期就会脱离图片下方会放到上一页。  
  355.             // 所以必须用表格加以固定的技巧来实现  
  356.             float[] widthes = { 50f };// 设置表格的列宽和列数  
  357.             PdfPTable hiddenTable = new PdfPTable(widthes);// 建立一个pdf表格  
  358.             hiddenTable.setSpacingBefore(11f); // 设置表格上空间  
  359.             hiddenTable.setTotalWidth(500);// 设置表格的宽度  
  360.             hiddenTable.setWidthPercentage(100);// 设置表格宽度为%100  
  361.             hiddenTable.getDefaultCell().disableBorderSide(1);  
  362.             hiddenTable.getDefaultCell().disableBorderSide(2);  
  363.             hiddenTable.getDefaultCell().disableBorderSide(4);  
  364.             hiddenTable.getDefaultCell().disableBorderSide(8);  
  365.   
  366.             Image upgif = Image.getInstance("source/imag/bage.png");  
  367.             upgif.scalePercent(7.5f);// 设置缩放的百分比%7.5  
  368.             upgif.setAlignment(Element.ALIGN_RIGHT);  
  369.   
  370.             cell = new PdfPCell(new Paragraph("", FontChinese));// 描述  
  371.             cell.setHorizontalAlignment(Element.ALIGN_RIGHT);// 设置内容水平居中显示  
  372.             cell.addElement(upgif);  
  373.             cell.setPaddingTop(0f); // 设置内容靠上位置  
  374.             cell.setPaddingBottom(0f);  
  375.             cell.setPaddingRight(20f);  
  376.             cell.setBorder(Rectangle.NO_BORDER);// 设置单元格无边框  
  377.             hiddenTable.addCell(cell);  
  378.   
  379.             cell = new PdfPCell(new Paragraph("XX 年 XX 月 XX 日                    ", FontChinese));// 金额  
  380.             cell.setHorizontalAlignment(Element.ALIGN_RIGHT);// 设置内容水平居中显示  
  381.             cell.setPaddingTop(0f);  
  382.             cell.setPaddingRight(20f);  
  383.             cell.setBorder(Rectangle.NO_BORDER);  
  384.             hiddenTable.addCell(cell);  
  385.             document.add(hiddenTable);  
  386.             System.out.println("拼装起租通知书结束...");  
  387.             document.close();  
  388.         } catch (DocumentException e) {  
  389.             e.printStackTrace();  
  390.         } catch (IOException e) {  
  391.             e.printStackTrace();  
  392.         }  
  393.     }  
  394.   
  395.     /** 
  396.      * 支持中文 
  397.      *  
  398.      * @return 
  399.      */  
  400.     public Font getChineseFont() {  
  401.         BaseFont bfChinese;  
  402.         Font fontChinese = null;  
  403.         try {  
  404.             bfChinese = BaseFont.createFont("STSongStd-Light""UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);  
  405.             // fontChinese = new Font(bfChinese, 12, Font.NORMAL);  
  406.             fontChinese = new Font(bfChinese, 12, Font.NORMAL, BaseColor.BLUE);  
  407.         } catch (DocumentException e) {  
  408.             e.printStackTrace();  
  409.         } catch (IOException e) {  
  410.             e.printStackTrace();  
  411.         }  
  412.         return fontChinese;  
  413.   
  414.     }  
  415.   
  416. }  

(二)、使用模板 : PdfTempletePractise.java

[java]  view plain  copy
  1. package pdf.practise;  
  2.   
  3. import java.io.FileOutputStream;  
  4. import java.io.IOException;  
  5. import java.util.ArrayList;  
  6. import java.util.HashMap;  
  7. import java.util.List;  
  8. import java.util.Map;  
  9.   
  10. import com.itextpdf.text.BaseColor;  
  11. import com.itextpdf.text.DocumentException;  
  12. import com.itextpdf.text.Element;  
  13. import com.itextpdf.text.Font;  
  14. import com.itextpdf.text.Paragraph;  
  15. import com.itextpdf.text.pdf.AcroFields;  
  16. import com.itextpdf.text.pdf.AcroFields.Item;  
  17. import com.itextpdf.text.pdf.BaseFont;  
  18. import com.itextpdf.text.pdf.PdfContentByte;  
  19. import com.itextpdf.text.pdf.PdfPCell;  
  20. import com.itextpdf.text.pdf.PdfPTable;  
  21. import com.itextpdf.text.pdf.PdfReader;  
  22. import com.itextpdf.text.pdf.PdfStamper;  
  23.   
  24. /** 
  25.  *  
  26.  * @Title: 模板报表制作 
  27.  * @Description: 
  28.  * @Copyright: Copyright (c) 2014 
  29.  * @Company: SinoSoft 
  30.  *  
  31.  * @author: ShaoMin 
  32.  * @version: 1.0 
  33.  * @CreateDate:Nov 5, 2014 
  34.  */  
  35. public class PdfTempletePractise {  
  36.   
  37.     protected PdfStamper mPdfStamper = null;// pdf解析器  
  38.   
  39.     // 定义动态表的各类数据  
  40.     private final int TABLE_COLNUM = 4;// 整个表格列数  
  41.     private final float TABLE_WIDTH = 369.7f;// 整个表格宽度  
  42.     private final float ROW_HEIGHT = 19.19f;// 单元格高度  
  43.     private final float XPOS = 174.52f;// 整个表格 X坐标  
  44.     private final float YPOS = 569.18f; // 整个表格 Y坐标  
  45.     private final float[] ROW_WIDTHS = { 0.2565f, 0.25f, 0.25f, 0.245f };// 单元格宽度  
  46.   
  47.     /** 
  48.      * @author ShaoMin 
  49.      * @param args 
  50.      */  
  51.     public static void main(String[] args) {  
  52.         PdfTempletePractise tPdfTemplete = new PdfTempletePractise();  
  53.   
  54.         Map<String, String> mMapDatas = new HashMap<String, String>();  
  55.         mMapDatas.put("PdfResultFile""temp/pdf/templetePdfFile.pdf");// 生成的文件路径  
  56.         mMapDatas.put("PdfTemplateFile""source/pdf/templete/EdorAcceptResource.pdf");// 获取模板路径  
  57.         mMapDatas.put("CustomerName""SAM-SHO");// 客户姓名  
  58.         mMapDatas.put("ContNo""123456789098765");// 合同号  
  59.         mMapDatas.put("ContCount""1");// 保单个数  
  60.         mMapDatas.put("EdorType""CT-退保");// 保全类型  
  61.         mMapDatas.put("GetMoney""999.99");// 保全失算金额  
  62.         mMapDatas.put("AcceptName""人寿保险");// 受理人  
  63.         mMapDatas.put("AcceptDate""2014-14-1");// 受理日期  
  64.   
  65.         tPdfTemplete.fillTempleteDates(mMapDatas);// 表单域数据  
  66.   
  67.         List<String[]> tableLists = new ArrayList<String[]>();  
  68.         for (int i = 0; i < 16; i++) {  
  69.             String[] arrStr = new String[4];  
  70.             arrStr[0] = i + "--" + 0;  
  71.             arrStr[1] = i + "--" + 1;  
  72.             arrStr[2] = i + "--" + 2;  
  73.             arrStr[3] = i + "--" + 3;  
  74.             tableLists.add(arrStr);  
  75.         }  
  76.         tPdfTemplete.createTable(tableLists);  
  77.           
  78.         System.out.println("完成.........");  
  79.   
  80.     }  
  81.   
  82.     /** 
  83.      * 填充模板数据,表单域数据 
  84.      *  
  85.      * @author ShaoMin 
  86.      * @param map 
  87.      */  
  88.     @SuppressWarnings("unchecked")  
  89.     protected boolean fillTempleteDates(Map<String, String> map) {  
  90.   
  91.         String tPdfResultFile = map.get("PdfResultFile");// 生成的文件路径  
  92.         String tPdfTemplateFile = map.get("PdfTemplateFile");// 获取模板路径  
  93.   
  94.         FileOutputStream fos = null;  
  95.         PdfReader reader = null;  
  96.   
  97.         try {  
  98.   
  99.             fos = new FileOutputStream(tPdfResultFile);// 需要生成PDF  
  100.             reader = new PdfReader(tPdfTemplateFile);// 模板  
  101.             mPdfStamper = new PdfStamper(reader, fos);// 解析  
  102.             AcroFields form = mPdfStamper.getAcroFields();// 获取到模板上预定义的参数域  
  103.             // 获取模板中定义的变量  
  104.             Map<String, Item> acroFieldMap = form.getFields();  
  105.             for (Map.Entry<String, Item> entry : acroFieldMap.entrySet()) {  
  106.                 // 获得块名  
  107.                 String fieldName = entry.getKey();  
  108.                 String fieldValue = map.get(fieldName);// 通过名字,获取传入的参数值  
  109.                 if (!"".equals(fieldValue)) {  
  110.                     // 为模板中的变量赋值  
  111.                     form.setField(fieldName, fieldValue);  
  112.                     System.out.println(fieldName + "," + fieldValue);  
  113.                 }  
  114.             }  
  115.   
  116.             // 模板中的变量赋值之后不能编辑  
  117.             mPdfStamper.setFormFlattening(true);  
  118.             reader.close();// 阅读器关闭,解析器暂时不关闭,因为创建动态表格还需要使用  
  119.         } catch (Exception e) {  
  120.             e.printStackTrace();  
  121.             return false;  
  122.         } finally {  
  123.             if (reader != null) {  
  124.                 reader.close();  
  125.             }  
  126.         }  
  127.         return true;  
  128.     }  
  129.   
  130.     /** 
  131.      * 创建表格 
  132.      *  
  133.      * @author ShaoMin 
  134.      * @param resultList 
  135.      * @return 
  136.      */  
  137.     protected boolean createTable(List<String[]> resultList) {  
  138.   
  139.         PdfPTable table = new PdfPTable(TABLE_COLNUM);// 创建表格  
  140.         PdfPCell cell = null;  
  141.         try {  
  142.   
  143.             for (String[] tResults : resultList) {  
  144.                 for (int i = 0; i < tResults.length; i++) {  
  145.                     // 创建单元格,并置上值  
  146.                     Paragraph para = new Paragraph(tResults[i], getChineseFont());  
  147.                     para.setAlignment(Element.ALIGN_CENTER);  
  148.                     cell = new PdfPCell(para);  
  149.                     // cell.setBorderWidth(0)//边框  
  150.                     cell.setFixedHeight(ROW_HEIGHT);// 单元格高度  
  151.                     cell.setHorizontalAlignment(Element.ALIGN_CENTER);//水平位置  
  152.                     cell.setVerticalAlignment(Element.ALIGN_MIDDLE);//垂直位置  
  153.   
  154.                     table.addCell(cell);// 单元格加入动态表格  
  155.                 }  
  156.             }  
  157.             table.setWidths(ROW_WIDTHS);// 设置每个单元格的宽度,是比例关系  
  158.             table.setTotalWidth(TABLE_WIDTH);// 总宽度  
  159.             PdfContentByte tContent = mPdfStamper.getOverContent(1);// 获取模板的层次  
  160.             table.writeSelectedRows(0, -10, -1, XPOS, YPOS, tContent);// 把表格写入模板的固定位置(0行-最后一行| 0列-最后一列)  
  161.   
  162.             mPdfStamper.close();// 关闭解析器  
  163.         } catch (DocumentException e) {  
  164.             e.printStackTrace();  
  165.             return false;  
  166.         } catch (IOException e) {  
  167.             e.printStackTrace();  
  168.             return false;  
  169.         } finally {  
  170.             try {  
  171.                 if (mPdfStamper != null) {  
  172.                     mPdfStamper.close();// 关闭解析器  
  173.                 }  
  174.             } catch (DocumentException e) {  
  175.                 e.printStackTrace();  
  176.             } catch (IOException e) {  
  177.                 e.printStackTrace();  
  178.             }  
  179.         }  
  180.         return true;  
  181.     }  
  182.   
  183.     /** 
  184.      * 支持中文 
  185.      *  
  186.      * @return 
  187.      */  
  188.     public Font getChineseFont() {  
  189.         BaseFont bfChinese;  
  190.         Font fontChinese = null;  
  191.         try {  
  192.             bfChinese = BaseFont.createFont("STSongStd-Light""UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);  
  193.             // fontChinese = new Font(bfChinese, 12, Font.NORMAL);  
  194.             fontChinese = new Font(bfChinese, 12, Font.NORMAL, BaseColor.BLUE);  
  195.         } catch (DocumentException e) {  
  196.             e.printStackTrace();  
  197.         } catch (IOException e) {  
  198.             e.printStackTrace();  
  199.         }  
  200.         return fontChinese;  
  201.   
  202.     }  
  203.   
  204. }  

二、PDF打印设计:

1、核心:

1)模板方法设计模式:Template Method设计

2)抽象类的使用

2、实现

1)打印抽象类:AbstractPDFPrintBL.java

2)实例,受理凭证打印: EdorAcceptPDFPrintBL.java

3)实际使用的过程中需要传递List和map容器的数据。表格数据放入List,其他数据放入Map。

3、代码如下:

1)抽象类如下:

[java]  view plain  copy
  1. package com.sinosoft.lis.agentprint;  
  2.   
  3. import java.io.File;  
  4.   
  5. /** 
  6.  * @Title: PDF打印公共类 
  7.  * @Description:其他PDF打印类,都可以继承本类,例如受理凭证打印类:EdorAcceptPDFPrintBL 
  8.  * @Copyright: Copyright (c) 2014 
  9.  * @Company:  
  10.  *  
  11.  * @author: ShaoMin 
  12.  * @version: 1.0 
  13.  * @CreateDate:Oct 27, 2014 
  14.  */  
  15. public abstract class AbstractPDFPrintBL {  
  16.   
  17.     protected Logger logger = Logger.getLogger(getClass());  
  18.     protected CErrors mErrors = new CErrors();  
  19.   
  20.     /** 存放动态表格的数据 */  
  21.     protected List<String[]> lists = new ArrayList<String[]>();  
  22.     /** 用于存放要填充的模板数据 */  
  23.     protected Map<String, String> map = new HashMap<String, String>();  
  24.   
  25.     protected PdfStamper mPdfStamper = null;// pdf解析器  
  26.   
  27.     /** 
  28.      * 传输数据的公共方法 
  29.      */  
  30.     public boolean submitData() {  
  31.   
  32.         // 获取数据  
  33.         if (!getInput()) {  
  34.             return false;  
  35.         }  
  36.   
  37.         // 数据校验  
  38.         if (!checkDatas()) {  
  39.             return false;  
  40.         }  
  41.   
  42.         // 打印处理  
  43.         if (!dealData()) {  
  44.             return false;  
  45.         }  
  46.         return true;  
  47.     }  
  48.   
  49.     /** 
  50.      * 获取必要的数据 
  51.      *  
  52.      * @author ShaoMin 
  53.      * @return 
  54.      */  
  55.     protected abstract boolean getInput();  
  56.   
  57.     /** 
  58.      * 数据校验 
  59.      *  
  60.      * @author ShaoMin 
  61.      * @return 
  62.      */  
  63.     protected abstract boolean checkDatas();  
  64.   
  65.     /** 
  66.      * 业务处理 
  67.      *  
  68.      * @author ShaoMin 
  69.      * @return 
  70.      */  
  71.     private boolean dealData() {  
  72.   
  73.         // 删除临时文件  
  74.         this.deleteTempFile();  
  75.   
  76.         // 填充模板数据  
  77.         if (!fillTempleteDates(map)) {  
  78.             try {  
  79.                 if (mPdfStamper != null) {  
  80.                     mPdfStamper.close();  
  81.                 }  
  82.             } catch (DocumentException e) {  
  83.                 e.printStackTrace();  
  84.             } catch (IOException e) {  
  85.                 e.printStackTrace();  
  86.             }  
  87.             return false;  
  88.         }  
  89.   
  90.         // 写入动态数据创建表格  
  91.         if (lists != null && !lists.isEmpty()) {  
  92.             if (!createTable(lists)) {  
  93.                 return false;  
  94.             }  
  95.         }  
  96.           
  97.         // 不使用模板,直接输出PDF  
  98.         if(!createPdfFile()){  
  99.             return false;  
  100.         }  
  101.         return true;  
  102.   
  103.     }  
  104.   
  105.     /** 
  106.      * 不使用模板,直接输出PDF(可以输出文本和表格) 
  107.      * @author ShaoMin 
  108.      * @return 
  109.      */  
  110.     protected  boolean createPdfFile() {  
  111.         return true;  
  112.     }  
  113.   
  114.     /** 
  115.      * 生成pdf的动态表格,子类可以重写实现复杂逻辑 
  116.      * 没有表格输出,在构造函数时,传入空的集合即可。 
  117.      * 如Collections.EMPTY_LIST,不建议直接传null 
  118.      * @author ShaoMin 
  119.      * @param resultList 
  120.      * @return 
  121.      * @throws Exception 
  122.      */  
  123.     protected abstract boolean createTable(List<String[]> resultList);  
  124.       
  125.   
  126.     /** 
  127.      * 支持汉字 
  128.      */  
  129.     protected BaseFont getBaseFont() {  
  130.         BaseFont tBaseFont = null;  
  131.         try {  
  132.             tBaseFont = BaseFont.createFont("STSongStd-Light""UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);  
  133.         } catch (Exception e) {  
  134.             e.printStackTrace();  
  135.             return null;  
  136.         }  
  137.   
  138.         return tBaseFont;  
  139.     }  
  140.   
  141.     /** 
  142.      * 删除临时文件 
  143.      * @author ShaoMin 
  144.      * @param filePath 
  145.      * @return 
  146.      */  
  147.     private boolean deleteTempFile() {  
  148.         String tPdfResultFile = map.get("PdfResultFile");  
  149.         File tFile = new File(tPdfResultFile);  
  150.         if (tFile.exists() && tFile.isFile()) {  
  151.             tFile.delete();  
  152.         }  
  153.         return true;  
  154.     }  
  155.   
  156.     /** 
  157.      * 填充模板数据,子类可以重写实现复杂逻辑 
  158.      * @author ShaoMin 
  159.      * @param map 
  160.      */  
  161.     @SuppressWarnings("unchecked")  
  162.     protected boolean fillTempleteDates(Map<String, String> map) {  
  163.   
  164.         String tPdfResultFile = map.get("PdfResultFile");// 生成的文件路径  
  165.         String tPdfTemplateFile = map.get("PdfTemplateFile");// 获取模板路径  
  166.   
  167.         FileOutputStream fos = null;  
  168.         PdfReader reader = null;  
  169.   
  170.         try {  
  171.   
  172.             fos = new FileOutputStream(tPdfResultFile);// 需要生成PDF  
  173.             reader = new PdfReader(tPdfTemplateFile);// 模板  
  174.             mPdfStamper = new PdfStamper(reader, fos);// 解析  
  175.             AcroFields form = mPdfStamper.getAcroFields();// 获取到模板上预定义的参数域  
  176.             // 获取模板中定义的变量  
  177.             Map<String, Item> acroFieldMap = form.getFields();  
  178.             for (Map.Entry<String, Item> entry : acroFieldMap.entrySet()) {  
  179.                 // 获得块名  
  180.                 String fieldName = entry.getKey();  
  181.                 String fieldValue = map.get(fieldName);// 通过名字,获取传入的参数值  
  182.                 if (!"".equals(fieldValue)) {  
  183.                     // 为模板中的变量赋值  
  184.                     form.setField(fieldName, fieldValue);  
  185.                     System.out.println(fieldName + "," + fieldValue);  
  186.                 }  
  187.             }  
  188.   
  189.             // 模板中的变量赋值之后不能编辑  
  190.             mPdfStamper.setFormFlattening(true);  
  191.             reader.close();// 阅读器关闭,解析器暂时不关闭,因为创建动态表格还需要使用  
  192.         } catch (Exception e) {  
  193.             e.printStackTrace();  
  194.             return false;  
  195.         } finally {  
  196.             if (reader != null) {  
  197.                 reader.close();  
  198.             }  
  199.         }  
  200.         return true;  
  201.     }  
  202.   
  203.     /** 
  204.      * 判断字符串是否为空 
  205.      * @param str 字符串 
  206.      * @return boolean 
  207.      */  
  208.     protected boolean isEmpty(String str) {  
  209.         if (str == null || "".equals(str)) {  
  210.             return true;  
  211.         }  
  212.         return false;  
  213.     }  
  214.   
  215.     /** 
  216.      * 判断字符串不为空 
  217.      * @param str 字符串 
  218.      * @return boolean 
  219.      */  
  220.     protected boolean isNotEmpty(String str) {  
  221.         return !isEmpty(str);  
  222.     }  
  223.   
  224.     public void setLists(ArrayList<String[]> lists) {  
  225.         this.lists = lists;  
  226.     }  
  227.   
  228.     public void setMap(Map<String, String> map) {  
  229.         this.map = map;  
  230.     }  
  231.   
  232. }  



2)实现类如下:打印凭证
[java]  view plain  copy
  1. package com.sinosoft.lis.agentprint;  
  2.   
  3. import java.io.IOException;  
  4.   
  5. /** 
  6.  *  
  7.  * @Title: 受理凭证打印类 
  8.  * @Description: 
  9.  * @Copyright: Copyright (c) 2014 
  10.  * @Company:  
  11.  *  
  12.  * @author: SAM 
  13.  * @version: 1.0 
  14.  * @CreateDate:2014-5-27 
  15.  */  
  16. public class EdorAcceptPDFPrintBL extends AbstractPDFPrintBL {  
  17.   
  18.     // 定义动态表的各类数据  
  19.     private final int TABLE_COLNUM = 4;// 整个表格列数  
  20.     private final float TABLE_WIDTH = 369.7f;// 整个表格宽度  
  21.     private final float ROW_HEIGHT = 19.19f;// 单元格高度  
  22.     private final float XPOS = 174.52f;// 整个表格 X坐标  
  23.     private final float YPOS = 569.18f; // 整个表格 Y坐标  
  24. //    private final int TABLE_BORDER = 120;// 表格的边框  
  25.     private final float FONT_SIZE = 8f;// 字体的大小  
  26.     private final float[] ROW_WIDTHS = {0.2565f, 0.25f, 0.25f, 0.245f};//单元格宽度  
  27.       
  28.   
  29.     // 私有构造方法  
  30.     private EdorAcceptPDFPrintBL() {  
  31.   
  32.     }  
  33.   
  34.     private EdorAcceptPDFPrintBL(Map<String, String> map, List<String[]> lists) {  
  35.         this.map = map;  
  36.         this.lists = lists;  
  37.     }  
  38.   
  39.       
  40.     public static EdorAcceptPDFPrintBL getIntance() {  
  41.         return new EdorAcceptPDFPrintBL();  
  42.   
  43.     }  
  44.       
  45.     /** 
  46.      * 私有静态工厂方法,取代构造方法使用 
  47.      * 如不需要动态表格的打印,这边lists参数可以传入空的集合 
  48.      * 如Collections.EMPTY_LIST,不建议直接传null 
  49.      * @author ShaoMin 
  50.      * @param map 
  51.      * @param lists 
  52.      * @return 
  53.      */  
  54.     public static EdorAcceptPDFPrintBL getIntanceByColection(Map<String, String> map, List<String[]> lists) {  
  55.         return new EdorAcceptPDFPrintBL(map, lists);  
  56.     }  
  57.   
  58.     @Override  
  59.     public boolean checkDatas() {  
  60.         if (map == null || map.isEmpty()) {  
  61.             mErrors.addOneError("数据传输失败");  
  62.             return false;  
  63.         }  
  64.   
  65.         if (lists == null || lists.isEmpty()) {  
  66.             mErrors.addOneError("数据传输失败");  
  67.             return false;  
  68.         }  
  69.         return true;  
  70.     }  
  71.   
  72.     @Override  
  73.     protected boolean getInput() {  
  74.   
  75.         return true;  
  76.     }  
  77.   
  78.     @Override  
  79.     protected boolean createTable(List<String[]> resultList) {  
  80.   
  81.         PdfContentByte tContent = mPdfStamper.getOverContent(1);//获取模板的层次  
  82.         PdfPTable table = new PdfPTable(TABLE_COLNUM);  
  83.         PdfPCell cell = null;  
  84.         try {  
  85.               
  86.             //设置中文字体  
  87.             BaseFont bfChinese = this.getBaseFont();  
  88.             Font subBoldFontChinese = new Font(bfChinese, FONT_SIZE, Font.NORMAL);  
  89.   
  90.             for (String[] tResults : resultList) {  
  91.                 for (int i = 0; i < tResults.length; i++) {  
  92.                     //创建单元格,并置上值  
  93.                     Paragraph para = new Paragraph(tResults[i], subBoldFontChinese);  
  94.                     para.setAlignment(Element.ALIGN_CENTER);  
  95.                     cell = new PdfPCell(para);  
  96.                     // cell.setBorder(TABLE_BORDER);//边框  
  97.                     cell.setFixedHeight(ROW_HEIGHT);// 单元格高度  
  98.                     cell.setHorizontalAlignment(Element.ALIGN_CENTER);  
  99.                     cell.setVerticalAlignment(Element.ALIGN_MIDDLE);  
  100.   
  101.                     table.addCell(cell);//单元格加入动态表格  
  102.                 }  
  103.             }  
  104.             table.setWidths(ROW_WIDTHS);// 设置每个单元格的宽度  
  105.             table.setTotalWidth(TABLE_WIDTH);// 总宽度  
  106.             table.writeSelectedRows(0, -10, -1, XPOS, YPOS, tContent);//把表格写入模板的固定位置  
  107.   
  108.             mPdfStamper.close();//关闭解析器  
  109.         } catch (DocumentException e) {  
  110.             e.printStackTrace();  
  111.             return false;  
  112.         } catch (IOException e) {  
  113.             e.printStackTrace();  
  114.             return false;  
  115.         } finally {  
  116.             try {  
  117.                 if (mPdfStamper != null) {  
  118.                     mPdfStamper.close();//关闭解析器  
  119.                 }  
  120.             } catch (DocumentException e) {  
  121.                 e.printStackTrace();  
  122.             } catch (IOException e) {  
  123.                 e.printStackTrace();  
  124.             }  
  125.         }  
  126.         return true;  
  127.     }  
  128.   
  129.       
  130.   
  131. }  


3)调用代码如下:

[java]  view plain  copy
  1. // 1- 定义必要容器  
  2.     mMapDatas = new HashMap<String, String>();  
  3.     mListDatas = new ArrayList<String[]>();  
  4.   
  5.     // 2-封装map数据  
  6.   
  7.     // 2-1 获取必要信息:如文件名称、保全类型名等,并封装map数据  
  8.     mMapDatas.put("PdfTemplateFile""templte.pdf");// PDF模版文件  
  9.     mMapDatas.put("PdfResultFile""result.psd");// 生成PDF文件  
  10.     mMapDatas.put("PdfTempPath""tem/pdf");// 生成PDF临时路径  
  11.   
  12.     mMapDatas.put("CustomerName", “Sam-SHO”);// 客户姓名  
  13.     mMapDatas.put("ContNo""123456789");// 合同号  
  14.     mMapDatas.put("ContCount""1");// 保单个数  
  15.     mMapDatas.put("EdorType""CT-退保");// 保全类型  
  16.   
  17.     mMapDatas.put("GetMoney""200"));// 保全失算金额  
  18.     mMapDatas.put("AcceptName""SAM");// 受理人  
  19.     mMapDatas.put("AcceptDate""2014-11-07");// 受理日期  
  20.   
  21.     // 3-封装list数据  
  22.     // 3-1 获取受理资料信息-  
  23.   
  24.     // 3-2 封装list数据  
  25.     for (int i = 1; i <= B.size(); i++) {  
  26.         A a = B.get(i);  
  27.         String[] strArr = new String[4];// 4列数据  
  28.         String tCopyFlag = a.getResourceCopyFlag();  
  29.         // 0-原件;1-复印件;2-无  
  30.         strArr[0] = "0".equals(tCopyFlag) ? "Y" : "";// 原件  
  31.         strArr[1] = "1".equals(tCopyFlag) ? "Y" : "";// 复印件  
  32.         strArr[2] = a.getResourcePages();// 份数  
  33.         strArr[3] = a.getResourceDesc();// 备注  
  34.   
  35.         mListDatas.add(strArr);  
  36.     }  
  37.       
  38.     // 4-调用打印类  
  39.     EdorAcceptPDFPrintBL tPdfPrint = EdorAcceptPDFPrintBL.getIntanceByColection(mMapDatas, mListDatas);  
  40.     if (!tPdfPrint.submitData()) {  
  41.         return false;  
  42.     }  
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值