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"); } }