[itext]Java生成PDF文件

一、前言

  最近在做也导出试卷的功能,刚开始是导出为doc,可是导出来格式都有变化,最后说直接将word转为pdf,可是各种不稳定,各种报错、最后想到直接将文件写入pdf(参考:http://www.cnblogs.com/qlqwjy/p/8193281.html)。经一番查找,选定iText--用于生成PDF文档的一个Java类库。

 

二、iText简介

  iText是著名的开放源码的站点sourceforge一个项目,是用于生成PDF文档的一个java类库。通过iText不仅可以生成PDF或rtf的文档,而且可以将XML、Html文件转化为PDF文件。

  iText的安装非常方便,在http://itextpdf.com/ 网站上下载iText.jar文件后,只需要在系统的CLASSPATH中加入iText.jar的路径,在程序中就可以使用iText类库了。

 

  所需jar包:

 

三、建立第一个PDF文档

  用iText生成PDF文档需要5个步骤:

  ①建立com.lowagie.text.Document对象的实例。
  Document document = new Document(); 

  ②建立一个书写器(Writer)与document对象关联,通过书写器(Writer)可以将文档写入到磁盘中。
  PDFWriter.getInstance(document, new FileOutputStream("Helloworld.PDF")); 

  ③打开文档。
  document.open(); 

  ④向文档中添加内容。
  document.add(new Paragraph("Hello World")); 

  ⑤关闭文档。
  document.close(); 

  通过上面的5个步骤,就能产生一个Helloworld.PDF的文件,文件内容为"Hello World"。

  建立com.lowagie.text.Document对象的实例

  com.lowagie.text.Document对象的构建函数有三个,分别是:
  public Document();
  public Document(Rectangle pageSize);
  public Document(Rectangle pageSize,
  int marginLeft,
  int marginRight,
  int marginTop,
  int marginBottom); 

  构建函数的参数pageSize是文档页面的大小,对于第一个构建函数,页面的大小为A4,同Document(PageSize.A4)的效 果一样;对于第三个构建函数,参数marginLeft、marginRight、marginTop、marginBottom分别为左、右、上、下的 页边距。

  通过参数pageSize可以设定页面大小、面背景色、以及页面横向/纵向等属性。iText定义了A0-A10、AL、LETTER、 HALFLETTER、_11x17、LEDGER、NOTE、B0-B5、ARCH_A-ARCH_E、FLSA 和FLSE等纸张类型,也可以通过Rectangle pageSize = new Rectangle(144, 720);自定义纸张。通过Rectangle方法rotate()可以将页面设置成横向。

  书写器(Writer)对象

  一旦文档(document)对象建立好之后,需要建立一个或多个书写器(Writer)对象与之关联。通过书写器(Writer)对象可以将 具体文档存盘成需要的格式,如com.lowagie.text.PDF.PDFWriter可以将文档存成PDF文 件,com.lowagie.text.html.HtmlWriter可以将文档存成html文件。

  设定文档属性

  在文档打开之前,可以设定文档的标题、主题、作者、关键字、装订方式、创建者、生产者、创建日期等属性,调用的方法分别是:
  public boolean addTitle(String title)
  public boolean addSubject(String subject)
  public boolean addKeywords(String keywords)
  public boolean addAuthor(String author)
  public boolean addCreator(String creator)
  public boolean addProducer()
  public boolean addCreationDate()
  public boolean addHeader(String name, String content) 

  其中方法addHeader对于PDF文档无效,addHeader仅对html文档有效,用于添加文档的头信息。
当新的页面产生之前,可以设定页面的大小、书签、脚注(HeaderFooter)等信息,调用的方法是:
  public boolean setPageSize(Rectangle pageSize)
  public boolean add(Watermark watermark)
  public void removeWatermark()
  public void setHeader(HeaderFooter header)
  public void resetHeader()
  public void setFooter(HeaderFooter footer)
  public void resetFooter()
  public void resetPageCount()
  public void setPageCount(int pageN) 

  如果要设定第一页的页面属性,这些方法必须在文档打开之前调用。

  对于PDF文档,iText还提供了文档的显示属性,通过调用书写器的setViewerPreferences方法可以控制文档打开时Acrobat Reader的显示属性,如是否单页显示、是否全屏显示、是否隐藏状态条等属性。

  另外,iText也提供了对PDF文件的安全保护,通过书写器(Writer)的setEncryption方法,可以设定文档的用户口令、只读、可打印等属性。

  添加文档内容

  所有向文档添加的内容都是以对象为单位的,如Phrase、Paragraph、Table、Graphic对象等。比较常用的是段落(Paragraph)对象,用于向文档中添加一段文字。
四、文本处理

  iText中用文本块(Chunk)、短语(Phrase)和段落(paragraph)处理文本。
文本块(Chunk)是处理文本的最小单位,有一串带格式(包括字体、颜色、大小)的字符串组成。如以下代码就是产生一个字体为HELVETICA、大小为10、带下划线的字符串:
Chunk chunk1 = new Chunk("This text is underlined", FontFactory.getFont(FontFactory.HELVETICA, 12, Font.UNDERLINE)); 

  短语(Phrase)由一个或多个文本块(Chunk)组成,短语(Phrase)也可以设定字体,但对于其中以设定过字体的文本块 (Chunk)无效。通过短语(Phrase)成员函数add可以将一个文本块(Chunk)加到短语(Phrase)中, 如:phrase6.add(chunk);

  段落(paragraph)由一个或多个文本块(Chunk)或短语(Phrase)组成,相当于WORD文档中的段落概念,同样可以设定段落 的字体大小、颜色等属性。另外也可以设定段落的首行缩进、对齐方式(左对齐、右对齐、居中对齐)。通过函数setAlignment可以设定段落的对齐方 式,setAlignment的参数1为居中对齐、2为右对齐、3为左对齐,默认为左对齐。

五、表格处理

  iText中处理表格的类为:com.lowagie.text.Table和 com.lowagie.text.PDF.PDFPTable,对于比较简单的表格处理可以用com.lowagie.text.Table,但是如果 要处理复杂的表格,这就需要com.lowagie.text.PDF.PDFPTable进行处理。这里就类 com.lowagie.text.Table进行说明。

  类com.lowagie.text.Table的构造函数有三个:

  ①Table (int columns)
  ②Table(int columns, int rows)
  ③Table(Properties attributes)

  参数columns、rows、attributes分别为表格的列数、行数、表格属性。创建表格时必须指定表格的列数,而对于行数可以不用指定。

  建立表格之后,可以设定表格的属性,如:边框宽度、边框颜色、衬距(padding space 即单元格之间的间距)大小等属性。下面通过一个简单的例子说明如何使用表格,代码如下:

Table table = new Table(3);
table.setBorderWidth(1);
table.setBorderColor(new Color(0, 0, 255));
table.setPadding(5);
table.setSpacing(5);
Cell cell = new Cell("header");
cell.setHeader(true);
cell.setColspan(3);
table.addCell(cell);
table.endHeaders();
cell = new Cell("example cell with colspan 1 and rowspan 2");
cell.setRowspan(2);
cell.setBorderColor(new Color(255, 0, 0));
table.addCell(cell);
table.addCell("1.1");
table.addCell("2.1");
table.addCell("1.2");
table.addCell("2.2");
table.addCell("cell test1");
cell = new Cell("big cell");
cell.setRowspan(2);
cell.setColspan(2);
table.addCell(cell);
table.addCell("cell test2"); 

 

  运行结果如下:
  header cell test2 

  代码1-5行用于新建一个表格,如代码所示,建立了一个列数为3的表格,并将边框宽度设为1,颜色为蓝色,衬距为5。

  代码6-10行用于设定表格的表头,第7行cell.setHeader(true);是将该单元格作为表头信息显示;第8行 cell.setColspan(3);指定了该单元格占3列;为表格添加表头信息时,要注意的是一旦表头信息添加完了之后,必须调用 endHeaders()方法,如第10行,否则当表格跨页后,表头信息不会再显示。

  代码11-14行是向表格中添加一个宽度占一列,长度占二行的单元格。

  往表格中添加单元格(cell)时,按自左向右、从上而下的次序添加。如执行完11行代码后,表格的右下方出现2行2列的空白,这是再往表格添加单元格时,先填满这个空白,然后再另起一行,15-24行代码说明了这种添加顺序。

六、图像处理

  iText中处理表格的类为com.lowagie.text.Image,目前iText支持的图像格式有:GIF, Jpeg, PNG, wmf等格式,对于不同的图像格式,iText用同样的构造函数自动识别图像格式。通过下面的代码分别获得gif、jpg、png图像的实例。
  Image gif = Image.getInstance("vonnegut.gif");
  Image jpeg = Image.getInstance("myKids.jpg");
  Image png = Image.getInstance("hitchcock.png"); 

  图像的位置

  图像的位置主要是指图像在文档中的对齐方式、图像和文本的位置关系。IText中通过函数public void setAlignment(int alignment)进行处理,参数alignment为Image.RIGHT、Image.MIDDLE、Image.LEFT分别指右对齐、居中、 左对齐;当参数alignment为Image.TEXTWRAP、Image.UNDERLYING分别指文字绕图形显示、图形作为文字的背景显示。这 两种参数可以结合以达到预期的效果,如setAlignment(Image.RIGHT|Image.TEXTWRAP)显示的效果为图像右对齐,文字 围绕图像显示。

  图像的尺寸和旋转

  如果图像在文档中不按原尺寸显示,可以通过下面的函数进行设定:
  public void scaleAbsolute(int newWidth, int newHeight)
  public void scalePercent(int percent)
  public void scalePercent(int percentX, int percentY) 

  函数public void scaleAbsolute(int newWidth, int newHeight)直接设定显示尺寸;函数public void scalePercent(int percent)设定显示比例,如scalePercent(50)表示显示的大小为原尺寸的50%;而函数scalePercent(int percentX, int percentY)则图像高宽的显示比例。

  如果图像需要旋转一定角度之后在文档中显示,可以通过函数public void setRotation(double r)设定,参数r为弧度,如果旋转角度为30度,则参数r= Math.PI / 6。

七、中文处理

  默认的iText字体设置不支持中文字体,需要下载远东字体包iTextAsian.jar,否则不能往PDF文档中输出中文字体。通过下面的代码就可以在文档中使用中文了:
  BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
  com.lowagie.text.Font FontChinese = new com.lowagie.text.Font(bfChinese, 12, com.lowagie.text.Font.NORMAL);
  Paragraph pragraph=new Paragraph("你好", FontChinese); 

八、分页处理

  如果只是简单的显示当前页码,使用以下代码即可(设定了页面的大小后,会自动分页)。

HeaderFooter footer = new HeaderFooter(new Phrase("页码:",keyfont), true); 
footer.setBorder(Rectangle.NO_BORDER); 
document.setHeader(footer);

 

 

或者:

        //3.1添加页号
        HeaderFooter footer = new HeaderFooter(new Phrase("第",textfont), new Phrase("页",textfont));      
        footer.setBorder(Rectangle.NO_BORDER);    
        document.setFooter(footer);  
        //3.2打开文档
        document.open();

  如果要显示当前页码以及总页码。

  则需要计算总页数,设定每页大小,使用pdf.newPage( )手动分页。

  详见一下代码:

 

package com.foster;
 
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
 
import com.lowagie.text.Cell;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Font;
import com.lowagie.text.HeaderFooter;
import com.lowagie.text.Image;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Table;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfWriter;
 
public class PDFReport {
 
     
    public static void main(String[] args) throws Exception, DocumentException {
         
        List<String> ponum=new ArrayList<String>();
        add(ponum, 26);
        List<String> line=new ArrayList<String>();
        add(line, 26);
        List<String> part=new ArrayList<String>();
        add(part, 26);
        List<String> description=new ArrayList<String>();
        add(description, 26);
        List<String> origin=new ArrayList<String>();
        add(origin, 26);
         
        //Create Document Instance
        Document document=new Document();
         
        //add Chinese font
        BaseFont bfChinese=BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
         
        //Font headfont=new Font(bfChinese,10,Font.BOLD);
        Font keyfont=new Font(bfChinese,8,Font.BOLD);
        Font textfont=new Font(bfChinese,8,Font.NORMAL);
         
        //Create Writer associated with document
        PdfWriter.getInstance(document, new FileOutputStream(new File("D:\\POReceiveReport.pdf")));
         
        document.open();
         
        //Seperate Page controller
        int recordPerPage=10;
        int fullPageRequired=ponum.size()/recordPerPage;
        int remainPage=ponum.size()%recordPerPage>1?1:0;
        int totalPage=fullPageRequired+remainPage;
         
        for(int j=0;j<totalPage;j++){
            document.newPage();
             
            //create page number
            String pageNo=leftPad("页码: "+(j+1)+" / "+totalPage,615);
            Paragraph pageNumber=new Paragraph(pageNo, keyfont) ;
            document.add(pageNumber);
             
            //create title image
            Image jpeg=Image.getInstance("D:\\title.JPG");
            jpeg.setAlignment(Image.ALIGN_CENTER);
            jpeg.scaleAbsolute(530, 37);
            document.add(jpeg);
             
            //header information
            Table tHeader=new Table(2);
            float[] widthsHeader={2f,3f};
            tHeader.setWidths(widthsHeader);
            tHeader.setWidth(100);
            tHeader.getDefaultCell().setBorder(PdfPCell.NO_BORDER);
             
             
            String compAdd="河源市高新技术开发区兴业大道中66号";
            String company="丰达音响(河源)有限公司";
            String vendor="V006";
            String vendorName="中山市卢氏五金有限公司";
            String ccn="FHH";
            String mas_loc="FHH";
            String delivery_note="20130718001";
            String receive_date="20130718";
            String dept="H11";
            String asn="0123456789";
             
             
            Cell c1Header=new Cell(new Paragraph("地址:"+compAdd,keyfont));
            tHeader.addCell(c1Header);
            c1Header=new Cell(new Paragraph("供应商:"+vendor,keyfont));
            tHeader.addCell(c1Header);
            c1Header=new Cell(new Paragraph("公司:"+company,keyfont));
            tHeader.addCell(c1Header);
            c1Header=new Cell(new Paragraph("供应商工厂:"+vendorName,keyfont));
            tHeader.addCell(c1Header);
            c1Header = new Cell(new Paragraph("CCN:   "+ccn+"    Master Loc:   "+mas_loc,keyfont));
            tHeader.addCell(c1Header);
            c1Header = new Cell(new Paragraph("送货编号: "+delivery_note+"                             送货日期: "+receive_date,keyfont));
            tHeader.addCell(c1Header);
            c1Header=new Cell(new Paragraph("Dept:"+dept,keyfont));
            tHeader.addCell(c1Header);
            c1Header=new Cell(new Paragraph("ASN#:"+asn,keyfont));
            tHeader.addCell(c1Header);
            document.add(tHeader);
             
            //record header field
            Table t=new Table(5);
            float[] widths={1.5f,1f,1f,1.5f,1f};
            t.setWidths(widths);
            t.setWidth(100);
            t.getDefaultCell().setBorder(PdfPCell.NO_BORDER);
            Cell c1 = new Cell(new Paragraph("PO#",keyfont));
            t.addCell(c1);
            c1 = new Cell(new Paragraph("Line",keyfont));
            t.addCell(c1);
            c1 = new Cell(new Paragraph("Part#",keyfont));
            t.addCell(c1);
            c1 = new Cell(new Paragraph("Description",keyfont));
            t.addCell(c1);
            c1 = new Cell(new Paragraph("Origin",keyfont));
            t.addCell(c1);
             
            //calculate the real records within a page ,to calculate the last record number of every page
            int maxRecordInPage= j+1 ==totalPage ? (remainPage==0?recordPerPage:(ponum.size()%recordPerPage)):recordPerPage;
             
            for(int i=j*recordPerPage;i<((j*recordPerPage)+maxRecordInPage);i++){
                Cell c2=new Cell(new Paragraph(ponum.get(i), textfont));
                t.addCell(c2);
                c2=new Cell(new Paragraph(line.get(i), textfont));
                t.addCell(c2);
                c2=new Cell(new Paragraph(part.get(i), textfont));
                t.addCell(c2);
                c2=new Cell(new Paragraph(description.get(i), textfont));
                t.addCell(c2);
                c2=new Cell(new Paragraph(origin.get(i), textfont));
                t.addCell(c2);
            }
            document.add(t);
             
            if(j+1==totalPage){
 
                Paragraph foot11 = new Paragraph("文件只作  Foster 收貨用"+printBlank(150)+"__________________________",keyfont);
                document.add(foot11);
                Paragraph foot12 = new Paragraph("Printed from Foster supplier portal"+printBlank(134)+company+printBlank(40)+"版本: 1.0",keyfont);
                document.add(foot12);
                HeaderFooter footer11=new HeaderFooter(foot11, true);
                footer11.setAlignment(HeaderFooter.ALIGN_BOTTOM);
                HeaderFooter footer12=new HeaderFooter(foot12, true);
                footer12.setAlignment(HeaderFooter.ALIGN_BOTTOM);
            }
        }
        document.close();
    }
     
    public static String leftPad(String str, int i) {
        int addSpaceNo = i-str.length();
        String space = "";
        for (int k=0; k<addSpaceNo; k++){
                space= " "+space;
        };
        String result =space + str ;
        return result;
     }
     
    public static void add(List<String> list,int num){
        for(int i=0;i<num;i++){
            list.add("test"+i);
        }
    }
     
    public static String printBlank(int tmp){
          String space="";
          for(int m=0;m<tmp;m++){
              space=space+" ";
          }
          return space;
    }
 
}

 

  为了使副标题严格对齐,使用了表格table进行控制,但是却没能找到去掉表格边框的方法..........郁闷.......

九、总结 

  总的来说,iText是一套java环境下不错的制作PDF的组件。因为iText支持jsp/javabean下的开发,这使得B/S应用中 的报表问题能得到很好的解决。由于iText毕竟不是专门为制作报表设计,所有报表中的内容、格式都需要通过写代码实现,相对于那些专业的支持可视化设计 的报表软件来说,编程的工作量就有一定程度的增加。

 

 

下面是生成PDF文件的示例代码:

需要导入itext.jar和iTextAsian.jar  下载地址:http://sourceforge.net/projects/itext/files/

import java.awt.Color; 
import java.io.File; 
import java.io.FileNotFoundException; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.text.DecimalFormat; 
import java.text.NumberFormat; 
import java.util.ArrayList; 
import java.util.Date; 
   
import com.lowagie.text.Document; 
import com.lowagie.text.DocumentException; 
import com.lowagie.text.Element; 
import com.lowagie.text.Font; 
import com.lowagie.text.PageSize; 
import com.lowagie.text.Paragraph; 
import com.lowagie.text.Phrase; 
import com.lowagie.text.pdf.BaseFont; 
import com.lowagie.text.pdf.PdfCell; 
import com.lowagie.text.pdf.PdfPCell; 
import com.lowagie.text.pdf.PdfPRow; 
import com.lowagie.text.pdf.PdfPTable; 
import com.lowagie.text.pdf.PdfWriter; 
import com.sun.java_cup.internal.internal_error; 
   
public class PDFReport{ 
    Document document = new Document();// 建立一个Document对象     
       
    private static Font headfont ;// 设置字体大小 
    private static Font keyfont;// 设置字体大小 
    private static Font textfont;// 设置字体大小 
       
   
       
    static{ 
        BaseFont bfChinese; 
        try { 
            //bfChinese = BaseFont.createFont("STSong-Light","UniGB-UCS2-H",BaseFont.NOT_EMBEDDED); 
            bfChinese = BaseFont.createFont("STSong-Light","UniGB-UCS2-H",BaseFont.NOT_EMBEDDED); 
            headfont = new Font(bfChinese, 10, Font.BOLD);// 设置字体大小 
            keyfont = new Font(bfChinese, 8, Font.BOLD);// 设置字体大小 
            textfont = new Font(bfChinese, 8, Font.NORMAL);// 设置字体大小 
        } catch (Exception e) {          
            e.printStackTrace(); 
        }  
    } 
       
       
    public PDFReport(File file) {         
         document.setPageSize(PageSize.A4);// 设置页面大小 
         try { 
            PdfWriter.getInstance(document,new FileOutputStream(file)); 
            document.open();  
        } catch (Exception e) { 
            e.printStackTrace(); 
        }  
           
           
    } 
    int maxWidth = 520; 
       
       
     public PdfPCell createCell(String value,com.lowagie.text.Font font,int align){ 
         PdfPCell cell = new PdfPCell(); 
         cell.setVerticalAlignment(Element.ALIGN_MIDDLE);         
         cell.setHorizontalAlignment(align);     
         cell.setPhrase(new Phrase(value,font)); 
        return cell; 
    } 
       
     public PdfPCell createCell(String value,com.lowagie.text.Font font){ 
         PdfPCell cell = new PdfPCell(); 
         cell.setVerticalAlignment(Element.ALIGN_MIDDLE); 
         cell.setHorizontalAlignment(Element.ALIGN_CENTER);  
         cell.setPhrase(new Phrase(value,font)); 
        return cell; 
    } 
   
     public PdfPCell createCell(String value,com.lowagie.text.Font font,int align,int colspan){ 
         PdfPCell cell = new PdfPCell(); 
         cell.setVerticalAlignment(Element.ALIGN_MIDDLE); 
         cell.setHorizontalAlignment(align);     
         cell.setColspan(colspan); 
         cell.setPhrase(new Phrase(value,font)); 
        return cell; 
    } 
    public PdfPCell createCell(String value,com.lowagie.text.Font font,int align,int colspan,boolean boderFlag){ 
         PdfPCell cell = new PdfPCell(); 
         cell.setVerticalAlignment(Element.ALIGN_MIDDLE); 
         cell.setHorizontalAlignment(align);     
         cell.setColspan(colspan); 
         cell.setPhrase(new Phrase(value,font)); 
         cell.setPadding(3.0f); 
         if(!boderFlag){ 
             cell.setBorder(0); 
             cell.setPaddingTop(15.0f); 
             cell.setPaddingBottom(8.0f); 
         } 
        return cell; 
    } 
     public PdfPTable createTable(int colNumber){ 
        PdfPTable table = new PdfPTable(colNumber); 
        try{ 
            table.setTotalWidth(maxWidth); 
            table.setLockedWidth(true); 
            table.setHorizontalAlignment(Element.ALIGN_CENTER);      
            table.getDefaultCell().setBorder(1); 
        }catch(Exception e){ 
            e.printStackTrace(); 
        } 
        return table; 
    } 
     public PdfPTable createTable(float[] widths){ 
            PdfPTable table = new PdfPTable(widths); 
            try{ 
                table.setTotalWidth(maxWidth); 
                table.setLockedWidth(true); 
                table.setHorizontalAlignment(Element.ALIGN_CENTER);      
                table.getDefaultCell().setBorder(1); 
            }catch(Exception e){ 
                e.printStackTrace(); 
            } 
            return table; 
        } 
       
     public PdfPTable createBlankTable(){ 
         PdfPTable table = new PdfPTable(1); 
         table.getDefaultCell().setBorder(0); 
         table.addCell(createCell("", keyfont));          
         table.setSpacingAfter(20.0f); 
         table.setSpacingBefore(20.0f); 
         return table; 
     } 
        
     public void generatePDF() throws Exception{ 
        PdfPTable table = createTable(4); 
        table.addCell(createCell("学生信息列表:", keyfont,Element.ALIGN_LEFT,4,false)); 
               
        table.addCell(createCell("姓名", keyfont, Element.ALIGN_CENTER)); 
        table.addCell(createCell("年龄", keyfont, Element.ALIGN_CENTER)); 
        table.addCell(createCell("性别", keyfont, Element.ALIGN_CENTER)); 
        table.addCell(createCell("住址", keyfont, Element.ALIGN_CENTER)); 
           
        for(int i=0;i<5;i++){ 
            table.addCell(createCell("姓名"+i, textfont)); 
            table.addCell(createCell(i+15+"", textfont)); 
            table.addCell(createCell((i%2==0)?"男":"女", textfont)); 
            table.addCell(createCell("地址"+i, textfont)); 
        } 
        document.add(table); 
           
        document.close(); 
     } 
        
     public static void main(String[] args) throws Exception { 
         File file = new File("D:\\text.pdf"); 
         file.createNewFile(); 
        new PDFReport(file).generatePDF();       
    } 
       
       
}

 

另外一个示例:

import java.awt.Color;
import java.io.FileOutputStream;
 
import org.apache.tools.ant.Main;
 
import com.lowagie.text.Chapter;
import com.lowagie.text.Document;
import com.lowagie.text.Font;
import com.lowagie.text.FontFactory;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Section;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfWriter;
 
public class PdfTwo {
    private static Font headfont ;// 设置字体大小
    private static Font keyfont;// 设置字体大小
    private static Font textfont;// 设置字体大小
 
    static{
        BaseFont bfChinese;
        try {
            //bfChinese = BaseFont.createFont("STSong-Light","UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);
            bfChinese = BaseFont.createFont("STSong-Light","UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);
            headfont = new Font(bfChinese, 10, Font.BOLD);// 设置字体大小
            keyfont = new Font(bfChinese, 8, Font.BOLD);// 设置字体大小
            textfont = new Font(bfChinese, 8, Font.NORMAL);// 设置字体大小
        } catch (Exception e) {         
            e.printStackTrace();
        } 
    }
public  void writeSimplePdf() throws Exception{
//1.新建document对象
//第一个参数是页面大小。接下来的参数分别是左、右、上和下页边距。
Document document = new Document(PageSize.A4, 50, 50, 50, 50);
//2.建立一个书写器(Writer)与document对象关联,通过书写器(Writer)可以将文档写入到磁盘中。
//创建 PdfWriter 对象 第一个参数是对文档对象的引用,第二个参数是文件的实际名称,在该名称中还会给出其输出路径。
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("C:\\ITextTest.pdf"));
//3.打开文档
document.open();
//4.向文档中添加内容
//通过 com.lowagie.text.Paragraph 来添加文本。可以用文本及其默认的字体、颜色、大小等等设置来创建一个默认段落
document.add(new Paragraph("First page of the document."));
document.add(new Paragraph("Some more text on the first page with different color and font type.",
FontFactory.getFont(FontFactory.COURIER, 14, Font.BOLD, new Color(255, 150, 200))));
//5.关闭文档
document.close();
}
public void writeCharpter() throws Exception{
//新建document对象  第一个参数是页面大小。接下来的参数分别是左、右、上和下页边距。
Document document = new Document(PageSize.A4, 20, 20, 20, 20);
//建立一个书写器(Writer)与document对象关联,通过书写器(Writer)可以将文档写入到磁盘中。
PdfWriter writer = PdfWriter.getInstance(document,new FileOutputStream("c:\\ITextTest.pdf"));
//打开文件
document.open();
//标题
document.add(new Paragraph("\n11111111111111111111111111111111111111"));
 
document.addTitle("Hello mingri example");
//作者
document.addAuthor("wolf");
//主题
document.addSubject("This example explains how to add metadata.");
document.addKeywords("iText, Hello mingri");
document.addCreator("My program using iText");
// document.newPage();
//向文档中添加内容
document.add(new Paragraph("\n22222222222222222222222222222222222222222222222222222222222222222"));
document.add(new Paragraph("\n"));
document.add(new Paragraph("\n"));
document.add(new Paragraph("\n"));
document.add(new Paragraph("\n"));
document.add(new Paragraph("\n"));
document.add(new Paragraph("First page of the document.",keyfont));
document.add(new Paragraph("First page of the document."));
document.add(new Paragraph("First page of the document."));
document.add(new Paragraph("First page of the document."));
document.add(new Paragraph("Some more text on the first page with different color and font type.",
FontFactory.getFont(FontFactory.defaultEncoding, 10,Font.BOLD, new Color(0, 0, 0))));
Paragraph title1 = new Paragraph("Chapter 1",
FontFactory.getFont(FontFactory.HELVETICA, 18, Font.BOLDITALIC, new Color(0, 0,255)));
//新建章节
Chapter chapter1 = new Chapter(title1, 1);
chapter1.setNumberDepth(0);
Paragraph title11 = new Paragraph("This is Section 1 in Chapter 1",
FontFactory.getFont(FontFactory.HELVETICA, 16, Font.BOLD,new Color(255, 0, 0)));
Section section1 = chapter1.addSection(title11);
Paragraph someSectionText = new Paragraph("This text comes as part of section 1 of chapter 1.");
section1.add(someSectionText);
someSectionText = new Paragraph("Following is a 3 X 2 table.");
section1.add(someSectionText);
document.add(chapter1);
//关闭文档
document.close();
}
public  void writePdf(String title,String cont,String createTime,String authorName) throws Exception{
//1.新建document对象
//第一个参数是页面大小。接下来的参数分别是左、右、上和下页边距。
Document document = new Document(PageSize.A4, 50, 50, 50, 50);
//2.建立一个书写器(Writer)与document对象关联,通过书写器(Writer)可以将文档写入到磁盘中。
//创建 PdfWriter 对象 第一个参数是对文档对象的引用,第二个参数是文件的实际名称,在该名称中还会给出其输出路径。
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("C:\\ITextTest.pdf"));
//3.打开文档
document.open();
//4.向文档中添加内容
//通过 com.lowagie.text.Paragraph 来添加文本。可以用文本及其默认的字体、颜色、大小等等设置来创建一个默认段落
Paragraph pt=new Paragraph("zhong:-"+title,keyfont);//设置字体样式
pt.setAlignment(1);//设置文字居中 0靠左   1,居中     2,靠右
document.add(pt);
document.add(new Paragraph("\n"));
pt=new Paragraph(createTime+"\t\t\t\t\t\t"+authorName,keyfont);
pt.setAlignment(2);
document.add(pt);
document.add(new Paragraph("\n"));
document.add(new Paragraph(createTime+"\t\t\t\t\t\t"+authorName,keyfont));
document.add(new Paragraph("\n"));
document.add(new Paragraph("Some more text on the 胜多负少的身份的分公司的风格发的电饭锅的分公司的分公司的的分公司电饭锅是的分公司的风格的分公司的分公司的复合弓好几顿饭发的寡鹄单凫过好地方风格和的发干活的风格和发干活的风格和地方过电饭锅好地方干活的风格和电饭锅好地方干活负少的身份的分公司的风格发的电饭锅的分公司的分公司的的分公司电饭锅是的分公司的风格的分公司的分公司的复合弓好几顿饭发的寡鹄单凫过好地方风格和的发干活的风格和发干活的风格和地方过电饭锅好地方干活的风格和电饭锅好地方干活负少的身份的分公司的风格发的电饭锅的分公司的分公司的的分公司电饭锅是的分公司的风格的分公司的分公司的复合弓好几顿饭发的寡鹄单凫过好地方风格和的发干活的风格和发干活的风格和地方过电饭锅好地方干活的风格和电饭锅好地方干活的风格和符合斯蒂夫 first page with different color andsdfsadfffffffffffffffffffffffffff font type.",
keyfont));
//5.关闭文档
document.close();
}
   public static void main(String[] args) throws Exception {
  System.out.println("begin");
  PdfTwo ppt=new PdfTwo();
  ppt.writePdf("fgh--标题--dfg23fgh","sdfsdfasdfasdfsdfasdf","时间","作者");
  System.out.println("end");
}
 
}

 

 

 

最后附一个完整的将数据写到pdf然后提供下载的代码:

ExportPaperPdfUtil.java  (生成pdf的工具类)

package cn.xm.exam.utils;

import java.io.FileOutputStream;
import java.util.List;

import com.lowagie.text.Document;
import com.lowagie.text.Font;
import com.lowagie.text.HeaderFooter;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Phrase;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfWriter;

import cn.xm.exam.bean.exam.Bigquestion;
import cn.xm.exam.bean.exam.Exampaper;
import cn.xm.exam.bean.exam.Exampaperoption;
import cn.xm.exam.bean.exam.Exampaperquestion;

/**
 * 将试卷写入pdf的工具类
 * 
 * @author QiaoLiQiang
 * @time 2018年1月6日上午11:32:25
 */
public class ExportPaperPdfUtil {
    private static Font headfont;// 设置字体大小
    private static Font keyfont;// 设置字体大小
    private static Font textfont;// 设置字体大小

    static {
        BaseFont bfChinese;
        try {
            // bfChinese =
            // BaseFont.createFont("STSong-Light","UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);
            bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            headfont = new Font(bfChinese, 10, Font.BOLD);// 设置字体大小
            keyfont = new Font(bfChinese, 9, Font.BOLD);// 设置字体大小
            textfont = new Font(bfChinese, 8, Font.NORMAL);// 设置字体大小
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 将一份试卷写到指定的位置为pdf
     * 
     * @param exampaper
     *            数据源
     * @param url
     *            写到位置的pdf的全路径
     * @throws Exception
     */
    public static void writeExampaperPdf(Exampaper exampaper, String url) throws Exception {
        // 1.新建document对象
        // 第一个参数是页面大小。接下来的参数分别是左、右、上和下页边距。
        Document document = new Document(PageSize.A4, 50, 50, 50, 50);
        // 2.建立一个书写器(Writer)与document对象关联,通过书写器(Writer)可以将文档写入到磁盘中。
        // 创建 PdfWriter 对象 第一个参数是对文档对象的引用,第二个参数是文件的实际名称,在该名称中还会给出其输出路径。
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(url));
        // 3.添加页号打开文档
        //3.1添加页号
        HeaderFooter footer = new HeaderFooter(new Phrase("第",textfont), new Phrase("页",textfont));      
        footer.setBorder(Rectangle.NO_BORDER);    
        document.setFooter(footer);  
        //3.2打开文档
        document.open();
        // 4.向文档中添加内容
        // 通过 com.lowagie.text.Paragraph 来添加文本。可以用文本及其默认的字体、颜色、大小等等设置来创建一个默认段落
        Paragraph pt = new Paragraph(exampaper.getTitle(), headfont);// 将标题写进去
        pt.setAlignment(1);// 设置文字居中 0靠左 1,居中 2,靠右
        document.add(pt);
        List<Bigquestion> bigQuestions = exampaper.getBigQuestions();
        for (int i = 0; bigQuestions != null && i < bigQuestions.size(); i++) {
            document.add(new Paragraph("\n"));// 添加段落分隔符 换行
            document.add(new Paragraph(bigQuestions.get(i).getBigquestionname(),keyfont));// 大题题干写进去
            List<Exampaperquestion> questions = bigQuestions.get(i).getQuestions();
            for (int j = 0; questions != null && j < questions.size(); j++) {
//                document.add(new Paragraph("\n"));// 添加段落分隔符 换行
                document.add(new Paragraph(questions.get(j).getQuestionsequence().toString() + ".\t"
                        + questions.get(j).getQuestioncontent(),textfont));// 将小题的题干与序号写进去
                List<Exampaperoption> options = questions.get(j).getOptions();// 获取选项
                for (int k = 0; options != null && k < options.size(); k++) {
//                    document.add(new Paragraph("\n"));// 添加段落分隔符 换行
                    document.add(new Paragraph("\t"+
                            options.get(k).getOptionsequence() + "\t" + options.get(k).getOptioncontent(),textfont));// 将选项序号与题干写进去
                }
            }

        }
        // 5.关闭文档
        document.close();
    }
}

 

ExtExamPaperAction.java     调用工具类生成pdf并打开流提供下载

package cn.xm.exam.action.exam.exam;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionSupport;

import cn.xm.exam.bean.exam.Exampaper;
import cn.xm.exam.service.exam.examPaper.ExamPaperService;
import cn.xm.exam.utils.ExportPaperPdfUtil;
import cn.xm.exam.utils.RemoveHtmlTag;
import cn.xm.exam.utils.Word2PdfUtil;
import freemarker.template.Configuration;
import freemarker.template.Template;

/**
 * 导出试卷 1.查出数据 2.Word 3.打开流,提供下载
 * 
 * @author QiaoLiQiang
 * @time 2017年10月31日下午10:29:51
 */
@Controller
@Scope("prototype")
@SuppressWarnings("all")
public class ExtExamPaperAction extends ActionSupport {
    private Logger logger = Logger.getLogger(FindExamAction.class);
    private String fileName;// 导出的Excel名称
    @Autowired
    private ExamPaperService examPaperService;
    // 1.查数据
    private String paperId;

    public Exampaper findPaperAllInfoById() {
        Exampaper paper = null;
        try {
            paper = RemoveHtmlTag.removePaperTag(examPaperService.getPaperAllInfoByPaperId(paperId));
        } catch (SQLException e) {
            logger.error("查询试卷所有信息出错!!!", e);
        }
        return paper;
    }

    // 2.写入Word
    public void writeExamPaper2Word(Exampaper paper) {
        // 获取路径
        String path = ServletActionContext.getServletContext().getRealPath("/files/papers");
        // 用于携带数据的map
        String filePath = path + "\\" + fileName + ".pdf";
        // Configuration用于读取ftl文件
        // 输出文档路径及名称
        File outFile = new File(filePath);
        // 获取文件的父文件夹并删除文件夹下面的文件
        File parentFile = outFile.getParentFile();
        // 获取父文件夹下面的所有文件
        File[] listFiles = parentFile.listFiles();
        if (parentFile != null && parentFile.isDirectory()) {
            for (File fi : listFiles) {
                // 删除文件
                fi.delete();
            }
        }
        try {
            // 调用工具类写到pdf
            ExportPaperPdfUtil.writeExampaperPdf(paper, filePath);
        } catch (Exception e) {
            logger.error("试卷写入pdf出错", e);
        }
    }

    // 3.打开文件的流提供下载
    public InputStream getInputStream() throws Exception {
        Exampaper paper = this.findPaperAllInfoById();// 查数据
        this.writeExamPaper2Word(paper);// 写入数据
        String path = ServletActionContext.getServletContext().getRealPath("/files/papers");
        String destPath = path + "\\" + fileName + ".pdf";
        File file = new File(destPath);
        // 只用返回一个输入流
        return FileUtils.openInputStream(file);// 打开文件
    }

    // 文件下载名
    public String getDownloadFileName() {
        String downloadFileName = "";
        String filename = fileName + ".pdf";
        try {
            downloadFileName = new String(filename.getBytes(), "ISO8859-1");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return downloadFileName;
    }

    @Override
    public String execute() throws Exception {
        // 先将名字设为秒数产生唯一的名字
        // this.setFileName(String.valueOf(System.currentTimeMillis()));
        this.setFileName("考试试卷");
        return super.execute();
    }

    // get,set方法
    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public String getPaperId() {
        return paperId;
    }

    public void setPaperId(String paperId) {
        this.paperId = paperId;
    }

}

 

struts配置

        <!-- 导出试卷信息 -->
        <action name="extPaper" class="extExamPaperAction">
            <result type="stream">
                <!-- 其他的参数在类中设置或者使用默认 -->
                <param name="contentType">application/octet-stream</param>
                <param name="inputName">inputStream</param>
                <param name="contentDisposition">attachment;filename="${downloadFileName}"</param>
                <param name="bufferSize">8192</param>
            </result>
        </action>

 

 

结果:

 

posted @ 2018-01-06 13:32  QiaoZhi  阅读(61242)  评论(4编辑  收藏  举报