一、iText介紹iText是著名的開放源碼的站點sourceforge一個項目,是用於生成PDF文檔的一個java類庫。通過iText不僅可以生成PDF或rtf的文檔,而且可以將XML、Html文件轉化為PDF文件。iText的安裝非常方便,在http://www.lowagie.com/iText/download.html-download網站上下載iText.jar文件後,只需要在系統的CLASSPATH中加入iText.jar的路徑,在程序中就可以使用iText類庫了。二、建立第一個PDF文檔用iText生成PDF文檔需要5個步驟:①建立com.lowagie.text.Document對象的實例。Documentdocument=newDocument();②建立一個書寫器(Writer)與document對象關聯,通過書寫器(Writer)可以將文檔寫入到磁碟中。PDFWriter.getInstance(document,newFileOutputStream("Helloworld.PDF"));③打開文檔。document.open();④向文檔中添加內容。document.add(newParagraph("HelloWorld"));⑤關閉文檔。document.close();通過上面的5個步驟,就能產生一個Helloworld.PDF的文件,文件內容為"HelloWorld"。建立com.lowagie.text.Document對象的實例com.lowagie.text.Document對象的構建函數有三個,分別是:publicDocument();publicDocument(RectanglepageSize);publicDocument(RectanglepageSize,intmarginLeft,intmarginRight,intmarginTop,intmarginBottom);構建函數的參數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等紙張類型,也可以通過RectanglepageSize=newRectangle(144,720);自定義紙張。通過Rectangle方法rotate()可以將頁面設置成橫向。書寫器(Writer)對象一旦文檔(document)對象建立好之後,需要建立一個或多個書寫器(Writer)對象與之關聯。通過書寫器(Writer)對象可以將具體文檔存檔成需要的格式,如com.lowagie.text.PDF.PDFWriter可以將文檔存成PDF文件,com.lowagie.text.html.HtmlWriter可以將文檔存成html文件。設定文檔屬性在文檔打開之前,可以設定文檔的標題、主題、作者、關鍵字、裝訂方式、創建者、生產者、創建日期等屬性,調用的方法分別是:publicbooleanaddTitle(Stringtitle)publicbooleanaddSubject(Stringsubject)publicbooleanaddKeywords(Stringkeywords)publicbooleanaddAuthor(Stringauthor)publicbooleanaddCreator(Stringcreator)publicbooleanaddProcer()publicbooleanaddCreationDate()publicbooleanaddHeader(Stringname,Stringcontent)其中方法addHeader對於PDF文檔無效,addHeader僅對html文檔有效,用於添加文檔的頭信息。當新的頁面產生之前,可以設定頁面的大小、書簽、腳注(HeaderFooter)等信息,調用的方法是:publicbooleansetPageSize(RectanglepageSize)publicbooleanadd(Watermarkwatermark)publicvoidremoveWatermark()publicvoidsetHeader(HeaderFooterheader)publicvoidresetHeader()publicvoidsetFooter(HeaderFooterfooter)publicvoidresetFooter()publicvoidresetPageCount()publicvoidsetPageCount(intpageN)如果要設定第一頁的頁面屬性,這些方法必須在文檔打開之前調用。對於PDF文檔,iText還提供了文檔的顯示屬性,通過調用書寫器的setViewerPreferences方法可以控制文檔打開時AcrobatReader的顯示屬性,如是否單頁顯示、是否全屏顯示、是否隱藏狀態條等屬性。另外,iText也提供了對PDF文件的安全保護,通過書寫器(Writer)的setEncryption方法,可以設定文檔的用戶口令、只讀、可列印等屬性。添加文檔內容所有向文檔添加的內容都是以對象為單位的,如Phrase、Paragraph、Table、Graphic對象等。比較常用的是段落(Paragraph)對象,用於向文檔中添加一段文字。三、文本處理iText中用文本塊(Chunk)、短語(Phrase)和段落(paragraph)處理文本。文本塊(Chunk)是處理文本的最小單位,有一串帶格式(包括字體、顏色、大小)的字元串組成。如以下代碼就是產生一個字體為HELVETICA、大小為10、帶下劃線的字元串:Chunkchunk1=newChunk("Thistextisunderlined",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(intcolumns)②Table(intcolumns,introws)③Table(Propertiesattributes)參數columns、rows、attributes分別為表格的列數、行數、表格屬性。創建表格時必須指定表格的列數,而對於行數可以不用指定。建立表格之後,可以設定表格的屬性,如:邊框寬度、邊框顏色、襯距(paddingspace即單元格之間的間距)大小等屬性。下面通過一個簡單的例子說明如何使用表格,代碼如下:1:Tabletable=newTable(3);2:table.setBorderWidth(1);3:table.setBorderColor(newColor(0,0,255));4:table.setPadding(5);5:table.setSpacing(5);6:Cellcell=newCell("header");7:cell.setHeader(true);8:cell.setColspan(3);9:table.addCell(cell);10:table.endHeaders();11:cell=newCell("");12:cell.setRowspan(2);13:cell.setBorderColor(newColor(255,0,0));14:table.addCell(cell);15:table.addCell("1.1");16:table.addCell("2.1");17:table.addCell("1.2");18:table.addCell("2.2");19:table.addCell("celltest1");20:cell=newCell("bigcell");21:cell.setRowspan(2);22:cell.setColspan(2);23:table.addCell(cell);24:table.addCell("celltest2");運行結果如下:header1.12.11.22.2celltest1bigcellcelltest2代碼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圖像的實例。Imagegif=Image.getInstance("vonnegut.gif");Imagejpeg=Image.getInstance("myKids.jpg");Imagepng=Image.getInstance("hitchcock.png");圖像的位置圖像的位置主要是指圖像在文檔中的對齊方式、圖像和文本的位置關系。IText中通過函數publicvoidsetAlignment(intalignment)進行處理,參數alignment為Image.RIGHT、Image.MIDDLE、Image.LEFT分別指右對齊、居中、左對齊;當參數alignment為Image.TEXTWRAP、Image.UNDERLYING分別指文字繞圖形顯示、圖形作為文字的背景顯示。這兩種參數可以結合以達到預期的效果,如setAlignment(Image.RIGHT|Image.TEXTWRAP)顯示的效果為圖像右對齊,文字圍繞圖像顯示。圖像的尺寸和旋轉如果圖像在文檔中不按原尺寸顯示,可以通過下面的函數進行設定:publicvoidscaleAbsolute(intnewWidth,intnewHeight)publicvoidscalePercent(intpercent)publicvoidscalePercent(intpercentX,intpercentY)函數publicvoidscaleAbsolute(intnewWidth,intnewHeight)直接設定顯示尺寸;函數publicvoidscalePercent(intpercent)設定顯示比例,如scalePercent(50)表示顯示的大小為原尺寸的50%;而函數scalePercent(intpercentX,intpercentY)則圖像高寬的顯示比例。如果圖像需要旋轉一定角度之後在文檔中顯示,可以通過函數publicvoidsetRotation(doubler)設定,參數r為弧度,如果旋轉角度為30度,則參數r=Math.PI/6。六、中文處理默認的iText字體設置不支持中文字體,需要下載遠東字體包iTextAsian.jar,否則不能往PDF文檔中輸出中文字體。通過下面的代碼就可以在文檔中使用中文了:BaseFontbfChinese=BaseFont.createFont("STSong-Light","UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);com.lowagie.text.FontFontChinese=newcom.lowagie.text.Font(bfChinese,12,com.lowagie.text.Font.NORMAL);Paragraphpragraph=newParagraph("你好",FontChinese);小結iText還有很多高級的功能,這里就不一一介紹了,具體開發時可參考發布的文檔。總的來說,iText是一套java環境下不錯的製作PDF的組件。因為iText支持jsp/javabean下的開發,這使得B/S應用中的報表問題能得到很好的解決。由於iText畢竟不是專門為製作報表設計,所有報表中的內容、格式都需要通過寫代碼實現,相對於那些專業的支持可視化設計的報表軟體來說,編程的工作量就有一定程度的增加。
B. itext 生成 PDF(一)
itext 生成 PDF(二)
官網: http://itextsupport.com/apidocs/itext5/latest/
博文: https://blog.csdn.net/u010154380/article/details/78087663
博文: https://blog.csdn.net/u013129932/article/details/43889705
iText是著名的開放源碼的站點sourceforge一個項目,是用於生成PDF文檔的一個java類庫。通過iText不僅可以生成PDF或rtf的文檔,而且可以將XML、Html文件轉化為PDF文件。
項目要使用iText,必須引入jar包。才能使用,maven依賴如下:
<dependency><groupId>com.itextpdf</groupId><artifactId>itextpdf</artifactId><version>5.5.10</version></dependency>
輸出中文,還要引入下面itext-asian.jar包:
<dependency><groupId>com.itextpdf</groupId><artifactId>itext-asian</artifactId><version>5.2.0</version></dependency>
設置pdf文件密碼,還要引入下面bcprov-jdk15on.jar包:
<dependency><groupId>org.bouncycastle</groupId><artifactId>bcprov-jdk15on</artifactId><version>1.54</version></dependency>
iText常用類
com.itextpdf.text.Document:這是iText庫中最常用的類,它代表了一個pdf實例。如果你需要從零開始生成一個PDF文件,你需要使用這個Document類。首先創建(new)該實例,然後打開(open)它,並添加(add)內容,最後關閉(close)該實例,即可生成一個pdf文件。
com.itextpdf.text.Paragraph:表示一個縮進的文本段落,在段落中,你可以設置對齊方式,縮進,段落前後間隔等
com.itextpdf.text.Chapter:表示PDF的一個章節,他通過一個Paragraph類型的標題和整形章數創建
com.itextpdf.text.Font:這個類包含了所有規范好的字體,包括family of font,大小,樣式和顏色,所有這些字體都被聲明為靜態常量
com.itextpdf.text.List:表示一個列表;
com.itextpdf.text.Anchor:表示一個錨,類似於HTML頁面的鏈接。
com.itextpdf.text.pdf.PdfWriter:當這個PdfWriter被添加到PdfDocument後,所有添加到Document的內容將會寫入到與文件或網路關聯的輸出流中。
com.itextpdf.text.pdf.PdfReader:用於讀取PDF文件;
iText使用
創建一個簡單的pdf文件,如下:
packagecom.hd.pdf;importjava.io.FileNotFoundException;importjava.io.FileOutputStream;importcom.itextpdf.text.Document;importcom.itextpdf.text.DocumentException;importcom.itextpdf.text.Paragraph;importcom.itextpdf.text.pdf.PdfWriter;publicclassTestPDFDemo1{publicstaticvoidmain(String[]args)throws FileNotFoundException,DocumentException{// 1.新建document對象Document document=newDocument();// 2.建立一個書寫器(Writer)與document對象關聯,通過書寫器(Writer)可以將文檔寫入到磁碟中。// 創建 PdfWriter 對象 第一個參數是對文檔對象的引用,第二個參數是文件的實際名稱,在該名稱中還會給出其輸出路徑。PdfWriter writer=PdfWriter.getInstance(document,newFileOutputStream("C:/Users/H__D/Desktop/test.pdf"));// 3.打開文檔document.open();// 4.添加一個內容段落document.add(newParagraph("Hello World!"));// 5.關閉文檔document.close();}}
打開文件
851491-20161209165247147-746087588.png
PDF中創建表格
publicstaticvoidmain(String[]args)throws DocumentException,FileNotFoundException{//創建文件Document document=newDocument();//建立一個書寫器PdfWriter writer=PdfWriter.getInstance(document,newFileOutputStream("C:/Users/H__D/Desktop/test4.pdf"));//打開文件document.open();//添加內容document.add(newParagraph("HD content here"));// 3列的表.PdfPTable table=newPdfPTable(3);table.setWidthPercentage(100);// 寬度100%填充table.setSpacingBefore(10f);// 前間距table.setSpacingAfter(10f);// 後間距List<PdfPRow>listRow=table.getRows();//設置列寬float[]columnWidths={1f,2f,3f};table.setWidths(columnWidths);//行1PdfPCell cells1[]=newPdfPCell[3];PdfPRow row1=newPdfPRow(cells1);//單元格cells1[0]=newPdfPCell(newParagraph("111"));//單元格內容cells1[0].setBorderColor(BaseColor.BLUE);//邊框驗證cells1[0].setPaddingLeft(20);//左填充20cells1[0].setHorizontalAlignment(Element.ALIGN_CENTER);//水平居中cells1[0].setVerticalAlignment(Element.ALIGN_MIDDLE);//垂直居中cells1[1]=newPdfPCell(newParagraph("222"));cells1[2]=newPdfPCell(newParagraph("333"));//行2PdfPCell cells2[]=newPdfPCell[3];PdfPRow row2=newPdfPRow(cells2);cells2[0]=newPdfPCell(newParagraph("444"));//把第一行添加到集合listRow.add(row1);listRow.add(row2);//把表格添加到文件中document.add(table);//關閉文檔document.close();//關閉書寫器writer.close();}
打開圖片
851491-20161209165247147-746087588.png
給PDF文件設置文件屬性,例如:
publicstaticvoidmain(String[]args)throws FileNotFoundException,DocumentException{//創建文件Document document=newDocument();//建立一個書寫器PdfWriter writer=PdfWriter.getInstance(document,newFileOutputStream("C:/Users/H__D/Desktop/test2.pdf"));//打開文件document.open();//添加內容document.add(newParagraph("Some content here"));//設置屬性//標題document.addTitle("this is a title");//作者document.addAuthor("H__D");//主題document.addSubject("this is subject");//關鍵字document.addKeywords("Keywords");//創建時間document.addCreationDate();//應用程序document.addCreator("hd.com");//關閉文檔document.close();//關閉書寫器writer.close();}
打開文件
851491-20161209165247147-746087588.png
PDF中添加圖片
publicstaticvoidmain(String[]args)throws DocumentException,IOException{//創建文件Document document=newDocument();//建立一個書寫器PdfWriter writer=PdfWriter.getInstance(document,newFileOutputStream("C:/Users/H__D/Desktop/test3.pdf"));//打開文件document.open();//添加內容document.add(newParagraph("HD content here"));//圖片1Image image1=Image.getInstance("C:/Users/H__D/Desktop/IMG_0109.JPG");//設置圖片位置的x軸和y周image1.setAbsolutePosition(100f,550f);//設置圖片的寬度和高度image1.scaleAbsolute(200,200);//將圖片1添加到pdf文件中document.add(image1);//圖片2Image image2=Image.getInstance(newURL("http://static.cnblogs.com/images/adminlogo.gif"));//將圖片2添加到pdf文件中document.add(image2);//關閉文檔document.close();//關閉書寫器writer.close();}
打開圖片
851491-20161209165247147-746087588.png
PDF中創建列表
publicstaticvoidmain(String[]args)throws DocumentException,FileNotFoundException{//創建文件Document document=newDocument();//建立一個書寫器PdfWriter writer=PdfWriter.getInstance(document,newFileOutputStream("C:/Users/H__D/Desktop/test5.pdf"));//打開文件document.open();//添加內容document.add(newParagraph("HD content here"));//添加有序列表List orderedList=newList(List.ORDERED);orderedList.add(newListItem("Item one"));orderedList.add(newListItem("Item two"));orderedList.add(newListItem("Item three"));document.add(orderedList);//關閉文檔document.close();//關閉書寫器writer.close();}
打開文件
851491-20161209180029726-1168732515.png
PDF中設置樣式/格式化輸出,輸出中文內容,必須引入itext-asian.jar
publicstaticvoidmain(String[]args)throws DocumentException,IOException{//創建文件Document document=newDocument();//建立一個書寫器PdfWriter writer=PdfWriter.getInstance(document,newFileOutputStream("C:/Users/H__D/Desktop/test6.pdf"));//打開文件document.open();//中文字體,解決中文不能顯示問題BaseFont bfChinese=BaseFont.createFont("STSong-Light","UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);//藍色字體Font blueFont=newFont(bfChinese);blueFont.setColor(BaseColor.BLUE);//段落文本Paragraph paragraphBlue=newParagraph("paragraphOne blue front",blueFont);document.add(paragraphBlue);//綠色字體Font greenFont=newFont(bfChinese);greenFont.setColor(BaseColor.GREEN);//創建章節Paragraph chapterTitle=newParagraph("段落標題xxxx",greenFont);Chapter chapter1=newChapter(chapterTitle,1);chapter1.setNumberDepth(0);Paragraph sectionTitle=newParagraph("部分標題",greenFont);Section section1=chapter1.addSection(sectionTitle);Paragraph sectionContent=newParagraph("部分內容",blueFont);section1.add(sectionContent);//將章節添加到文章中document.add(chapter1);//關閉文檔document.close();//關閉書寫器writer.close();}
打開圖片
![
851491-20161209180029726-1168732515.png
]
851491-20161209165247147-746087588.png
給PDF文件設置密碼,需要引入bcprov-jdk15on.jar包:
publicstaticvoidmain(String[]args)throws DocumentException,IOException{// 創建文件Document document=newDocument();// 建立一個書寫器PdfWriter writer=PdfWriter.getInstance(document,newFileOutputStream("C:/Users/H__D/Desktop/test8.pdf"));//用戶密碼String userPassword="123456";//擁有者密碼String ownerPassword="hd";writer.setEncryption(userPassword.getBytes(),ownerPassword.getBytes(),PdfWriter.ALLOW_PRINTING,PdfWriter.ENCRYPTION_AES_128);// 打開文件document.open();//添加內容document.add(newParagraph("password !!!!"));// 關閉文檔document.close();// 關閉書寫器writer.close();}
打開圖片
851491-20161209165247147-746087588.png
給PDF文件設置許可權
publicstaticvoidmain(String[]args)throws DocumentException,IOException{// 創建文件Document document=newDocument();// 建立一個書寫器PdfWriter writer=PdfWriter.getInstance(document,newFileOutputStream("C:/Users/H__D/Desktop/test9.pdf"));// 只讀許可權writer.setEncryption("".getBytes(),"".getBytes(),PdfWriter.ALLOW_PRINTING,PdfWriter.ENCRYPTION_AES_128);// 打開文件document.open();// 添加內容document.add(newParagraph("password !!!!"));// 關閉文檔document.close();// 關閉書寫器writer.close();}
讀取/修改已有的PDF文件
publicstaticvoidmain(String[]args)throwsDocumentException,IOException{//讀取pdf文件PdfReaderpdfReader=newPdfReader("C:/Users/H__D/Desktop/test1.pdf");//修改器PdfStamperpdfStamper=newPdfStamper(pdfReader,newFileOutputStream("C:/Users/H__D/Desktop/test10.pdf"));Imageimage=Image.getInstance("C:/Users/H__D/Desktop/IMG_0109.JPG");image.scaleAbsolute(50,50);image.setAbsolutePosition(0,700);for(inti=1;i<=pdfReader.getNumberOfPages();i++){PdfContentBytecontent=pdfStamper.getUnderContent(i);content.addImage(image);}pdfStamper.close();}
itext 生成 PDF(二)
鏈接:https://www.jianshu.com/p/20d4905383b4
C. Java能直接修改pdf文件嗎
貌似沒見過這個插件,還有pdf有一部分是根本不能修改的,哪怕用專業工具都不行,如果pdf裡面的文字可以讀取出來,倒是可以導入txt然後就很好修改了,pdf圖文混排,覺得java修改難度較大