譯文鏈接:http://howtodoinjava.com/apache-commons/create-pdf-files-in-java-itext-tutorial/java
對於excel文件的讀寫操做,相信你們都比較熟悉,使用apache的POI庫便可。本篇文章,我將基於iText庫編寫各式各樣的代碼示例去建立PDF文件。這些例子會按它們各自的功能分類,爲了使你們能更加形象的看到代碼所生成的PDF文件內容,每個例子我都會附加上一張PDF文件截圖。我已經儘量的把我能找到的有用的例子放在這裏,若是你以爲我錯過了一些用例,隨時在評論裏留下你的建議,我會把這些例子添加進去。apache
好的一面是,iText是開源的API,可是須要注意,雖然iText是開源,若是你出於商業目的使用它,仍然須要購買商業許可證。你能夠從http://itextpdf.com上免費獲取iText的Java類庫,iText庫很是強大,支持HTML、RTF、XML以及PDF文件的生產,你能夠在文檔中使用各類各樣的字體,而且,還可使用一樣的代碼生成上述不一樣類型的文件,這真的是一個很棒的特性,不是嗎?網絡
iText庫包含一系列接口,能夠生成不一樣字體的PDF文件,在PDF中建立表格,添加水印等等功能。固然,iText還有許許多多其它的功能,這將留給讀者去探索。app
若是你的項目是maven工程的話,在pom.xml文件中添加以下依賴,便可以給本身的應用程序添加iText庫支持。eclipse
<dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>5.0.6</version> </dependency>
固然,你也能夠本身去下載最新的jar文件,而後添加到工程裏,下載地址。maven
讓咱們先列出幾個接下來例子中要用到的重要的類,熟悉熟悉。ide
com.itextpdf.text.Document:這是iText庫中最經常使用的類,它表明了一個pdf實例。若是你須要從零開始生成一個PDF文件,你須要使用這個Document類。首先建立(new)該實例,而後打開(open)它,並添加(add)內容,最後關閉(close)該實例,便可生成一個pdf文件。學習
com.itextpdf.text.Paragraph:表示一個縮進的文本段落,在段落中,你能夠設置對齊方式,縮進,段落先後間隔等。字體
com.itextpdf.text.Chapter:表示PDF的一個章節,他經過一個Paragraph類型的標題和整形章數建立。spa
com.itextpdf.text.Font:這個類包含了全部規範好的字體,包括family of font,大小,樣式和顏色,全部這些字體都被聲明爲靜態常量。
com.itextpdf.text.List:表示一個列表;
com.itextpdf.text.pdf.PDFPTable:表示一個表格;
com.itextpdf.text.Anchor:表示一個錨,相似於HTML頁面的連接。
com.itextpdf.text.pdf.PdfWriter:當這個PdfWriter被添加到PdfDocument後,全部添加到Document的內容將會寫入到與文件或網絡關聯的輸出流中。
com.itextpdf.text.pdf.PdfReader:用於讀取PDF文件;
讓咱們先從簡單的「Hello World」程序開始,在這個程序中,我將會建立一個PDF文件,裏面的內容爲一條簡單的語句。
package cn.edu.hdu.chenpi.cpdemo.itext; import java.io.FileNotFoundException; import java.io.FileOutputStream; import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.PdfWriter; public class JavaPdfHelloWorld { public static void main(String[] args) { Document document = new Document(); try { PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("HelloWorld.pdf")); document.open(); document.add(new Paragraph("A Hello World PDF document.")); document.close(); writer.close(); } catch (DocumentException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } } }
這個例子將展現如何給PDF文件設置各類屬性,如做者名字,建立日期,建立者,或者標題。
Document document = new Document(); try { PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("SetAttributeExample.pdf")); document.open(); document.add(new Paragraph("Some content here")); //Set attributes here document.addAuthor("Lokesh Gupta"); document.addCreationDate(); document.addCreator("HowToDoInJava.com"); document.addTitle("Set Attribute Example"); document.addSubject("An example to show how attributes can be added to pdf files."); document.close(); writer.close(); } catch (Exception e) { e.printStackTrace(); }
下面例子展現如何往PDF文件中添加圖片。例子中圖片來源包含了兩種方式:本地圖片或URL。
而且,我添加了一些代碼,用於設置圖片在文檔中的位置。
Document document = new Document(); try { PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("AddImageExample.pdf")); document.open(); document.add(new Paragraph("Image Example")); //Add Image Image image1 = Image.getInstance("C:\\temp.jpg"); //Fixed Positioning image1.setAbsolutePosition(100f, 550f); //Scale to new height and new width of image image1.scaleAbsolute(200, 200); //Add to document document.add(image1); String imageUrl = "http://www.eclipse.org/xtend/images/java8_logo.png"; Image image2 = Image.getInstance(new URL(imageUrl)); document.add(image2); document.close(); writer.close(); } catch (Exception e) { e.printStackTrace(); }
如下代碼展現瞭如何在PDF文件中建立表格
Document document = new Document(); try { PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("AddTableExample.pdf")); document.open(); PdfPTable table = new PdfPTable(3); // 3 columns. table.setWidthPercentage(100); // Width 100% table.setSpacingBefore(10f); // Space before table table.setSpacingAfter(10f); // Space after table // Set Column widths float[] columnWidths = { 1f, 1f, 1f }; table.setWidths(columnWidths); PdfPCell cell1 = new PdfPCell(new Paragraph("Cell 1")); cell1.setBorderColor(BaseColor.BLUE); cell1.setPaddingLeft(10); cell1.setHorizontalAlignment(Element.ALIGN_CENTER); cell1.setVerticalAlignment(Element.ALIGN_MIDDLE); PdfPCell cell2 = new PdfPCell(new Paragraph("Cell 2")); cell2.setBorderColor(BaseColor.GREEN); cell2.setPaddingLeft(10); cell2.setHorizontalAlignment(Element.ALIGN_CENTER); cell2.setVerticalAlignment(Element.ALIGN_MIDDLE); PdfPCell cell3 = new PdfPCell(new Paragraph("Cell 3")); cell3.setBorderColor(BaseColor.RED); cell3.setPaddingLeft(10); cell3.setHorizontalAlignment(Element.ALIGN_CENTER); cell3.setVerticalAlignment(Element.ALIGN_MIDDLE); // To avoid having the cell border and the content overlap, if you // are having thick cell borders // cell1.setUserBorderPadding(true); // cell2.setUserBorderPadding(true); // cell3.setUserBorderPadding(true); table.addCell(cell1); table.addCell(cell2); table.addCell(cell3); document.add(table); document.close(); writer.close(); } catch (Exception e) { e.printStackTrace(); }
這個例子將會幫助你理解iText庫是如何在PDF文件裏建立列表的。
Document document = new Document(); try { PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("ListExample.pdf")); document.open(); document.add(new Paragraph("List Example")); //Add ordered list List orderedList = new List(List.ORDERED); orderedList.add(new ListItem("Item 1")); orderedList.add(new ListItem("Item 2")); orderedList.add(new ListItem("Item 3")); document.add(orderedList); //Add un-ordered list List unorderedList = new List(List.UNORDERED); unorderedList.add(new ListItem("Item 1")); unorderedList.add(new ListItem("Item 2")); unorderedList.add(new ListItem("Item 3")); document.add(unorderedList); //Add roman list RomanList romanList = new RomanList(); romanList.add(new ListItem("Item 1")); romanList.add(new ListItem("Item 2")); romanList.add(new ListItem("Item 3")); document.add(romanList); //Add Greek list GreekList greekList = new GreekList(); greekList.add(new ListItem("Item 1")); greekList.add(new ListItem("Item 2")); greekList.add(new ListItem("Item 3")); document.add(greekList); //ZapfDingbatsList List Example ZapfDingbatsList zapfDingbatsList = new ZapfDingbatsList(43, 30); zapfDingbatsList.add(new ListItem("Item 1")); zapfDingbatsList.add(new ListItem("Item 2")); zapfDingbatsList.add(new ListItem("Item 3")); document.add(zapfDingbatsList); //List and Sublist Examples List nestedList = new List(List.UNORDERED); nestedList.add(new ListItem("Item 1")); List sublist = new List(true, false, 30); sublist.setListSymbol(new Chunk("", FontFactory.getFont(FontFactory.HELVETICA, 6))); sublist.add("A"); sublist.add("B"); nestedList.add(sublist); nestedList.add(new ListItem("Item 2")); sublist = new List(true, false, 30); sublist.setListSymbol(new Chunk("", FontFactory.getFont(FontFactory.HELVETICA, 6))); sublist.add("C"); sublist.add("D"); nestedList.add(sublist); document.add(nestedList); document.close(); writer.close(); } catch (Exception e) { e.printStackTrace(); }
讓咱們來看一些給PDF文件內容設置樣式的例子,例子中包含了字體、章、節的使用。
Font blueFont = FontFactory.getFont(FontFactory.HELVETICA, 8, Font.NORMAL, new CMYKColor(255, 0, 0, 0)); Font redFont = FontFactory.getFont(FontFactory.COURIER, 12, Font.BOLD, new CMYKColor(0, 255, 0, 0)); Font yellowFont = FontFactory.getFont(FontFactory.COURIER, 14, Font.BOLD, new CMYKColor(0, 0, 255, 0)); Document document = new Document(); try { PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("StylingExample.pdf")); document.open(); //document.add(new Paragraph("Styling Example")); //Paragraph with color and font styles Paragraph paragraphOne = new Paragraph("Some colored paragraph text", redFont); document.add(paragraphOne); //Create chapter and sections Paragraph chapterTitle = new Paragraph("Chapter Title", yellowFont); Chapter chapter1 = new Chapter(chapterTitle, 1); chapter1.setNumberDepth(0); Paragraph sectionTitle = new Paragraph("Section Title", redFont); Section section1 = chapter1.addSection(sectionTitle); Paragraph sectionContent = new Paragraph("Section Text content", blueFont); section1.add(sectionContent); document.add(chapter1); document.close(); writer.close(); } catch (Exception e) { e.printStackTrace(); }
接下來,讓咱們看下如何給pdf文件生產保護密碼,以下,使用writer.setEncryption()方法便可給pdf文件設置密碼。
private static String USER_PASSWORD = "password"; private static String OWNER_PASSWORD = "lokesh"; public static void main(String[] args) { try { OutputStream file = new FileOutputStream(new File("PasswordProtected.pdf")); Document document = new Document(); PdfWriter writer = PdfWriter.getInstance(document, file); writer.setEncryption(USER_PASSWORD.getBytes(), OWNER_PASSWORD.getBytes(), PdfWriter.ALLOW_PRINTING, PdfWriter.ENCRYPTION_AES_128); document.open(); document.add(new Paragraph("Password Protected pdf example !!")); document.close(); file.close(); } catch (Exception e) { e.printStackTrace(); } }
在這個例子中,我將設置一些權限用於限制其它用戶訪問PDF文件,以下是一些權限設置值:
PdfWriter.ALLOW_PRINTING PdfWriter.ALLOW_ASSEMBLY PdfWriter.ALLOW_COPY PdfWriter.ALLOW_DEGRADED_PRINTING PdfWriter.ALLOW_FILL_IN PdfWriter.ALLOW_MODIFY_ANNOTATIONS PdfWriter.ALLOW_MODIFY_CONTENTS PdfWriter.ALLOW_SCREENREADERS
你能夠經過對不一樣的值執行或操做來實現多權限設置,舉個例子:PdfWriter.ALLOW_PRINTING | PdfWriter.ALLOW_COPY。
public static void main(String[] args) { try { OutputStream file = new FileOutputStream(new File( "LimitedAccess.pdf")); Document document = new Document(); PdfWriter writer = PdfWriter.getInstance(document, file); writer.setEncryption("".getBytes(), "".getBytes(), PdfWriter.ALLOW_PRINTING , //Only printing allowed; Try to copy text !! PdfWriter.ENCRYPTION_AES_128); document.open(); document.add(new Paragraph("Limited Access File !!")); document.close(); file.close(); } catch (Exception e) { e.printStackTrace(); } }
本例子將展現如何使用iText庫實現PDF文件的讀取和修改。在這個例子中,我將讀取一個PDF文件,並往每一頁添加一些內容。
public static void main(String[] args) { try { //Read file using PdfReader PdfReader pdfReader = new PdfReader("HelloWorld.pdf"); //Modify file using PdfReader PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileOutputStream("HelloWorld-modified.pdf")); Image image = Image.getInstance("temp.jpg"); image.scaleAbsolute(100, 50); image.setAbsolutePosition(100f, 700f); for(int i=1; i<= pdfReader.getNumberOfPages(); i++) { PdfContentByte content = pdfStamper.getUnderContent(i); content.addImage(image); } pdfStamper.close(); } catch (IOException e) { e.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); } }
這是本篇文章的最後一個例子,我將會往HttpServletResponse的輸出流中寫入一些PDF內容。在CS環境中,當你須要將PDF文件轉成流的形式的時候,這很是有用。
Document document = new Document(); try{ response.setContentType("application/pdf"); PdfWriter.getInstance(document, response.getOutputStream()); document.open(); document.add(new Paragraph("howtodoinjava.com")); document.add(new Paragraph(new Date().toString())); //Add more content here }catch(Exception e){ e.printStackTrace(); } document.close(); }
以上就是關於iText 庫的全部例子了,若是有什麼地方不清楚,或你想增長更多的例子,歡迎留下你的評論。
學習愉快~
譯文鏈接:http://howtodoinjava.com/apache-commons/create-pdf-files-in-java-itext-tutorial/