java根据模板生成pdf文件并导出

首先你的制作一个pdf模板:

1.先用word做出模板界面


2.文件另存为pdf格式文件


3.通过Adobe Acrobat pro软件打开刚刚用word转换成的pdf文件(注:如果没有这个软件可以通过我的百度云下载,链接:http://pan.baidu.com/s/1pL2klzt)如果无法下载可以联系博主。


4.点击右边的"准备表单"按钮,选择"测试.pdf"选择开始

进去到编辑页面,打开后它会自动侦测并命名表单域,右键表单域,点击属性,出现文本域属性对话框(其实无需任何操作,一般情况下不需要修改什么东西,至少我没有修改哦。如果你想修改fill1等信息,可以进行修改)




5.做完上面的工作后,直接"另存为"将pdf存储就可以


*****************************************************************************

以上部分是制作pdf模板操作,上述完成后,就开始通过程序来根据pdf模板生成pdf文件了,上java程序:

1.首先需要依赖包:itext的jar包,我是maven项目,所以附上maven依赖

[html]  view plain  copy
  1. <!-- https://mvnrepository.com/artifact/com.itextpdf/itextpdf -->  
  2.         <dependency>  
  3.             <groupId>com.itextpdf</groupId>  
  4.             <artifactId>itextpdf</artifactId>  
  5.             <version>5.5.10</version>  
  6.         </dependency>  
[html]  view plain  copy
  1. <!-- https://mvnrepository.com/artifact/com.itextpdf/itext-asian -->  
  2. <span style="white-space:pre;">     </span><dependency>  
  3. <span style="white-space:pre;">     </span>    <groupId>com.itextpdf</groupId>  
  4. <span style="white-space:pre;">     </span>    <artifactId>itext-asian</artifactId>  
  5. <span style="white-space:pre;">     </span>    <version>5.2.0</version>  
  6. <span style="white-space:pre;">     </span></dependency>  
2.下面就是生成pdf代码了

[java]  view plain  copy
  1. import java.io.ByteArrayOutputStream;  
  2. import java.io.FileOutputStream;  
  3. import java.io.IOException;  
  4.   
  5. import com.itextpdf.text.Document;  
  6. import com.itextpdf.text.DocumentException;  
  7. import com.itextpdf.text.pdf.AcroFields;  
  8. import com.itextpdf.text.pdf.PdfCopy;  
  9. import com.itextpdf.text.pdf.PdfImportedPage;  
  10. import com.itextpdf.text.pdf.PdfReader;  
  11. import com.itextpdf.text.pdf.PdfStamper;  
  12.   
  13. public class Snippet {  
  14.     // 利用模板生成pdf  
  15.     public static void fillTemplate() {  
  16.         // 模板路径  
  17.         String templatePath = "E:/测试3.pdf";  
  18.         // 生成的新文件路径  
  19.         String newPDFPath = "E:/ceshi.pdf";  
  20.         PdfReader reader;  
  21.         FileOutputStream out;  
  22.         ByteArrayOutputStream bos;  
  23.         PdfStamper stamper;  
  24.         try {  
  25.             out = new FileOutputStream(newPDFPath);// 输出流  
  26.             reader = new PdfReader(templatePath);// 读取pdf模板  
  27.             bos = new ByteArrayOutputStream();  
  28.             stamper = new PdfStamper(reader, bos);  
  29.             AcroFields form = stamper.getAcroFields();  
  30.   
  31.             String[] str = { "123456789""TOP__ONE""男""1991-01-01""130222111133338888""河北省保定市" };  
  32.             int i = 0;  
  33.             java.util.Iterator<String> it = form.getFields().keySet().iterator();  
  34.             while (it.hasNext()) {  
  35.                 String name = it.next().toString();  
  36.                 System.out.println(name);  
  37.                 form.setField(name, str[i++]);  
  38.             }  
  39.             stamper.setFormFlattening(true);// 如果为false那么生成的PDF文件还能编辑,一定要设为true  
  40.             stamper.close();  
  41.   
  42.             Document doc = new Document();  
  43.             PdfCopy copy = new PdfCopy(doc, out);  
  44.             doc.open();  
  45.             PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), 1);  
  46.             copy.addPage(importPage);  
  47.             doc.close();  
  48.   
  49.         } catch (IOException e) {  
  50.             System.out.println(1);  
  51.         } catch (DocumentException e) {  
  52.             System.out.println(2);  
  53.         }  
  54.   
  55.     }  
  56.   
  57.     public static void main(String[] args) {  
  58.         fillTemplate();  
  59.     }  
  60. }  
3.运行结果如下

*********************************************************************

如果没有模板,就行自己生成pdf文件保存到磁盘:下面的方法可以实现:

[java]  view plain  copy
  1. public static void test1(){//生成pdf  
  2.      Document document = new Document();  
  3.        try {  
  4.            PdfWriter.getInstance(document, new FileOutputStream("E:/1.pdf"));  
  5.            document.open();  
  6.            document.add(new Paragraph("hello word"));  
  7.            document.close();  
  8.          } catch (Exception e) {  
  9.              System.out.println("file create exception");  
  10.          }  
  11.      }  
但是上述方法中包含中文时就会出现问题,所以可以使用下面这行代码实现,所使用的jar包,上面的两个依赖都包含了:

[java]  view plain  copy
  1. public static void test1_1(){  
  2.       BaseFont bf;  
  3.       Font font = null;  
  4.       try {  
  5.           bf = BaseFont.createFont( "STSong-Light""UniGB-UCS2-H",  
  6.                       BaseFont.NOT_EMBEDDED);//创建字体  
  7.           font = new Font(bf,12);//使用字体  
  8.       } catch (Exception e) {  
  9.           e.printStackTrace();  
  10.       }  
  11.       Document document = new Document();  
  12.       try {  
  13.           PdfWriter.getInstance(document, new FileOutputStream("E:/2.pdf"));  
  14.           document.open();  
  15.           document.add(new Paragraph("hello word 你好 世界",font));//引用字体  
  16.           document.close();  
  17.          } catch (Exception e) {  
  18.              System.out.println("file create exception");  
  19.          }  
  20.      }  
**************************************************************************************

当然,如果你想弄的炫一点,想实现其他字体,可以去网上搜字体文件然后下载下来,放到项目里,我这里是在项目里新建了一个font文件夹,将字体文件放到了里面。

   1.把华康少女的字体文件拷贝到这个文件夹里面了:


运行以下代码就能得到pdf文件

[java]  view plain  copy
  1. public static void test1_2(){  
  2.       BaseFont bf;  
  3.       Font font = null;  
  4.       try {  
  5. //      bf = BaseFont.createFont("font/simsun.ttc,1", //注意这里有一个,1  
  6. //            BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);//宋体文字  
  7.         bf = BaseFont.createFont("font/华康少女文字W5(P).TTC,1"//simsun.ttc  
  8.              BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);//华康少女文字  
  9.           font = new Font(bf,12);  
  10.       } catch (Exception  e) {  
  11.           e.printStackTrace();  
  12.      }  
  13.      Document document = new Document();  
  14.      try {  
  15.          PdfWriter.getInstance(document, new FileOutputStream("E:/3.pdf"));  
  16.          document.open();  
  17.          document.add(new Paragraph("上善若水",font));  
  18.          document.close();  
  19.      } catch (Exception e) {  
  20.         System.out.println("file create exception");  
  21.      }  
  22.  }  



当然,如果你还想换其他字体,就去下载字体文件吧,然后把相关部分替换掉就行,上面注释的是宋体的。。。


***********************以下是转载别人的****************************

以下为转载的别人方法:可以供参考


我们系统需要生成一个可以打印的PDF文档,老板给了我一个Word文档,按照这个Word文档的格式生成PDF文档。

第一步:下载AdobeAcrobat DC,必须使用这个来制作from域。

第二步:使用AdobeAcrobat DC将Word导成PDF文档。

第三步:由于还要加水印的效果,所以还是使用AdobeAcrobat DC来添加水印,非常方便;

    添加水印的方法:使用AdobeAcrobat DC打开PDF文档,“工具”-》“编辑PDF”-》”水印”-》”添加”

添加水印的操作:

点击“确定”:

第四步:使用AdobeAcrobat DC添加From域;

添加From域方法:使用AdobeAcrobat DC打开文档,“工具”-》“准备表单”

点击“开始”:

点击“保存”:

添加“文本域”到我们想要添加内容的位置:

第五步:使用Java代码导出PDF文档;

主要三个类:功能类-PDFTempletTicket

[java]view plain copy
在CODE上查看代码片派生到我的代码片
  1. /** 
  2.  *@Title: PDFTempletTicket.java 
  3.  *@Package: org.csun.ns.util 
  4.  *@Description: TODO 
  5.  *@Author: chisj [email protected] 
  6.  *@Date: 2016年4月27日上午11:29:52 
  7.  *@Version V1.0 
  8.  */  
  9. package org.csun.ns.util;  
  10.    
  11. import java.io.ByteArrayOutputStream;  
  12. import java.io.File;  
  13. import java.io.FileOutputStream;  
  14. import java.util.ArrayList;  
  15.    
  16. import org.csun.ns.entity.Ticket;  
  17.    
  18. import com.itextpdf.text.pdf.AcroFields;  
  19. import com.itextpdf.text.pdf.BaseFont;  
  20. import com.itextpdf.text.pdf.PdfReader;  
  21. import com.itextpdf.text.pdf.PdfStamper;  
  22.    
  23. /** 
  24.  *@ClassName: PDFTempletTicket 
  25.  *@Description: TODO 
  26.  *@Author: chisj [email protected] 
  27.  *@Date: 2016年4月27日上午11:29:52 
  28.  */  
  29. public class PDFTempletTicket {  
  30.    
  31.          privateString templatePdfPath;  
  32.          privateString ttcPath;  
  33.          privateString targetPdfpath;  
  34.          privateTicket ticket;  
  35.           
  36.           
  37.          publicPDFTempletTicket() {  
  38.                    super();  
  39.          }  
  40.           
  41.          publicPDFTempletTicket(String templatePdfPath, String ttcPath,  
  42.                             StringtargetPdfpath, Ticket ticket) {  
  43.                    this.templatePdfPath= templatePdfPath;  
  44.                    this.ttcPath= ttcPath;  
  45.                    this.targetPdfpath= targetPdfpath;  
  46.                    this.ticket= ticket;  
  47.          }  
  48.           
  49.          publicvoid templetTicket(File file) throws Exception {  
  50.                     
  51.                    PdfReaderreader = new PdfReader(templatePdfPath);  
  52.                    ByteArrayOutputStreambos = new ByteArrayOutputStream();  
  53.                    PdfStamperps = new PdfStamper(reader, bos);  
  54.                     
  55.                    /*使用中文字体 */   
  56.                    BaseFontbf = BaseFont.createFont(PDFTicket.class.getResource("/") +"org/csun/ns/util/simsun.ttc,1",   
  57.                 BaseFont.IDENTITY_H,BaseFont.EMBEDDED);  
  58.        ArrayList<BaseFont> fontList = newArrayList<BaseFont>();   
  59.        fontList.add(bf);   
  60.                     
  61.                    AcroFieldss = ps.getAcroFields();  
  62.                    s.setSubstitutionFonts(fontList);  
  63.    
  64.                    s.setField("ticketId",ticket.getTicketId());  
  65.                    s.setField("ticketCreateTime",ticket.getTicketCreateTime());  
  66.                    s.setField("ticketCompany",ticket.getTicketCompany());  
  67.                    s.setField("sysName",ticket.getSysName());  
  68.                    s.setField("moneyLittle",ticket.getMoneyLittle());  
  69.                    s.setField("moneyBig",ticket.getMoneyBig());  
  70.                    s.setField("accountCompany",ticket.getAccountCompany());  
  71.                    s.setField("bedNumber",ticket.getBedNumber());  
  72.                    s.setField("username",ticket.getUsername());  
  73.                    s.setField("password",ticket.getPassword());  
  74.                     
  75.                     
  76.                    ps.setFormFlattening(true);  
  77.                    ps.close();  
  78.                     
  79.                    FileOutputStreamfos = new FileOutputStream(file);  
  80.                    fos.write(bos.toByteArray());  
  81.                    fos.close();  
  82.          }  
  83.    
  84.          /** 
  85.           * @return the templatePdfPath 
  86.           */  
  87.          publicString getTemplatePdfPath() {  
  88.                    returntemplatePdfPath;  
  89.          }  
  90.    
  91.          /** 
  92.           * @param templatePdfPath the templatePdfPathto set 
  93.           */  
  94.          publicvoid setTemplatePdfPath(String templatePdfPath) {  
  95.                    this.templatePdfPath= templatePdfPath;  
  96.          }  
  97.    
  98.          /** 
  99.           * @return the ttcPath 
  100.           */  
  101.          publicString getTtcPath() {  
  102.                    returnttcPath;  
  103.          }  
  104.    
  105.          /** 
  106.           * @param ttcPath the ttcPath to set 
  107.           */  
  108.          publicvoid setTtcPath(String ttcPath) {  
  109.                    this.ttcPath= ttcPath;  
  110.          }  
  111.    
  112.          /** 
  113.           * @return the targetPdfpath 
  114.           */  
  115.          publicString getTargetPdfpath() {  
  116.                    returntargetPdfpath;  
  117.          }  
  118.    
  119.          /** 
  120.           * @param targetPdfpath the targetPdfpath toset 
  121.           */  
  122.          publicvoid setTargetPdfpath(String targetPdfpath) {  
  123.                    this.targetPdfpath= targetPdfpath;  
  124.          }  
  125.    
  126.          /** 
  127.           * @return the ticket 
  128.           */  
  129.          publicTicket getTicket() {  
  130.                    returnticket;  
  131.          }  
  132.    
  133.          /** 
  134.           * @param ticket the ticket to set 
  135.           */  
  136.          publicvoid setTicket(Ticket ticket) {  
  137.                    this.ticket= ticket;  
  138.          }  
  139.           
  140.           
  141. }  

数据类-Ticket

[java]view plain copy
在CODE上查看代码片派生到我的代码片
  1. /** 
  2.  *@Title: Ticket.java 
  3.  *@Package: org.csun.ns.entity 
  4.  *@Description: TODO 
  5.  *@Author: chisj [email protected] 
  6.  *@Date: 2016年4月26日下午7:43:31 
  7.  *@Version V1.0 
  8.  */  
  9. package org.csun.ns.entity;  
  10.    
  11. /** 
  12.  *@ClassName: Ticket 
  13.  *@Description: TODO 
  14.  *@Author: chisj [email protected] 
  15.  *@Date: 2016年4月26日下午7:43:31 
  16.  */  
  17. public class Ticket {  
  18.    
  19.          privateString ticketId;  
  20.          privateString homesId;  
  21.          privateString ticketCreateTime;  
  22.          privateString ticketCompany;  
  23.          privateString sysName;  
  24.          privateString moneyLittle;  
  25.          privateString moneyBig;  
  26.          privateString accountCompany;  
  27.          privateString bedNumber;  
  28.          privateString username;  
  29.          privateString password;  
  30.    
  31.          publicTicket() {  
  32.                    super();  
  33.          }  
  34.           
  35.          publicTicket(String ticketId, String homesId, String ticketCreateTime,  
  36.                             StringticketCompany, String sysName, String moneyLittle,  
  37.                             StringmoneyBig, String accountCompany, String bedNumber,  
  38.                             Stringusername, String password) {  
  39.                    this.ticketId= ticketId;  
  40.                    this.homesId= homesId;  
  41.                    this.ticketCreateTime= ticketCreateTime;  
  42.                    this.ticketCompany= ticketCompany;  
  43.                    this.sysName= sysName;  
  44.                    this.moneyLittle= moneyLittle;  
  45.                    this.moneyBig= moneyBig;  
  46.                    this.accountCompany= accountCompany;  
  47.                    this.bedNumber= bedNumber;  
  48.                    this.username= username;  
  49.                    this.password= password;  
  50.          }  
  51.    
  52.          /** 
  53.           * @return the ticketId 
  54.           */  
  55.          publicString getTicketId() {  
  56.                    returnticketId;  
  57.          }  
  58.    
  59.          /** 
  60.           * @param ticketId the ticketId to set 
  61.           */  
  62.          publicvoid setTicketId(String ticketId) {  
  63.                    this.ticketId= ticketId;  
  64.          }  
  65.    
  66.          /** 
  67.           * @return the homesId 
  68.           */  
  69.          publicString getHomesId() {  
  70.                    returnhomesId;  
  71.          }  
  72.    
  73.          /** 
  74.           * @param homesId the homesId to set 
  75.           */  
  76.          publicvoid setHomesId(String homesId) {  
  77.                    this.homesId= homesId;  
  78.          }  
  79.    
  80.          /** 
  81.           * @return the ticketCreateTime 
  82.           */  
  83.          publicString getTicketCreateTime() {  
  84.                    returnticketCreateTime;  
  85.          }  
  86.    
  87.          /** 
  88.           * @param ticketCreateTime the ticketCreateTimeto set 
  89.           */  
  90.          publicvoid setTicketCreateTime(String ticketCreateTime) {  
  91.                    this.ticketCreateTime= ticketCreateTime;  
  92.          }  
  93.    
  94.          /** 
  95.           * @return the ticketCompany 
  96.           */  
  97.          publicString getTicketCompany() {  
  98.                    returnticketCompany;  
  99.          }  
  100.    
  101.          /** 
  102.           * @param ticketCompany the ticketCompany toset 
  103.           */  
  104.          publicvoid setTicketCompany(String ticketCompany) {  
  105.                    this.ticketCompany= ticketCompany;  
  106.          }  
  107.    
  108.          /** 
  109.           * @return the sysName 
  110.           */  
  111.          publicString getSysName() {  
  112.                    returnsysName;  
  113.          }  
  114.    
  115.          /** 
  116.           * @param sysName the sysName to set 
  117.           */  
  118.          publicvoid setSysName(String sysName) {  
  119.                    this.sysName= sysName;  
  120.          }  
  121.    
  122.          /** 
  123.           * @return the moneyLittle 
  124.           */  
  125.          publicString getMoneyLittle() {  
  126.                    returnmoneyLittle;  
  127.          }  
  128.    
  129.          /** 
  130.           * @param moneyLittle the moneyLittle to set 
  131.           */  
  132.          publicvoid setMoneyLittle(String moneyLittle) {  
  133.                    this.moneyLittle= moneyLittle;  
  134.          }  
  135.    
  136.          /** 
  137.           * @return the moneyBig 
  138.           */  
  139.          publicString getMoneyBig() {  
  140.                    returnmoneyBig;  
  141.          }  
  142.    
  143.          /** 
  144.           * @param moneyBig the moneyBig to set 
  145.           */  
  146.          publicvoid setMoneyBig(String moneyBig) {  
  147.                    this.moneyBig= moneyBig;  
  148.          }  
  149.    
  150.          /** 
  151.           * @return the accountCompany 
  152.           */  
  153.          publicString getAccountCompany() {  
  154.                    returnaccountCompany;  
  155.          }  
  156.    
  157.          /** 
  158.           * @param accountCompany the accountCompany toset 
  159.           */  
  160.          publicvoid setAccountCompany(String accountCompany) {  
  161.                    this.accountCompany= accountCompany;  
  162.          }  
  163.    
  164.          /** 
  165.           * @return the bedNumber 
  166.           */  
  167.          publicString getBedNumber() {  
  168.                    returnbedNumber;  
  169.          }  
  170.    
  171.          /** 
  172.           * @param bedNumber the bedNumber to set 
  173.           */  
  174.          publicvoid setBedNumber(String bedNumber) {  
  175.                    this.bedNumber= bedNumber;  
  176.          }  
  177.    
  178.          /** 
  179.           * @return the username 
  180.           */  
  181.          publicString getUsername() {  
  182.                    returnusername;  
  183.          }  
  184.    
  185.          /** 
  186.           * @param username the username to set 
  187.           */  
  188.          publicvoid setUsername(String username) {  
  189.                    this.username= username;  
  190.          }  
  191.    
  192.          /** 
  193.           * @return the password 
  194.           */  
  195.          publicString getPassword() {  
  196.                    returnpassword;  
  197.          }  
  198.    
  199.          /** 
  200.           * @param password the password to set 
  201.           */  
  202.          publicvoid setPassword(String password) {  
  203.                    this.password= password;  
  204.          }  
  205.           
  206. }  

测试类-TestTempletTicket

[java]view plain copy
在CODE上查看代码片派生到我的代码片
  1. /** 
  2.  *@Title: TestTempletTicket.java 
  3.  *@Package: org.csun.ns.util 
  4.  *@Description: TODO 
  5.  *@Author: chisj [email protected] 
  6.  *@Date: 2016年4月27日下午1:31:23 
  7.  *@Version V1.0 
  8.  */  
  9. package org.csun.ns.util;  
  10.    
  11. import java.io.File;  
  12.    
  13. import org.csun.ns.client.OSSConfigure;  
  14. import org.csun.ns.client.OSSUtil;  
  15. import org.csun.ns.entity.Ticket;  
  16.    
  17. /** 
  18.  *@ClassName: TestTempletTicket 
  19.  *@Description: TODO 
  20.  *@Author: chisj [email protected] 
  21.  *@Date: 2016年4月27日下午1:31:23 
  22.  */  
  23. public class TestTempletTicket {  
  24.    
  25.          publicstatic void main(String[] args) throws Exception {  
  26.                     
  27.                    Ticketticket = new Ticket();  
  28.                     
  29.                    ticket.setTicketId("2016042710000");  
  30.                    ticket.setTicketCreateTime("2016年4月27日");  
  31.                    ticket.setTicketCompany("武汉日创科技有限公司");  
  32.                    ticket.setSysName("智能看护系统");  
  33.                    ticket.setMoneyLittle("50,000.00");  
  34.                    ticket.setMoneyBig("伍万元整");  
  35.                    ticket.setAccountCompany("洪山福利院");  
  36.                    ticket.setBedNumber("500床位");  
  37.                    ticket.setUsername("qiu");  
  38.                    ticket.setPassword("123456");  
  39.                     
  40.                    PDFTempletTicketpdfTT = new PDFTempletTicket();  
  41.                     
  42.                   pdfTT.setTemplatePdfPath("D:\\ticket_from.pdf");  
  43.                    pdfTT.setTargetPdfpath("D:\\aaabbbccc.pdf");  
  44.                    pdfTT.setTicket(ticket);  
  45.                     
  46.                    Filefile = new File("D:\\aaabbbccc.pdf");  
  47.                    file.createNewFile();  
  48.                    pdfTT.templetTicket(file);  
  49.                     
  50.                    //OSSConfigureconfig = OSSUtil.getOSSConfigure();  
  51.        //OSSManageUtil.uploadFile(config, file, "aaabbbccc.pdf","pdf", "ticket/" + "aaabbbccc");  
  52.          
  53.        //System.out.println("path = " + config.getAccessUrl());  
  54.                     
  55.          }  
  56.           
  57. }  

导出来后的结果:

备注:导出PDF文档,From域的内容不可见问题;iText找不到字体;

问题1:我开始导出的From域内容看不到,将ps.setFormFlattening(true);设置为flase后,可以看到From域,还是看不到内容,我点击进入From后可以看到内容,该方法是将From域隐藏;后来看到有人设置From域内容的字体:BaseFontbf = BaseFont.createFont(PDFTicket.class.getResource("/") +"org/csun/ns/util/simsun.ttc,1"

                BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

以及:

s.setSubstitutionFonts(fontList);

问题2:别人的代码:

BaseFont bf = BaseFont.createFont("STSong-Light""UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);

会报找不到字体的错误,这里的解决方式就是通过使用自己的字体就好,simsun.ttc是Windows下面自带的字体(简体宋体:C:\Windows\Fonts下面有很多字体可以使用)

******************************以上是转载************************************

猜你喜欢

转载自blog.csdn.net/zhh1072773034/article/details/80251370