一、前言
前幾天,做ASN條碼收貨模塊,需要實現打印下載收貨報表,經一番查找,選定iText--用於生成PDF文檔的一個Java類庫。廢話不多說,進入正題。
二、iText簡介
iText是著名的開放源碼的站點sourceforge一個項目,是用於生成PDF文檔的一個java類庫。通過iText不僅可以生成PDF或rtf的文檔,而且可以將XML、Html文件轉化為PDF文件。
iText的安裝非常方便,在http://itextpdf.com/ 網站上下載iText.jar文件后,只需要在系統的CLASSPATH中加入iText.jar的路徑,在程序中就可以使用iText類庫了。
三、建立第一個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);
如果要顯示當前頁碼以及總頁碼。
則需要計算總頁數,設定每頁大小,使用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"); } }