java中怎么利用poi和itext生成pdf文档

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java中怎么利用poi和itext生成pdf文档相关的知识,希望对你有一定的参考价值。

生成PDF文档代码如下:

package poi.itext;
import java.io.FileOutputStream;
import java.io.IOException;
import java.awt.Color;
import com.lowagie.text.*;
import com.lowagie.text.pdf.*;
import com.lowagie.text.pdf.BaseFont;
/**
 * 创建Pdf文档
 * @author Administrator
 *
 */
public class HelloPdf

    public static void main(String[] args)throws Exception
    
        BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        Font FontChinese = new Font(bfChinese, 12, Font.NORMAL);
        // 第一步,创建document对象
        Rectangle rectPageSize = new Rectangle(PageSize.A4);
        
        //下面代码设置页面横置
        //rectPageSize = rectPageSize.rotate();
        
        //创建document对象并指定边距
        Document doc = new Document(rectPageSize,50,50,50,50);
        Document document = new Document();
        try
        
            // 第二步,将Document实例和文件输出流用PdfWriter类绑定在一起
            //从而完成向Document写,即写入PDF文档
            PdfWriter.getInstance(document,new FileOutputStream("src/poi/itext/HelloWorld.pdf"));
            //第3步,打开文档
            document.open();
            //第3步,向文档添加文字. 文档由段组成
            document.add(new Paragraph("Hello World"));
            Paragraph par = new Paragraph("世界你好",FontChinese);
            document.add(par);
            PdfPTable table = new PdfPTable(3);
            for(int i=0;i<12;i++)
            
                if (i == 0)
                
                    PdfPCell cell = new PdfPCell();
                    cell.setColspan(3);
                    cell.setBackgroundColor(new Color(180,180,180));
                    cell.addElement(new Paragraph("表格头" , FontChinese));
                    table.addCell(cell);
                
                else
                
                    PdfPCell cell = new PdfPCell();
                    cell.addElement(new Paragraph("表格内容" , FontChinese));
                    table.addCell(cell);
                
            
            document.add(table);
        
        catch (DocumentException de)
        
            System.err.println(de.getMessage());
        
        catch (IOException ioe)
        
            System.err.println(ioe.getMessage());
        
        //关闭document
        document.close();
        
        System.out.println("生成HelloPdf成功!");
     
    
    

希望对你有帮助。

参考技术A 一、iText介绍 iText是着名的开放源码的站点sourceforge一个项目,是用于生成PDF文档的一个java类库。通过iText不仅可以生成PDF或rtf的文档,而且可以将XML、html文件转化为PDF文件。 iText的安装非常方便,在http://www.lowagie.com/iText/down...

Java iText使用PDF模板生成PDF文档

我们系统需要生成一个可以打印的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

/**
 *@Title: PDFTempletTicket.java
 *@Package: org.csun.ns.util
 *@Description: TODO
 *@Author: chisj chisj@foxmail.com
 *@Date: 2016年4月27日上午11:29:52
 *@Version V1.0
 */
package org.csun.ns.util;
 
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
 
import org.csun.ns.entity.Ticket;
 
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
 
/**
 *@ClassName: PDFTempletTicket
 *@Description: TODO
 *@Author: chisj chisj@foxmail.com
 *@Date: 2016年4月27日上午11:29:52
 */
public class PDFTempletTicket 
 
         privateString templatePdfPath;
         privateString ttcPath;
         privateString targetPdfpath;
         privateTicket ticket;
        
        
         publicPDFTempletTicket() 
                   super();
         
        
         publicPDFTempletTicket(String templatePdfPath, String ttcPath,
                            StringtargetPdfpath, Ticket ticket) 
                   this.templatePdfPath= templatePdfPath;
                   this.ttcPath= ttcPath;
                   this.targetPdfpath= targetPdfpath;
                   this.ticket= ticket;
         
        
         publicvoid templetTicket(File file) throws Exception 
                  
                   PdfReaderreader = new PdfReader(templatePdfPath);
                   ByteArrayOutputStreambos = new ByteArrayOutputStream();
                   PdfStamperps = new PdfStamper(reader, bos);
                  
                   /*使用中文字体 */ 
                   BaseFontbf = BaseFont.createFont(PDFTicket.class.getResource("/") +"org/csun/ns/util/simsun.ttc,1", 
                BaseFont.IDENTITY_H,BaseFont.EMBEDDED);
       ArrayList<BaseFont> fontList = newArrayList<BaseFont>(); 
       fontList.add(bf); 
                  
                   AcroFieldss = ps.getAcroFields();
                   s.setSubstitutionFonts(fontList);
 
                   s.setField("ticketId",ticket.getTicketId());
                   s.setField("ticketCreateTime",ticket.getTicketCreateTime());
                   s.setField("ticketCompany",ticket.getTicketCompany());
                   s.setField("sysName",ticket.getSysName());
                   s.setField("moneyLittle",ticket.getMoneyLittle());
                   s.setField("moneyBig",ticket.getMoneyBig());
                   s.setField("accountCompany",ticket.getAccountCompany());
                   s.setField("bedNumber",ticket.getBedNumber());
                   s.setField("username",ticket.getUsername());
                   s.setField("password",ticket.getPassword());
                  
                  
                   ps.setFormFlattening(true);
                   ps.close();
                  
                   FileOutputStreamfos = new FileOutputStream(file);
                   fos.write(bos.toByteArray());
                   fos.close();
         
 
         /**
          * @return the templatePdfPath
          */
         publicString getTemplatePdfPath() 
                   returntemplatePdfPath;
         
 
         /**
          * @param templatePdfPath the templatePdfPathto set
          */
         publicvoid setTemplatePdfPath(String templatePdfPath) 
                   this.templatePdfPath= templatePdfPath;
         
 
         /**
          * @return the ttcPath
          */
         publicString getTtcPath() 
                   returnttcPath;
         
 
         /**
          * @param ttcPath the ttcPath to set
          */
         publicvoid setTtcPath(String ttcPath) 
                   this.ttcPath= ttcPath;
         
 
         /**
          * @return the targetPdfpath
          */
         publicString getTargetPdfpath() 
                   returntargetPdfpath;
         
 
         /**
          * @param targetPdfpath the targetPdfpath toset
          */
         publicvoid setTargetPdfpath(String targetPdfpath) 
                   this.targetPdfpath= targetPdfpath;
         
 
         /**
          * @return the ticket
          */
         publicTicket getTicket() 
                   returnticket;
         
 
         /**
          * @param ticket the ticket to set
          */
         publicvoid setTicket(Ticket ticket) 
                   this.ticket= ticket;
         
        
        

数据类-Ticket

/**
 *@Title: Ticket.java
 *@Package: org.csun.ns.entity
 *@Description: TODO
 *@Author: chisj chisj@foxmail.com
 *@Date: 2016年4月26日下午7:43:31
 *@Version V1.0
 */
package org.csun.ns.entity;
 
/**
 *@ClassName: Ticket
 *@Description: TODO
 *@Author: chisj chisj@foxmail.com
 *@Date: 2016年4月26日下午7:43:31
 */
public class Ticket 
 
         privateString ticketId;
         privateString homesId;
         privateString ticketCreateTime;
         privateString ticketCompany;
         privateString sysName;
         privateString moneyLittle;
         privateString moneyBig;
         privateString accountCompany;
         privateString bedNumber;
         privateString username;
         privateString password;
 
         publicTicket() 
                   super();
         
        
         publicTicket(String ticketId, String homesId, String ticketCreateTime,
                            StringticketCompany, String sysName, String moneyLittle,
                            StringmoneyBig, String accountCompany, String bedNumber,
                            Stringusername, String password) 
                   this.ticketId= ticketId;
                   this.homesId= homesId;
                   this.ticketCreateTime= ticketCreateTime;
                   this.ticketCompany= ticketCompany;
                   this.sysName= sysName;
                   this.moneyLittle= moneyLittle;
                   this.moneyBig= moneyBig;
                   this.accountCompany= accountCompany;
                   this.bedNumber= bedNumber;
                   this.username= username;
                   this.password= password;
         
 
         /**
          * @return the ticketId
          */
         publicString getTicketId() 
                   returnticketId;
         
 
         /**
          * @param ticketId the ticketId to set
          */
         publicvoid setTicketId(String ticketId) 
                   this.ticketId= ticketId;
         
 
         /**
          * @return the homesId
          */
         publicString getHomesId() 
                   returnhomesId;
         
 
         /**
          * @param homesId the homesId to set
          */
         publicvoid setHomesId(String homesId) 
                   this.homesId= homesId;
         
 
         /**
          * @return the ticketCreateTime
          */
         publicString getTicketCreateTime() 
                   returnticketCreateTime;
         
 
         /**
          * @param ticketCreateTime the ticketCreateTimeto set
          */
         publicvoid setTicketCreateTime(String ticketCreateTime) 
                   this.ticketCreateTime= ticketCreateTime;
         
 
         /**
          * @return the ticketCompany
          */
         publicString getTicketCompany() 
                   returnticketCompany;
         
 
         /**
          * @param ticketCompany the ticketCompany toset
          */
         publicvoid setTicketCompany(String ticketCompany) 
                   this.ticketCompany= ticketCompany;
         
 
         /**
          * @return the sysName
          */
         publicString getSysName() 
                   returnsysName;
         
 
         /**
          * @param sysName the sysName to set
          */
         publicvoid setSysName(String sysName) 
                   this.sysName= sysName;
         
 
         /**
          * @return the moneyLittle
          */
         publicString getMoneyLittle() 
                   returnmoneyLittle;
         
 
         /**
          * @param moneyLittle the moneyLittle to set
          */
         publicvoid setMoneyLittle(String moneyLittle) 
                   this.moneyLittle= moneyLittle;
         
 
         /**
          * @return the moneyBig
          */
         publicString getMoneyBig() 
                   returnmoneyBig;
         
 
         /**
          * @param moneyBig the moneyBig to set
          */
         publicvoid setMoneyBig(String moneyBig) 
                   this.moneyBig= moneyBig;
         
 
         /**
          * @return the accountCompany
          */
         publicString getAccountCompany() 
                   returnaccountCompany;
         
 
         /**
          * @param accountCompany the accountCompany toset
          */
         publicvoid setAccountCompany(String accountCompany) 
                   this.accountCompany= accountCompany;
         
 
         /**
          * @return the bedNumber
          */
         publicString getBedNumber() 
                   returnbedNumber;
         
 
         /**
          * @param bedNumber the bedNumber to set
          */
         publicvoid setBedNumber(String bedNumber) 
                   this.bedNumber= bedNumber;
         
 
         /**
          * @return the username
          */
         publicString getUsername() 
                   returnusername;
         
 
         /**
          * @param username the username to set
          */
         publicvoid setUsername(String username) 
                   this.username= username;
         
 
         /**
          * @return the password
          */
         publicString getPassword() 
                   returnpassword;
         
 
         /**
          * @param password the password to set
          */
         publicvoid setPassword(String password) 
                   this.password= password;
         
        

测试类-TestTempletTicket

/**
 *@Title: TestTempletTicket.java
 *@Package: org.csun.ns.util
 *@Description: TODO
 *@Author: chisj chisj@foxmail.com
 *@Date: 2016年4月27日下午1:31:23
 *@Version V1.0
 */
package org.csun.ns.util;
 
import java.io.File;
 
import org.csun.ns.client.OSSConfigure;
import org.csun.ns.client.OSSUtil;
import org.csun.ns.entity.Ticket;
 
/**
 *@ClassName: TestTempletTicket
 *@Description: TODO
 *@Author: chisj chisj@foxmail.com
 *@Date: 2016年4月27日下午1:31:23
 */
public class TestTempletTicket 
 
         publicstatic void main(String[] args) throws Exception 
                  
                   Ticketticket = new Ticket();
                  
                   ticket.setTicketId("2016042710000");
                   ticket.setTicketCreateTime("2016年4月27日");
                   ticket.setTicketCompany("武汉日创科技有限公司");
                   ticket.setSysName("智能看护系统");
                   ticket.setMoneyLittle("50,000.00");
                   ticket.setMoneyBig("伍万元整");
                   ticket.setAccountCompany("洪山福利院");
                   ticket.setBedNumber("500床位");
                   ticket.setUsername("qiu");
                   ticket.setPassword("123456");
                  
                   PDFTempletTicketpdfTT = new PDFTempletTicket();
                  
                  pdfTT.setTemplatePdfPath("D:\\\\ticket_from.pdf");
                   pdfTT.setTargetPdfpath("D:\\\\aaabbbccc.pdf");
                   pdfTT.setTicket(ticket);
                  
                   Filefile = new File("D:\\\\aaabbbccc.pdf");
                   file.createNewFile();
                   pdfTT.templetTicket(file);
                  
                   //OSSConfigureconfig = OSSUtil.getOSSConfigure();
       //OSSManageUtil.uploadFile(config, file, "aaabbbccc.pdf","pdf", "ticket/" + "aaabbbccc");
       
       //System.out.println("path = " + config.getAccessUrl());
                  
         
        

导出来后的结果:

备注:导出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下面有很多字体可以使用)

以上是关于java中怎么利用poi和itext生成pdf文档的主要内容,如果未能解决你的问题,请参考以下文章

利用itext生成pdf的简单例子

java利用itext导出pdf

java itextpdf 5.5.6读取pdf中文文档乱码怎么解决

java itext 创建pdf,直接返回输出流做成下载,怎么做

java怎么输出pdf格式的文件

Java IText 生成PdF文档怎样设置黑体字体