Java操作PDF之iText超入門

iText是著名的開放項目,是用於生成PDF文檔的一個java類庫。通過iText不僅可以生成PDF或rtf的文檔,而且可以將XML、Html文件轉化爲PDF文件。 

http://itextpdf.com/ 

版本:itextpdf-5.2.1.jar 

1、生成一個PDF 
Java代碼  收藏代碼
  1. //Step 1—Create a Document.  
  2. Document document = new Document();  
  3. //Step 2—Get a PdfWriter instance.  
  4. PdfWriter.getInstance(document, new FileOutputStream(FILE_DIR + "createSamplePDF.pdf"));  
  5. //Step 3—Open the Document.  
  6. document.open();  
  7. //Step 4—Add content.  
  8. document.add(new Paragraph("Hello World"));  
  9. //Step 5—Close the Document.  
  10. document.close();  


2、頁面大小,頁面背景色,頁邊空白,Title,Author,Subject,Keywords 
Java代碼  收藏代碼
  1. //頁面大小  
  2. Rectangle rect = new Rectangle(PageSize.B5.rotate());  
  3. //頁面背景色  
  4. rect.setBackgroundColor(BaseColor.ORANGE);  
  5.   
  6. Document doc = new Document(rect);  
  7.   
  8. PdfWriter writer = PdfWriter.getInstance(doc, out);  
  9.   
  10. //PDF版本(默認1.4)  
  11. writer.setPdfVersion(PdfWriter.PDF_VERSION_1_2);  
  12.   
  13. //文檔屬性  
  14. doc.addTitle("Title@sample");  
  15. doc.addAuthor("Author@rensanning");  
  16. doc.addSubject("Subject@iText sample");  
  17. doc.addKeywords("Keywords@iText");  
  18. doc.addCreator("Creator@iText");  
  19.   
  20. //頁邊空白  
  21. doc.setMargins(10203040);  
  22.   
  23. doc.open();  
  24. doc.add(new Paragraph("Hello World"));  

 

3、設置密碼 
Java代碼  收藏代碼
  1. PdfWriter writer = PdfWriter.getInstance(doc, out);  
  2.   
  3. // 設置密碼爲:"World"  
  4. writer.setEncryption("Hello".getBytes(), "World".getBytes(),  
  5.         PdfWriter.ALLOW_SCREENREADERS,  
  6.         PdfWriter.STANDARD_ENCRYPTION_128);  
  7.   
  8. doc.open();  
  9. doc.add(new Paragraph("Hello World"));  

 

4、添加Page 
Java代碼  收藏代碼
  1. document.open();  
  2. document.add(new Paragraph("First page"));  
  3. document.add(new Paragraph(Document.getVersion()));  
  4.   
  5. document.newPage();  
  6. writer.setPageEmpty(false);  
  7.   
  8. document.newPage();  
  9. document.add(new Paragraph("New page"));  


5、添加水印(背景圖) 
Java代碼  收藏代碼
  1. //圖片水印  
  2. PdfReader reader = new PdfReader(FILE_DIR + "setWatermark.pdf");  
  3. PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(FILE_DIR  
  4.         + "setWatermark2.pdf"));  
  5.   
  6. Image img = Image.getInstance("resource/watermark.jpg");  
  7. img.setAbsolutePosition(200400);  
  8. PdfContentByte under = stamp.getUnderContent(1);  
  9. under.addImage(img);  
  10.   
  11. //文字水印  
  12. PdfContentByte over = stamp.getOverContent(2);  
  13. over.beginText();  
  14. BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI,  
  15.         BaseFont.EMBEDDED);  
  16. over.setFontAndSize(bf, 18);  
  17. over.setTextMatrix(3030);  
  18. over.showTextAligned(Element.ALIGN_LEFT, "DUPLICATE"23043045);  
  19. over.endText();  
  20.   
  21. //背景圖  
  22. Image img2 = Image.getInstance("resource/test.jpg");  
  23. img2.setAbsolutePosition(00);  
  24. PdfContentByte under2 = stamp.getUnderContent(3);  
  25. under2.addImage(img2);  
  26.   
  27. stamp.close();  
  28. reader.close();  


6、插入Chunk, Phrase, Paragraph, List 
Java代碼  收藏代碼
  1. //Chunk對象: a String, a Font, and some attributes  
  2. document.add(new Chunk("China"));  
  3. document.add(new Chunk(" "));  
  4. Font font = new Font(Font.FontFamily.HELVETICA, 6, Font.BOLD, BaseColor.WHITE);  
  5. Chunk id = new Chunk("chinese", font);  
  6. id.setBackground(BaseColor.BLACK, 1f, 0.5f, 1f, 1.5f);  
  7. id.setTextRise(6);  
  8. document.add(id);  
  9. document.add(Chunk.NEWLINE);  
  10.   
  11. document.add(new Chunk("Japan"));  
  12. document.add(new Chunk(" "));  
  13. Font font2 = new Font(Font.FontFamily.HELVETICA, 6, Font.BOLD, BaseColor.WHITE);  
  14. Chunk id2 = new Chunk("japanese", font2);  
  15. id2.setBackground(BaseColor.BLACK, 1f, 0.5f, 1f, 1.5f);  
  16. id2.setTextRise(6);  
  17. id2.setUnderline(0.2f, -2f);  
  18. document.add(id2);  
  19. document.add(Chunk.NEWLINE);  
  20.   
  21. //Phrase對象: a List of Chunks with leading  
  22. document.newPage();  
  23. document.add(new Phrase("Phrase page"));  
  24.   
  25. Phrase director = new Phrase();  
  26. Chunk name = new Chunk("China");  
  27. name.setUnderline(0.2f, -2f);  
  28. director.add(name);  
  29. director.add(new Chunk(","));  
  30. director.add(new Chunk(" "));  
  31. director.add(new Chunk("chinese"));  
  32. director.setLeading(24);  
  33. document.add(director);  
  34.   
  35. Phrase director2 = new Phrase();  
  36. Chunk name2 = new Chunk("Japan");  
  37. name2.setUnderline(0.2f, -2f);  
  38. director2.add(name2);  
  39. director2.add(new Chunk(","));  
  40. director2.add(new Chunk(" "));  
  41. director2.add(new Chunk("japanese"));  
  42. director2.setLeading(24);  
  43. document.add(director2);  
  44.           
  45. //Paragraph對象: a Phrase with extra properties and a newline  
  46. document.newPage();  
  47. document.add(new Paragraph("Paragraph page"));  
  48.   
  49. Paragraph info = new Paragraph();  
  50. info.add(new Chunk("China "));  
  51. info.add(new Chunk("chinese"));  
  52. info.add(Chunk.NEWLINE);  
  53. info.add(new Phrase("Japan "));  
  54. info.add(new Phrase("japanese"));  
  55. document.add(info);  
  56.   
  57. //List對象: a sequence of Paragraphs called ListItem  
  58. document.newPage();  
  59. List list = new List(List.ORDERED);  
  60. for (int i = 0; i < 10; i++) {  
  61.     ListItem item = new ListItem(String.format("%s: %d movies",  
  62.             "country" + (i + 1), (i + 1) * 100), new Font(  
  63.             Font.FontFamily.HELVETICA, 6, Font.BOLD, BaseColor.WHITE));  
  64.     List movielist = new List(List.ORDERED, List.ALPHABETICAL);  
  65.     movielist.setLowercase(List.LOWERCASE);  
  66.     for (int j = 0; j < 5; j++) {  
  67.         ListItem movieitem = new ListItem("Title" + (j + 1));  
  68.         List directorlist = new List(List.UNORDERED);  
  69.         for (int k = 0; k < 3; k++) {  
  70.             directorlist.add(String.format("%s, %s""Name1" + (k + 1),  
  71.                     "Name2" + (k + 1)));  
  72.         }  
  73.         movieitem.add(directorlist);  
  74.         movielist.add(movieitem);  
  75.     }  
  76.     item.add(movielist);  
  77.     list.add(item);  
  78. }  
  79. document.add(list);  


7、插入Anchor, Image, Chapter, Section 
Java代碼  收藏代碼
  1. //Anchor對象: internal and external links  
  2. Paragraph country = new Paragraph();  
  3. Anchor dest = new Anchor("china"new Font(Font.FontFamily.HELVETICA, 14, Font.BOLD, BaseColor.BLUE));  
  4. dest.setName("CN");  
  5. dest.setReference("http://www.china.com");//external  
  6. country.add(dest);  
  7. country.add(String.format(": %d sites"10000));  
  8. document.add(country);  
  9.   
  10. document.newPage();  
  11. Anchor toUS = new Anchor("Go to first page."new Font(Font.FontFamily.HELVETICA, 14, Font.BOLD, BaseColor.BLUE));  
  12. toUS.setReference("#CN");//internal  
  13. document.add(toUS);  
  14.   
  15. //Image對象  
  16. document.newPage();  
  17. Image img = Image.getInstance("resource/test.jpg");  
  18. img.setAlignment(Image.LEFT | Image.TEXTWRAP);  
  19. img.setBorder(Image.BOX);  
  20. img.setBorderWidth(10);  
  21. img.setBorderColor(BaseColor.WHITE);  
  22. img.scaleToFit(100072);//大小  
  23. img.setRotationDegrees(-30);//旋轉  
  24. document.add(img);  
  25.   
  26. //Chapter, Section對象(目錄)  
  27. document.newPage();  
  28. Paragraph title = new Paragraph("Title");  
  29. Chapter chapter = new Chapter(title, 1);  
  30.   
  31. title = new Paragraph("Section A");  
  32. Section section = chapter.addSection(title);  
  33. section.setBookmarkTitle("bmk");  
  34. section.setIndentation(30);  
  35. section.setBookmarkOpen(false);  
  36. section.setNumberStyle(  
  37. Section.NUMBERSTYLE_DOTTED_WITHOUT_FINAL_DOT);  
  38.   
  39. Section subsection = section.addSection(new Paragraph("Sub Section A"));  
  40. subsection.setIndentationLeft(20);  
  41. subsection.setNumberDepth(1);  
  42.   
  43. document.add(chapter);  


8、畫圖 
Java代碼  收藏代碼
  1. //左右箭頭  
  2. document.add(new VerticalPositionMark() {  
  3.   
  4.     public void draw(PdfContentByte canvas, float llx, float lly,  
  5.             float urx, float ury, float y) {  
  6.         canvas.beginText();  
  7.         BaseFont bf = null;  
  8.         try {  
  9.             bf = BaseFont.createFont(BaseFont.ZAPFDINGBATS, "", BaseFont.EMBEDDED);  
  10.         } catch (Exception e) {  
  11.             e.printStackTrace();  
  12.         }  
  13.         canvas.setFontAndSize(bf, 12);  
  14.           
  15.         // LEFT  
  16.         canvas.showTextAligned(Element.ALIGN_CENTER, String.valueOf((char220), llx - 10, y, 0);  
  17.         // RIGHT  
  18.         canvas.showTextAligned(Element.ALIGN_CENTER, String.valueOf((char220), urx + 10, y + 8180);  
  19.           
  20.         canvas.endText();  
  21.     }  
  22. });  
  23.   
  24. //直線  
  25. Paragraph p1 = new Paragraph("LEFT");  
  26. p1.add(new Chunk(new LineSeparator()));  
  27. p1.add("R");  
  28. document.add(p1);  
  29. //點線  
  30. Paragraph p2 = new Paragraph("LEFT");  
  31. p2.add(new Chunk(new DottedLineSeparator()));  
  32. p2.add("R");  
  33. document.add(p2);  
  34. //下滑線  
  35. LineSeparator UNDERLINE = new LineSeparator(1100null, Element.ALIGN_CENTER, -2);  
  36. Paragraph p3 = new Paragraph("NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN");  
  37. p3.add(UNDERLINE);  
  38. document.add(p3);  

 

9、設置段落 
Java代碼  收藏代碼
  1. Paragraph p = new Paragraph("In the previous example, you added a header and footer with the showTextAligned() method. This example demonstrates that it’s sometimes more interesting to use PdfPTable and writeSelectedRows(). You can define a bottom border for each cell so that the header is underlined. This is the most elegant way to add headers and footers, because the table mechanism allows you to position and align lines, images, and text.");  
  2.   
  3. //默認  
  4. p.setAlignment(Element.ALIGN_JUSTIFIED);  
  5. document.add(p);  
  6.   
  7. document.newPage();  
  8. p.setAlignment(Element.ALIGN_JUSTIFIED);  
  9. p.setIndentationLeft(1 * 15f);  
  10. p.setIndentationRight((5 - 1) * 15f);  
  11. document.add(p);  
  12.   
  13. //居右  
  14. document.newPage();  
  15. p.setAlignment(Element.ALIGN_RIGHT);  
  16. p.setSpacingAfter(15f);  
  17. document.add(p);  
  18.   
  19. //居左  
  20. document.newPage();  
  21. p.setAlignment(Element.ALIGN_LEFT);  
  22. p.setSpacingBefore(15f);  
  23. document.add(p);  
  24.   
  25. //居中  
  26. document.newPage();  
  27. p.setAlignment(Element.ALIGN_CENTER);  
  28. p.setSpacingAfter(15f);  
  29. p.setSpacingBefore(15f);  
  30. document.add(p);  


10、刪除Page 
Java代碼  收藏代碼
  1. FileOutputStream out = new FileOutputStream(FILE_DIR + "deletePage.pdf");  
  2.   
  3. Document document = new Document();  
  4.   
  5. PdfWriter writer = PdfWriter.getInstance(document, out);  
  6.   
  7. document.open();  
  8. document.add(new Paragraph("First page"));  
  9. document.add(new Paragraph(Document.getVersion()));  
  10.   
  11. document.newPage();  
  12. writer.setPageEmpty(false);  
  13.   
  14. document.newPage();  
  15. document.add(new Paragraph("New page"));  
  16.   
  17. document.close();  
  18.   
  19. PdfReader reader = new PdfReader(FILE_DIR + "deletePage.pdf");  
  20. reader.selectPages("1,3");  
  21. PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(FILE_DIR  
  22.         + "deletePage2.pdf"));  
  23. stamp.close();  
  24. reader.close();  


11、插入Page 
Java代碼  收藏代碼
  1. FileOutputStream out = new FileOutputStream(FILE_DIR + "insertPage.pdf");  
  2.   
  3. Document document = new Document();  
  4.   
  5. PdfWriter.getInstance(document, out);  
  6.   
  7. document.open();  
  8. document.add(new Paragraph("1 page"));  
  9.   
  10. document.newPage();  
  11. document.add(new Paragraph("2 page"));  
  12.   
  13. document.newPage();  
  14. document.add(new Paragraph("3 page"));  
  15.   
  16. document.close();  
  17.   
  18. PdfReader reader = new PdfReader(FILE_DIR + "insertPage.pdf");  
  19. PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(FILE_DIR  
  20.         + "insertPage2.pdf"));  
  21.   
  22. stamp.insertPage(2, reader.getPageSize(1));  
  23.   
  24. ColumnText ct = new ColumnText(null);  
  25. ct.addElement(new Paragraph(24new Chunk("INSERT PAGE")));  
  26. ct.setCanvas(stamp.getOverContent(2));  
  27. ct.setSimpleColumn(3636559770);  
  28.   
  29. stamp.close();  
  30. reader.close();  


12、排序page 
Java代碼  收藏代碼
  1. PdfWriter writer = PdfWriter.getInstance(doc, out);  
  2. writer.setLinearPageMode();  
  3.   
  4. doc.open();  
  5. doc.add(new Paragraph("1 page"));  
  6. doc.newPage();  
  7. doc.add(new Paragraph("2 page"));  
  8. doc.newPage();  
  9. doc.add(new Paragraph("3 page"));  
  10. doc.newPage();  
  11. doc.add(new Paragraph("4 page"));  
  12. doc.newPage();  
  13. doc.add(new Paragraph("5 page"));  
  14.   
  15. int[] order = {4,3,2,1};  
  16. writer.reorderPages(order);  


13、目錄 
Java代碼  收藏代碼
  1. // Code 1  
  2. document.add(new Chunk("Chapter 1").setLocalDestination("1"));  
  3.   
  4. document.newPage();  
  5. document.add(new Chunk("Chapter 2").setLocalDestination("2"));  
  6. document.add(new Paragraph(new Chunk("Sub 2.1").setLocalDestination("2.1")));  
  7. document.add(new Paragraph(new Chunk("Sub 2.2").setLocalDestination("2.2")));  
  8.   
  9. document.newPage();  
  10. document.add(new Chunk("Chapter 3").setLocalDestination("3"));  
  11.   
  12. // Code 2  
  13. PdfContentByte cb = writer.getDirectContent();  
  14. PdfOutline root = cb.getRootOutline();  
  15.   
  16. // Code 3  
  17. @SuppressWarnings("unused")  
  18. PdfOutline oline1 = new PdfOutline(root, PdfAction.gotoLocalPage("1"false), "Chapter 1");  
  19.   
  20. PdfOutline oline2 = new PdfOutline(root, PdfAction.gotoLocalPage("2"false), "Chapter 2");  
  21. oline2.setOpen(false);  
  22.   
  23. @SuppressWarnings("unused")  
  24. PdfOutline oline2_1 = new PdfOutline(oline2, PdfAction.gotoLocalPage("2.1"false), "Sub 2.1");  
  25. @SuppressWarnings("unused")  
  26. PdfOutline oline2_2 = new PdfOutline(oline2, PdfAction.gotoLocalPage("2.2"false), "Sub 2.2");  
  27.   
  28. @SuppressWarnings("unused")  
  29. PdfOutline oline3 = new PdfOutline(root, PdfAction.gotoLocalPage("3"false), "Chapter 3");  

 

14、Header, Footer 
Java代碼  收藏代碼
  1. PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(FILE_DIR + "setHeaderFooter.pdf"));  
  2.   
  3. writer.setPageEvent(new PdfPageEventHelper() {  
  4.   
  5.     public void onEndPage(PdfWriter writer, Document document) {  
  6.           
  7.         PdfContentByte cb = writer.getDirectContent();  
  8.         cb.saveState();  
  9.   
  10.         cb.beginText();  
  11.         BaseFont bf = null;  
  12.         try {  
  13.             bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED);  
  14.         } catch (Exception e) {  
  15.             e.printStackTrace();  
  16.         }  
  17.         cb.setFontAndSize(bf, 10);  
  18.           
  19.         //Header  
  20.         float x = document.top(-20);  
  21.           
  22.         //左  
  23.         cb.showTextAligned(PdfContentByte.ALIGN_LEFT,  
  24.                            "H-Left",  
  25.                            document.left(), x, 0);  
  26.         //中  
  27.         cb.showTextAligned(PdfContentByte.ALIGN_CENTER,  
  28.                             writer.getPageNumber()+ " page",  
  29.                            (document.right() + document.left())/2,  
  30.                            x, 0);  
  31.         //右  
  32.         cb.showTextAligned(PdfContentByte.ALIGN_RIGHT,  
  33.                            "H-Right",  
  34.                            document.right(), x, 0);  
  35.   
  36.         //Footer  
  37.         float y = document.bottom(-20);  
  38.   
  39.         //左  
  40.         cb.showTextAligned(PdfContentByte.ALIGN_LEFT,  
  41.                            "F-Left",  
  42.                            document.left(), y, 0);  
  43.         //中  
  44.         cb.showTextAligned(PdfContentByte.ALIGN_CENTER,  
  45.                             writer.getPageNumber()+" page",  
  46.                            (document.right() + document.left())/2,  
  47.                            y, 0);  
  48.         //右  
  49.         cb.showTextAligned(PdfContentByte.ALIGN_RIGHT,  
  50.                            "F-Right",  
  51.                            document.right(), y, 0);  
  52.   
  53.         cb.endText();  
  54.           
  55.         cb.restoreState();  
  56.     }  
  57. });  
  58.   
  59. doc.open();  
  60. doc.add(new Paragraph("1 page"));          
  61. doc.newPage();  
  62. doc.add(new Paragraph("2 page"));          
  63. doc.newPage();  
  64. doc.add(new Paragraph("3 page"));          
  65. doc.newPage();  
  66. doc.add(new Paragraph("4 page"));  


15、左右文字 
Java代碼  收藏代碼
  1. PdfWriter writer = PdfWriter.getInstance(document, out);  
  2.   
  3. document.open();  
  4.   
  5. PdfContentByte canvas = writer.getDirectContent();  
  6.   
  7. Phrase phrase1 = new Phrase("This is a test!left");  
  8. Phrase phrase2 = new Phrase("This is a test!right");  
  9. Phrase phrase3 = new Phrase("This is a test!center");  
  10. ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, phrase1, 105000);  
  11. ColumnText.showTextAligned(canvas, Element.ALIGN_RIGHT, phrase2, 105360);  
  12. ColumnText.showTextAligned(canvas, Element.ALIGN_CENTER, phrase3, 105720);  


16、幻燈片放映 
Java代碼  收藏代碼
  1. PdfWriter writer = PdfWriter.getInstance(doc, out);  
  2.   
  3. writer.setPdfVersion(PdfWriter.VERSION_1_5);  
  4.   
  5. writer.setViewerPreferences(PdfWriter.PageModeFullScreen);//全屏  
  6. writer.setPageEvent(new PdfPageEventHelper() {  
  7.     public void onStartPage(PdfWriter writer, Document document) {  
  8.         writer.setTransition(new PdfTransition(PdfTransition.DISSOLVE, 3));  
  9.         writer.setDuration(5);//間隔時間  
  10.     }  
  11. });  
  12.   
  13. doc.open();  
  14. doc.add(new Paragraph("1 page"));  
  15. doc.newPage();  
  16. doc.add(new Paragraph("2 page"));  
  17. doc.newPage();  
  18. doc.add(new Paragraph("3 page"));  
  19. doc.newPage();  
  20. doc.add(new Paragraph("4 page"));  
  21. doc.newPage();  
  22. doc.add(new Paragraph("5 page"));  


17、壓縮PDF到Zip 
Java代碼  收藏代碼
  1. ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(FILE_DIR + "zipPDF.zip"));  
  2. for (int i = 1; i <= 3; i++) {  
  3.     ZipEntry entry = new ZipEntry("hello_" + i + ".pdf");  
  4.     zip.putNextEntry(entry);  
  5.     Document document = new Document();  
  6.     PdfWriter writer = PdfWriter.getInstance(document, zip);  
  7.     writer.setCloseStream(false);  
  8.     document.open();  
  9.     document.add(new Paragraph("Hello " + i));  
  10.     document.close();  
  11.     zip.closeEntry();  
  12. }  
  13. zip.close();  

 

18、分割PDF 
Java代碼  收藏代碼
  1. FileOutputStream out = new FileOutputStream(FILE_DIR + "splitPDF.pdf");  
  2.   
  3. Document document = new Document();  
  4.   
  5. PdfWriter.getInstance(document, out);  
  6.   
  7. document.open();  
  8. document.add(new Paragraph("1 page"));  
  9.   
  10. document.newPage();  
  11. document.add(new Paragraph("2 page"));  
  12.   
  13. document.newPage();  
  14. document.add(new Paragraph("3 page"));  
  15.   
  16. document.newPage();  
  17. document.add(new Paragraph("4 page"));  
  18.   
  19. document.close();  
  20.   
  21. PdfReader reader = new PdfReader(FILE_DIR + "splitPDF.pdf");  
  22.   
  23. Document dd = new Document();  
  24. PdfWriter writer = PdfWriter.getInstance(dd, new FileOutputStream(FILE_DIR + "splitPDF1.pdf"));  
  25. dd.open();  
  26. PdfContentByte cb = writer.getDirectContent();  
  27. dd.newPage();  
  28. cb.addTemplate(writer.getImportedPage(reader, 1), 00);  
  29. dd.newPage();  
  30. cb.addTemplate(writer.getImportedPage(reader, 2), 00);  
  31. dd.close();  
  32. writer.close();  
  33.   
  34. Document dd2 = new Document();  
  35. PdfWriter writer2 = PdfWriter.getInstance(dd2, new FileOutputStream(FILE_DIR + "splitPDF2.pdf"));  
  36. dd2.open();  
  37. PdfContentByte cb2 = writer2.getDirectContent();  
  38. dd2.newPage();  
  39. cb2.addTemplate(writer2.getImportedPage(reader, 3), 00);  
  40. dd2.newPage();  
  41. cb2.addTemplate(writer2.getImportedPage(reader, 4), 00);  
  42. dd2.close();  
  43. writer2.close();  


19、合併PDF 
Java代碼  收藏代碼
  1. PdfReader reader1 = new PdfReader(FILE_DIR + "splitPDF1.pdf");  
  2. PdfReader reader2 = new PdfReader(FILE_DIR + "splitPDF2.pdf");  
  3.   
  4. FileOutputStream out = new FileOutputStream(FILE_DIR + "mergePDF.pdf");  
  5.   
  6. Document document = new Document();  
  7. PdfWriter writer = PdfWriter.getInstance(document, out);  
  8.   
  9. document.open();  
  10. PdfContentByte cb = writer.getDirectContent();  
  11.   
  12. int totalPages = 0;  
  13. totalPages += reader1.getNumberOfPages();  
  14. totalPages += reader2.getNumberOfPages();  
  15.   
  16. java.util.List<PdfReader> readers = new ArrayList<PdfReader>();  
  17. readers.add(reader1);  
  18. readers.add(reader2);  
  19.   
  20. int pageOfCurrentReaderPDF = 0;  
  21. Iterator<PdfReader> iteratorPDFReader = readers.iterator();  
  22.   
  23. // Loop through the PDF files and add to the output.  
  24. while (iteratorPDFReader.hasNext()) {  
  25.     PdfReader pdfReader = iteratorPDFReader.next();  
  26.   
  27.     // Create a new page in the target for each source page.  
  28.     while (pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) {  
  29.         document.newPage();  
  30.         pageOfCurrentReaderPDF++;  
  31.         PdfImportedPage page = writer.getImportedPage(pdfReader, pageOfCurrentReaderPDF);  
  32.         cb.addTemplate(page, 00);  
  33.     }  
  34.     pageOfCurrentReaderPDF = 0;  
  35. }  
  36. out.flush();  
  37. document.close();  
  38. out.close();  


20、Annotation 
Java代碼  收藏代碼
  1. PdfWriter writer = PdfWriter.getInstance(doc, out);  
  2. writer.setLinearPageMode();  
  3.   
  4. doc.open();  
  5. doc.add(new Paragraph("1 page"));  
  6. doc.add(new Annotation("Title""This is a annotation!"));  
  7.   
  8. doc.newPage();  
  9. doc.add(new Paragraph("2 page"));  
  10. Chunk chunk = new Chunk("\u00a0");  
  11. chunk.setAnnotation(PdfAnnotation.createText(writer, null"Title""This is a another annotation!"false"Comment"));  
  12. doc.add(chunk);  
  13.   
  14. //添加附件  
  15. doc.newPage();  
  16. doc.add(new Paragraph("3 page"));  
  17. Chunk chunk2 = new Chunk("\u00a0\u00a0");  
  18. PdfAnnotation annotation = PdfAnnotation.createFileAttachment(  
  19.         writer, null"Title"null,  
  20.         "resource/test2.jpg",  
  21.         "img.jpg");  
  22. annotation.put(PdfName.NAME,  
  23.         new PdfString("Paperclip"));  
  24. chunk2.setAnnotation(annotation);  
  25. doc.add(chunk2);  

 

21、插入一個Table 
Java代碼  收藏代碼
  1. PdfPTable table = new PdfPTable(3);  
  2. PdfPCell cell;  
  3. cell = new PdfPCell(new Phrase("Cell with colspan 3"));  
  4. cell.setColspan(3);  
  5. table.addCell(cell);  
  6. cell = new PdfPCell(new Phrase("Cell with rowspan 2"));  
  7. cell.setRowspan(2);  
  8. table.addCell(cell);  
  9. table.addCell("row 1; cell 1");  
  10. table.addCell("row 1; cell 2");  
  11. table.addCell("row 2; cell 1");  
  12. table.addCell("row 2; cell 2");  
  13.   
  14. document.add(table);  


22、表格嵌套 
Java代碼  收藏代碼
  1. PdfPTable table = new PdfPTable(4);  
  2.   
  3. //1行2列  
  4. PdfPTable nested1 = new PdfPTable(2);  
  5. nested1.addCell("1.1");  
  6. nested1.addCell("1.2");  
  7.   
  8. //2行1列  
  9. PdfPTable nested2 = new PdfPTable(1);  
  10. nested2.addCell("2.1");  
  11. nested2.addCell("2.2");  
  12.   
  13. //將表格插入到指定位置  
  14. for (int k = 0; k < 24; ++k) {  
  15.     if (k == 1) {  
  16.         table.addCell(nested1);  
  17.     } else if (k == 20) {  
  18.         table.addCell(nested2);  
  19.     } else {  
  20.         table.addCell("cell " + k);  
  21.     }  
  22. }  
  23.   
  24. document.add(table);  


23、設置表格寬度 
Java代碼  收藏代碼
  1. PdfPTable table = new PdfPTable(3);  
  2. PdfPCell cell;  
  3. cell = new PdfPCell(new Phrase("Cell with colspan 3"));  
  4. cell.setColspan(3);  
  5. table.addCell(cell);  
  6. cell = new PdfPCell(new Phrase("Cell with rowspan 2"));  
  7. cell.setRowspan(2);  
  8. table.addCell(cell);  
  9. table.addCell("row 1; cell 1");  
  10. table.addCell("row 1; cell 2");  
  11. table.addCell("row 2; cell 1");  
  12. table.addCell("row 2; cell 2");  
  13.   
  14. //100%  
  15. table.setWidthPercentage(100);  
  16. document.add(table);          
  17. document.add(new Paragraph("\n\n"));  
  18.   
  19. //寬度50% 居左  
  20. table.setHorizontalAlignment(Element.ALIGN_LEFT);  
  21. document.add(table);  
  22. document.add(new Paragraph("\n\n"));  
  23.   
  24. //寬度50% 居中  
  25. table.setHorizontalAlignment(Element.ALIGN_CENTER);  
  26. document.add(table);  
  27. document.add(new Paragraph("\n\n"));  
  28.   
  29. //寬度50% 居右  
  30. table.setWidthPercentage(50);  
  31. table.setHorizontalAlignment(Element.ALIGN_RIGHT);  
  32. document.add(table);  
  33. document.add(new Paragraph("\n\n"));  
  34.   
  35. //固定寬度  
  36. table.setTotalWidth(300);  
  37. table.setLockedWidth(true);  
  38. document.add(table);  


24、設置表格前後間隔 
Java代碼  收藏代碼
  1. PdfPTable table = new PdfPTable(3);  
  2. PdfPCell cell = new PdfPCell(new Paragraph("合併3個單元格",fontZH));  
  3. cell.setColspan(3);  
  4. table.addCell(cell);  
  5. table.addCell("1.1");  
  6. table.addCell("2.1");  
  7. table.addCell("3.1");  
  8. table.addCell("1.2");  
  9. table.addCell("2.2");  
  10. table.addCell("3.2");  
  11.   
  12. cell = new PdfPCell(new Paragraph("紅色邊框",fontZH));  
  13. cell.setBorderColor(new BaseColor(25500));  
  14. table.addCell(cell);  
  15.   
  16. cell = new PdfPCell(new Paragraph("合併單2個元格",fontZH));  
  17. cell.setColspan(2);  
  18. cell.setBackgroundColor(new BaseColor(0xC00xC00xC0));  
  19. table.addCell(cell);  
  20.   
  21. table.setWidthPercentage(50);  
  22.   
  23. document.add(new Paragraph("追加2個表格",fontZH));  
  24. document.add(table);  
  25. document.add(table);  
  26.   
  27. document.newPage();  
  28. document.add(new Paragraph("使用'SpacingBefore'和'setSpacingAfter'",fontZH));  
  29. table.setSpacingBefore(15f);  
  30. document.add(table);  
  31. document.add(table);  
  32. document.add(new Paragraph("這裏沒有間隔",fontZH));  
  33. table.setSpacingAfter(15f);  


25、設置單元格寬度 
Java代碼  收藏代碼
  1. //按比例設置單元格寬度  
  2. float[] widths = {0.1f, 0.1f, 0.05f, 0.75f};  
  3. PdfPTable table = new PdfPTable(widths);  
  4. table.addCell("10%");  
  5. table.addCell("10%");  
  6. table.addCell("5%");  
  7. table.addCell("75%");  
  8. table.addCell("aa");  
  9. table.addCell("aa");  
  10. table.addCell("a");  
  11. table.addCell("aaaaaaaaaaaaaaa");  
  12. table.addCell("bb");  
  13. table.addCell("bb");  
  14. table.addCell("b");  
  15. table.addCell("bbbbbbbbbbbbbbb");  
  16. table.addCell("cc");  
  17. table.addCell("cc");  
  18. table.addCell("c");  
  19. table.addCell("ccccccccccccccc");  
  20. document.add(table);  
  21. document.add(new Paragraph("\n\n"));  
  22.   
  23. //調整比例  
  24. widths[0] = 20f;  
  25. widths[1] = 20f;  
  26. widths[2] = 10f;  
  27. widths[3] = 50f;  
  28. table.setWidths(widths);  
  29. document.add(table);  
  30.   
  31. //按絕對值設置單元格寬度  
  32. widths[0] = 40f;  
  33. widths[1] = 40f;  
  34. widths[2] = 20f;  
  35. widths[3] = 300f;  
  36. Rectangle r = new Rectangle(PageSize.A4.getRight(72), PageSize.A4.getTop(72));  
  37. table.setWidthPercentage(widths, r);  
  38. document.add(new Paragraph("\n\n"));  
  39. document.add(table);  


26、設置單元格高度 
Java代碼  收藏代碼
  1. PdfPTable table = new PdfPTable(2);  
  2.   
  3. PdfPCell cell;  
  4.   
  5. //折行  
  6. table.addCell(new PdfPCell(new Paragraph("折行", fontZH)));  
  7. cell = new PdfPCell(new Paragraph("blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah"));  
  8. cell.setNoWrap(false);  
  9. table.addCell(cell);  
  10.   
  11. //不折行  
  12. table.addCell(new PdfPCell(new Paragraph("不折行", fontZH)));  
  13. cell.setNoWrap(true);  
  14. table.addCell(cell);  
  15.   
  16. //設置高度  
  17. table.addCell(new PdfPCell(new Paragraph("任意高度",fontZH)));  
  18. cell = new PdfPCell(new Paragraph("1. blah blah\n2. blah blah blah\n3. blah blah\n4. blah blah blah\n5. blah blah\n6. blah blah blah\n7. blah blah\n8. blah blah blah"));  
  19. table.addCell(cell);  
  20.   
  21. //固定高度  
  22. table.addCell(new PdfPCell(new Paragraph("固定高度",fontZH)));  
  23. cell.setFixedHeight(50f);  
  24. table.addCell(cell);  
  25.   
  26. //最小高度  
  27. table.addCell(new PdfPCell(new Paragraph("最小高度",fontZH)));  
  28. cell = new PdfPCell(new Paragraph("最小高度:50",fontZH));  
  29. cell.setMinimumHeight(50f);  
  30. table.addCell(cell);  
  31.   
  32. //最後一行拉長到page底部  
  33. table.setExtendLastRow(true);  
  34. table.addCell(new PdfPCell(new Paragraph("拉長最後一行",fontZH)));  
  35. cell = new PdfPCell(new Paragraph("最後一行拉長到page底部",fontZH));  
  36. table.addCell(cell);  
  37.   
  38. document.add(table);  


27、設置單元格顏色 
Java代碼  收藏代碼
  1. PdfPTable table = new PdfPTable(4);  
  2. PdfPCell cell;  
  3. cell = new PdfPCell(new Paragraph("顏色測試",fontZH));  
  4. table.addCell(cell);  
  5.   
  6. //紅色背景,無邊框  
  7. cell = new PdfPCell(new Paragraph("紅色背景,無邊框",fontZH));  
  8. cell.setBorder(Rectangle.NO_BORDER);  
  9. cell.setBackgroundColor(BaseColor.RED);  
  10. table.addCell(cell);  
  11.   
  12. //綠色背景,下邊框  
  13. cell = new PdfPCell(new Paragraph("綠色背景,下邊框",fontZH));  
  14. cell.setBorder(Rectangle.BOTTOM);  
  15. cell.setBorderColorBottom(BaseColor.MAGENTA);  
  16. cell.setBorderWidthBottom(5f);  
  17. cell.setBackgroundColor(BaseColor.GREEN);  
  18. table.addCell(cell);  
  19.   
  20. //藍色背景,上邊框  
  21. cell = new PdfPCell(new Paragraph("藍色背景,上邊框",fontZH));  
  22. cell.setBorder(Rectangle.TOP);  
  23. cell.setUseBorderPadding(true);  
  24. cell.setBorderWidthTop(5f);  
  25. cell.setBorderColorTop(BaseColor.CYAN);  
  26. cell.setBackgroundColor(BaseColor.BLUE);  
  27. table.addCell(cell);  
  28.   
  29. cell = new PdfPCell(new Paragraph("背景灰色度",fontZH));  
  30. table.addCell(cell);  
  31. cell = new PdfPCell(new Paragraph("0.25"));  
  32. cell.setBorder(Rectangle.NO_BORDER);  
  33. cell.setGrayFill(0.25f);  
  34. table.addCell(cell);  
  35. cell = new PdfPCell(new Paragraph("0.5"));  
  36. cell.setBorder(Rectangle.NO_BORDER);  
  37. cell.setGrayFill(0.5f);  
  38. table.addCell(cell);  
  39. cell = new PdfPCell(new Paragraph("0.75"));  
  40. cell.setBorder(Rectangle.NO_BORDER);  
  41. cell.setGrayFill(0.75f);  
  42. table.addCell(cell);  
  43.   
  44. document.add(table);  


28、插入圖像 
Java代碼  收藏代碼
  1. Image image = Image.getInstance("resource/test2.jpg");  
  2. float[] widths = { 1f, 4f };  
  3.   
  4. PdfPTable table = new PdfPTable(widths);  
  5.   
  6. //插入圖片  
  7. table.addCell(new PdfPCell(new Paragraph("圖片測試", fontZH)));  
  8. table.addCell(image);  
  9.   
  10. //調整圖片大小  
  11. table.addCell("This two");  
  12. table.addCell(new PdfPCell(image, true));  
  13.   
  14. //不調整  
  15. table.addCell("This three");  
  16. table.addCell(new PdfPCell(image, false));  
  17. document.add(table);  


29、設置表頭 
Java代碼  收藏代碼
  1. String[] bogusData = { "M0065920""SL""FR86000P""PCGOLD",  
  2.         "119000""96 06""2001-08-13""4350""6011648299",  
  3.         "FLFLMTGP""153""119000.00" };  
  4. int NumColumns = 12;  
  5. // 12  
  6. PdfPTable datatable = new PdfPTable(NumColumns);  
  7. int headerwidths[] = { 9481081197910410 }; // percentage  
  8. datatable.setWidths(headerwidths);  
  9. datatable.setWidthPercentage(100);  
  10. datatable.getDefaultCell().setPadding(3);  
  11. datatable.getDefaultCell().setBorderWidth(2);  
  12. datatable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);  
  13.   
  14. datatable.addCell("Clock #");  
  15. datatable.addCell("Trans Type");  
  16. datatable.addCell("Cusip");  
  17. datatable.addCell("Long Name");  
  18. datatable.addCell("Quantity");  
  19. datatable.addCell("Fraction Price");  
  20. datatable.addCell("Settle Date");  
  21. datatable.addCell("Portfolio");  
  22. datatable.addCell("ADP Number");  
  23. datatable.addCell("Account ID");  
  24. datatable.addCell("Reg Rep ID");  
  25. datatable.addCell("Amt To Go ");  
  26.   
  27. datatable.setHeaderRows(1);  
  28.   
  29. //邊框  
  30. datatable.getDefaultCell().setBorderWidth(1);  
  31.   
  32. //背景色  
  33. for (int i = 1; i < 1000; i++) {  
  34.     for (int x = 0; x < NumColumns; x++) {  
  35.         datatable.addCell(bogusData[x]);  
  36.     }  
  37. }  
  38.   
  39. document.add(datatable);  


30、分割表格 
Java代碼  收藏代碼
  1. //橫向分割  
  2. PdfContentByte cb = writer.getDirectContent();  
  3. PdfPTable table = new PdfPTable(10);  
  4. for (int k = 1; k <= 100; ++k) {  
  5.     table.addCell("The number " + k);  
  6. }  
  7. table.setTotalWidth(400);  
  8.   
  9. table.writeSelectedRows(050, -15700, cb);  
  10. table.writeSelectedRows(5, -10, -1210700, cb);  


31、設置單元格留白 
Java代碼  收藏代碼
  1. PdfPTable table = new PdfPTable(2);  
  2. PdfPCell cell;  
  3. Paragraph p = new Paragraph("Quick brown fox jumps over the lazy dog. Quick brown fox jumps over the lazy dog.");  
  4. table.addCell(new PdfPCell(new Paragraph("默認",fontZH)));  
  5. table.addCell(p);  
  6. table.addCell(new PdfPCell(new Paragraph("Padding:10",fontZH)));  
  7. cell = new PdfPCell(p);  
  8. cell.setPadding(10f);  
  9. table.addCell(cell);  
  10. table.addCell(new PdfPCell(new Paragraph("Padding:0",fontZH)));  
  11. cell = new PdfPCell(p);  
  12. cell.setPadding(0f);  
  13. table.addCell(cell);  
  14. table.addCell(new PdfPCell(new Paragraph("上Padding:0 左Padding:20",fontZH)));  
  15. cell = new PdfPCell(p);  
  16. cell.setPaddingTop(0f);  
  17. cell.setPaddingLeft(20f);  
  18. table.addCell(cell);  
  19. document.add(table);  
  20.   
  21. document.newPage();  
  22. table = new PdfPTable(2);  
  23. table.addCell(new PdfPCell(new Paragraph("沒有Leading",fontZH)));  
  24. table.getDefaultCell().setLeading(0f, 0f);  
  25. table.addCell("blah blah\nblah blah blah\nblah blah\nblah blah blah\nblah blah\nblah blah blah\nblah blah\nblah blah blah\n");  
  26. table.getDefaultCell().setLeading(14f, 0f);  
  27. table.addCell(new PdfPCell(new Paragraph("固定Leading:14pt",fontZH)));  
  28. table.addCell("blah blah\nblah blah blah\nblah blah\nblah blah blah\nblah blah\nblah blah blah\nblah blah\nblah blah blah\n");  
  29. table.addCell(new PdfPCell(new Paragraph("相對於字體",fontZH)));  
  30. table.getDefaultCell().setLeading(0f, 1.0f);  
  31. table.addCell("blah blah\nblah blah blah\nblah blah\nblah blah blah\nblah blah\nblah blah blah\nblah blah\nblah blah blah\n");  
  32. document.add(table);  


32、設置單元格邊框 
Java代碼  收藏代碼
  1. //沒有邊框  
  2. PdfPTable table1 = new PdfPTable(3);    
  3. table1.getDefaultCell().setBorder(PdfPCell.NO_BORDER);    
  4. table1.addCell(new Paragraph("Cell 1"));   
  5. table1.addCell(new Paragraph("Cell 2"));   
  6. table1.addCell(new Paragraph("Cell 3"));   
  7. document.add(table1);  
  8.   
  9. //邊框粗細顏色  
  10. document.newPage();  
  11. Rectangle b1 = new Rectangle(0f, 0f);  
  12. b1.setBorderWidthLeft(6f);  
  13. b1.setBorderWidthBottom(5f);  
  14. b1.setBorderWidthRight(4f);  
  15. b1.setBorderWidthTop(2f);  
  16. b1.setBorderColorLeft(BaseColor.RED);  
  17. b1.setBorderColorBottom(BaseColor.ORANGE);  
  18. b1.setBorderColorRight(BaseColor.YELLOW);  
  19. b1.setBorderColorTop(BaseColor.GREEN);  
  20. PdfPTable table2 = new PdfPTable(1);  
  21. PdfPCell cell =  new PdfPCell(new Paragraph("Cell 1"));  
  22. cell.cloneNonPositionParameters(b1);  
  23. table2.addCell(cell);  
  24. document.add(table2);  


33、PdfPTableEvent 

34、PdfPCellEvent 

35、PdfPageEventHelper 

36、生成Barcode QRCode 
Java代碼  收藏代碼
  1. String myString = "http://www.google.com";  
  2.   
  3. Barcode128 code128 = new Barcode128();  
  4. code128.setCode(myString.trim());  
  5. code128.setCodeType(Barcode128.CODE128);  
  6. Image code128Image = code128.createImageWithBarcode(cb, nullnull);  
  7. code128Image.setAbsolutePosition(10,700);  
  8. code128Image.scalePercent(125);  
  9. doc.add(code128Image);  
  10.   
  11. BarcodeQRCode qrcode = new BarcodeQRCode(myString.trim(), 11null);  
  12. Image qrcodeImage = qrcode.getImage();  
  13. qrcodeImage.setAbsolutePosition(10,600);  
  14. qrcodeImage.scalePercent(200);  
  15. doc.add(qrcodeImage);  

 

37、HTML to PDF 
Java代碼  收藏代碼
  1. Document document = new Document(PageSize.LETTER);  
  2. PdfWriter.getInstance(document, new FileOutputStream("c://testpdf1.pdf"));  
  3. document.open();  
  4. HTMLWorker htmlWorker = new HTMLWorker(document);  
  5. htmlWorker.parse(new StringReader("<h1>This is a test!</h1>"));  
  6. document.close();  

 

原文出自:http://rensanning.iteye.com/blog/1538689

發佈了74 篇原創文章 · 獲贊 11 · 訪問量 39萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章