1、前言html
前几天,作ASN条码收货模块,须要实现打印下载收货报表,经一番查找,选定iText--用于生成PDF文档的一个Java类库。废话很少说,进入正题。java
2、iText简介apache
iText是著名的开放源码的站点sourceforge一个项目,是用于生成PDF文档的一个java类库。经过iText不只能够生成PDF或rtf的文档,并且能够将XML、Html文件转化为PDF文件。编程
iText的安装很是方便,在http://itextpdf.com/ 网站上下载iText.jar文件后,只须要在系统的CLASSPATH中加入iText.jar的路径,在程序中就可使用iText类库了。安全
3、创建第一个PDF文档jsp
用iText生成PDF文档须要5个步骤:函数
①创建com.lowagie.text.Document对象的实例。
Document document = new Document(); 字体
②创建一个书写器(Writer)与document对象关联,经过书写器(Writer)能够将文档写入到磁盘中。
PDFWriter.getInstance(document, new FileOutputStream("Helloworld.PDF")); 网站
③打开文档。
document.open(); ui
④向文档中添加内容。
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-A十、AL、LETTER、 HALFLETTER、_11x1七、LEDGER、NOTE、B0-B五、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)对象,用于向文档中添加一段文字。
4、文本处理
iText中用文本块(Chunk)、短语(Phrase)和段落(paragraph)处理文本。
文本块(Chunk)是处理文本的最小单位,有一串带格式(包括字体、颜色、大小)的字符串组成。如如下代码就是产生一个字体为HELVETICA、大小为十、带下划线的字符串:
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为左对齐,默认为左对齐。
5、表格处理
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行代码说明了这种添加顺序。
6、图像处理
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。
7、中文处理
默认的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);
8、分页处理
若是只是简单的显示当前页码,使用如下代码便可(设定了页面的大小后,会自动分页)。
HeaderFooter footer = new HeaderFooter(new Phrase("页码:",keyfont), true); footer.setBorder(Rectangle.NO_BORDER); document.setHeader(footer);
若是要显示当前页码以及总页码。
则须要计算总页数,设定每页大小,使用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进行控制,可是却没能找到去掉表格边框的方法..........郁闷.......
9、总结
总的来讲,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"); } }