Java操作PDF之iText详细入门

2016年08月08日 11:06:00

阅读数:19490
iText是著名的开放项目,是用于生成PDF文档的一个java类库。通过iText不仅可以生成PDF或rtf的文档,而且可以将XML、Html文件转化为PDF文件。

http://itextpdf.com/

版本:itextpdf-5.2.1.jar

1、生成一个PDF

  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

  1. //页面大小
  2. Rectangle rect = new Rectangle(PageSize.B5.rotate());
  3. //页面背景色
  4. rect.setBackgroundColor(BaseColor.ORANGE);
  5. Document doc = new Document(rect);
  6. PdfWriter writer = PdfWriter.getInstance(doc, out);
  7. //PDF版本(默认1.4)
  8. writer.setPdfVersion(PdfWriter.PDF_VERSION_1_2);
  9. //文档属性
  10. doc.addTitle("Title@sample");
  11. doc.addAuthor("Author@rensanning");
  12. doc.addSubject("Subject@iText sample");
  13. doc.addKeywords("Keywords@iText");
  14. doc.addCreator("Creator@iText");
  15. //页边空白
  16. doc.setMargins(10, 20, 30, 40);
  17. doc.open();
  18. doc.add(new Paragraph("Hello World"));

3、设置密码

  1. PdfWriter writer = PdfWriter.getInstance(doc, out);
  2. // 设置密码为:"World"
  3. writer.setEncryption("Hello".getBytes(), "World".getBytes(),
  4. PdfWriter.ALLOW_SCREENREADERS,
  5. PdfWriter.STANDARD_ENCRYPTION_128);
  6. doc.open();
  7. doc.add(new Paragraph("Hello World"));

4、添加Page

  1. document.open();
  2. document.add(new Paragraph("First page"));
  3. document.add(new Paragraph(Document.getVersion()));
  4. document.newPage();
  5. writer.setPageEmpty(false);
  6. document.newPage();
  7. document.add(new Paragraph("New page"));

5、添加水印(背景图)

  1. //图片水印
  2. PdfReader reader = new PdfReader(FILE_DIR + "setWatermark.pdf");
  3. PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(FILE_DIR
  4. + "setWatermark2.pdf"));
  5. Image img = Image.getInstance("resource/watermark.jpg");
  6. img.setAbsolutePosition(200, 400);
  7. PdfContentByte under = stamp.getUnderContent(1);
  8. under.addImage(img);
  9. //文字水印
  10. PdfContentByte over = stamp.getOverContent(2);
  11. over.beginText();
  12. BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI,
  13. BaseFont.EMBEDDED);
  14. over.setFontAndSize(bf, 18);
  15. over.setTextMatrix(30, 30);
  16. over.showTextAligned(Element.ALIGN_LEFT, "DUPLICATE", 230, 430, 45);
  17. over.endText();
  18. //背景图
  19. Image img2 = Image.getInstance("resource/test.jpg");
  20. img2.setAbsolutePosition(0, 0);
  21. PdfContentByte under2 = stamp.getUnderContent(3);
  22. under2.addImage(img2);
  23. stamp.close();
  24. reader.close();

6、插入Chunk, Phrase, Paragraph, List

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

7、插入Anchor, Image, Chapter, Section

  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. document.newPage();
  10. Anchor toUS = new Anchor("Go to first page.", new Font(Font.FontFamily.HELVETICA, 14, Font.BOLD, BaseColor.BLUE));
  11. toUS.setReference("#CN");//internal
  12. document.add(toUS);
  13. //Image对象
  14. document.newPage();
  15. Image img = Image.getInstance("resource/test.jpg");
  16. img.setAlignment(Image.LEFT | Image.TEXTWRAP);
  17. img.setBorder(Image.BOX);
  18. img.setBorderWidth(10);
  19. img.setBorderColor(BaseColor.WHITE);
  20. img.scaleToFit(1000, 72);//大小
  21. img.setRotationDegrees(-30);//旋转
  22. document.add(img);
  23. //Chapter, Section对象(目录)
  24. document.newPage();
  25. Paragraph title = new Paragraph("Title");
  26. Chapter chapter = new Chapter(title, 1);
  27. title = new Paragraph("Section A");
  28. Section section = chapter.addSection(title);
  29. section.setBookmarkTitle("bmk");
  30. section.setIndentation(30);
  31. section.setBookmarkOpen(false);
  32. section.setNumberStyle(
  33. Section.NUMBERSTYLE_DOTTED_WITHOUT_FINAL_DOT);
  34. Section subsection = section.addSection(new Paragraph("Sub Section A"));
  35. subsection.setIndentationLeft(20);
  36. subsection.setNumberDepth(1);
  37. document.add(chapter);

8、画图

  1. //左右箭头
  2. document.add(new VerticalPositionMark() {
  3. public void draw(PdfContentByte canvas, float llx, float lly,
  4. float urx, float ury, float y) {
  5. canvas.beginText();
  6. BaseFont bf = null;
  7. try {
  8. bf = BaseFont.createFont(BaseFont.ZAPFDINGBATS, "", BaseFont.EMBEDDED);
  9. } catch (Exception e) {
  10. e.printStackTrace();
  11. }
  12. canvas.setFontAndSize(bf, 12);
  13. // LEFT
  14. canvas.showTextAligned(Element.ALIGN_CENTER, String.valueOf((char) 220), llx - 10, y, 0);
  15. // RIGHT
  16. canvas.showTextAligned(Element.ALIGN_CENTER, String.valueOf((char) 220), urx + 10, y + 8, 180);
  17. canvas.endText();
  18. }
  19. });
  20. //直线
  21. Paragraph p1 = new Paragraph("LEFT");
  22. p1.add(new Chunk(new LineSeparator()));
  23. p1.add("R");
  24. document.add(p1);
  25. //点线
  26. Paragraph p2 = new Paragraph("LEFT");
  27. p2.add(new Chunk(new DottedLineSeparator()));
  28. p2.add("R");
  29. document.add(p2);
  30. //下滑线
  31. LineSeparator UNDERLINE = new LineSeparator(1, 100, null, Element.ALIGN_CENTER, -2);
  32. Paragraph p3 = new Paragraph("NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN");
  33. p3.add(UNDERLINE);
  34. document.add(p3);

9、设置段落

  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. p.setAlignment(Element.ALIGN_JUSTIFIED);
  4. document.add(p);
  5. document.newPage();
  6. p.setAlignment(Element.ALIGN_JUSTIFIED);
  7. p.setIndentationLeft(1 * 15f);
  8. p.setIndentationRight((5 - 1) * 15f);
  9. document.add(p);
  10. //居右
  11. document.newPage();
  12. p.setAlignment(Element.ALIGN_RIGHT);
  13. p.setSpacingAfter(15f);
  14. document.add(p);
  15. //居左
  16. document.newPage();
  17. p.setAlignment(Element.ALIGN_LEFT);
  18. p.setSpacingBefore(15f);
  19. document.add(p);
  20. //居中
  21. document.newPage();
  22. p.setAlignment(Element.ALIGN_CENTER);
  23. p.setSpacingAfter(15f);
  24. p.setSpacingBefore(15f);
  25. document.add(p);

10、删除Page

  1. FileOutputStream out = new FileOutputStream(FILE_DIR + "deletePage.pdf");
  2. Document document = new Document();
  3. PdfWriter writer = PdfWriter.getInstance(document, out);
  4. document.open();
  5. document.add(new Paragraph("First page"));
  6. document.add(new Paragraph(Document.getVersion()));
  7. document.newPage();
  8. writer.setPageEmpty(false);
  9. document.newPage();
  10. document.add(new Paragraph("New page"));
  11. document.close();
  12. PdfReader reader = new PdfReader(FILE_DIR + "deletePage.pdf");
  13. reader.selectPages("1,3");
  14. PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(FILE_DIR
  15. + "deletePage2.pdf"));
  16. stamp.close();
  17. reader.close();

11、插入Page

  1. FileOutputStream out = new FileOutputStream(FILE_DIR + "insertPage.pdf");
  2. Document document = new Document();
  3. PdfWriter.getInstance(document, out);
  4. document.open();
  5. document.add(new Paragraph("1 page"));
  6. document.newPage();
  7. document.add(new Paragraph("2 page"));
  8. document.newPage();
  9. document.add(new Paragraph("3 page"));
  10. document.close();
  11. PdfReader reader = new PdfReader(FILE_DIR + "insertPage.pdf");
  12. PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(FILE_DIR
  13. + "insertPage2.pdf"));
  14. stamp.insertPage(2, reader.getPageSize(1));
  15. ColumnText ct = new ColumnText(null);
  16. ct.addElement(new Paragraph(24, new Chunk("INSERT PAGE")));
  17. ct.setCanvas(stamp.getOverContent(2));
  18. ct.setSimpleColumn(36, 36, 559, 770);
  19. stamp.close();
  20. reader.close();

12、排序page

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

13、目录

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

14、Header, Footer

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

15、左右文字

  1. PdfWriter writer = PdfWriter.getInstance(document, out);
  2. document.open();
  3. PdfContentByte canvas = writer.getDirectContent();
  4. Phrase phrase1 = new Phrase("This is a test!left");
  5. Phrase phrase2 = new Phrase("This is a test!right");
  6. Phrase phrase3 = new Phrase("This is a test!center");
  7. ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, phrase1, 10, 500, 0);
  8. ColumnText.showTextAligned(canvas, Element.ALIGN_RIGHT, phrase2, 10, 536, 0);
  9. ColumnText.showTextAligned(canvas, Element.ALIGN_CENTER, phrase3, 10, 572, 0);

16、幻灯片放映

  1. PdfWriter writer = PdfWriter.getInstance(doc, out);
  2. writer.setPdfVersion(PdfWriter.VERSION_1_5);
  3. writer.setViewerPreferences(PdfWriter.PageModeFullScreen);//全屏
  4. writer.setPageEvent(new PdfPageEventHelper() {
  5. public void onStartPage(PdfWriter writer, Document document) {
  6. writer.setTransition(new PdfTransition(PdfTransition.DISSOLVE, 3));
  7. writer.setDuration(5);//间隔时间
  8. }
  9. });
  10. doc.open();
  11. doc.add(new Paragraph("1 page"));
  12. doc.newPage();
  13. doc.add(new Paragraph("2 page"));
  14. doc.newPage();
  15. doc.add(new Paragraph("3 page"));
  16. doc.newPage();
  17. doc.add(new Paragraph("4 page"));
  18. doc.newPage();
  19. doc.add(new Paragraph("5 page"));

17、压缩PDF到Zip

  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

  1. FileOutputStream out = new FileOutputStream(FILE_DIR + "splitPDF.pdf");
  2. Document document = new Document();
  3. PdfWriter.getInstance(document, out);
  4. document.open();
  5. document.add(new Paragraph("1 page"));
  6. document.newPage();
  7. document.add(new Paragraph("2 page"));
  8. document.newPage();
  9. document.add(new Paragraph("3 page"));
  10. document.newPage();
  11. document.add(new Paragraph("4 page"));
  12. document.close();
  13. PdfReader reader = new PdfReader(FILE_DIR + "splitPDF.pdf");
  14. Document dd = new Document();
  15. PdfWriter writer = PdfWriter.getInstance(dd, new FileOutputStream(FILE_DIR + "splitPDF1.pdf"));
  16. dd.open();
  17. PdfContentByte cb = writer.getDirectContent();
  18. dd.newPage();
  19. cb.addTemplate(writer.getImportedPage(reader, 1), 0, 0);
  20. dd.newPage();
  21. cb.addTemplate(writer.getImportedPage(reader, 2), 0, 0);
  22. dd.close();
  23. writer.close();
  24. Document dd2 = new Document();
  25. PdfWriter writer2 = PdfWriter.getInstance(dd2, new FileOutputStream(FILE_DIR + "splitPDF2.pdf"));
  26. dd2.open();
  27. PdfContentByte cb2 = writer2.getDirectContent();
  28. dd2.newPage();
  29. cb2.addTemplate(writer2.getImportedPage(reader, 3), 0, 0);
  30. dd2.newPage();
  31. cb2.addTemplate(writer2.getImportedPage(reader, 4), 0, 0);
  32. dd2.close();
  33. writer2.close();

19、合并PDF

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

20、Annotation

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

21、插入一个Table

  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. document.add(table);

22、表格嵌套

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

23、设置表格宽度

  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. //100%
  14. table.setWidthPercentage(100);
  15. document.add(table);
  16. document.add(new Paragraph("\n\n"));
  17. //宽度50% 居左
  18. table.setHorizontalAlignment(Element.ALIGN_LEFT);
  19. document.add(table);
  20. document.add(new Paragraph("\n\n"));
  21. //宽度50% 居中
  22. table.setHorizontalAlignment(Element.ALIGN_CENTER);
  23. document.add(table);
  24. document.add(new Paragraph("\n\n"));
  25. //宽度50% 居右
  26. table.setWidthPercentage(50);
  27. table.setHorizontalAlignment(Element.ALIGN_RIGHT);
  28. document.add(table);
  29. document.add(new Paragraph("\n\n"));
  30. //固定宽度
  31. table.setTotalWidth(300);
  32. table.setLockedWidth(true);
  33. document.add(table);

24、设置表格前后间隔

  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. cell = new PdfPCell(new Paragraph("红色边框",fontZH));
  12. cell.setBorderColor(new BaseColor(255, 0, 0));
  13. table.addCell(cell);
  14. cell = new PdfPCell(new Paragraph("合并单2个元格",fontZH));
  15. cell.setColspan(2);
  16. cell.setBackgroundColor(new BaseColor(0xC0, 0xC0, 0xC0));
  17. table.addCell(cell);
  18. table.setWidthPercentage(50);
  19. document.add(new Paragraph("追加2个表格",fontZH));
  20. document.add(table);
  21. document.add(table);
  22. document.newPage();
  23. document.add(new Paragraph("使用'SpacingBefore'和'setSpacingAfter'",fontZH));
  24. table.setSpacingBefore(15f);
  25. document.add(table);
  26. document.add(table);
  27. document.add(new Paragraph("这里没有间隔",fontZH));
  28. table.setSpacingAfter(15f);

25、设置单元格宽度

  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. widths[0] = 20f;
  24. widths[1] = 20f;
  25. widths[2] = 10f;
  26. widths[3] = 50f;
  27. table.setWidths(widths);
  28. document.add(table);
  29. //按绝对值设置单元格宽度
  30. widths[0] = 40f;
  31. widths[1] = 40f;
  32. widths[2] = 20f;
  33. widths[3] = 300f;
  34. Rectangle r = new Rectangle(PageSize.A4.getRight(72), PageSize.A4.getTop(72));
  35. table.setWidthPercentage(widths, r);
  36. document.add(new Paragraph("\n\n"));
  37. document.add(table);

26、设置单元格高度

  1. PdfPTable table = new PdfPTable(2);
  2. PdfPCell cell;
  3. //折行
  4. table.addCell(new PdfPCell(new Paragraph("折行", fontZH)));
  5. 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"));
  6. cell.setNoWrap(false);
  7. table.addCell(cell);
  8. //不折行
  9. table.addCell(new PdfPCell(new Paragraph("不折行", fontZH)));
  10. cell.setNoWrap(true);
  11. table.addCell(cell);
  12. //设置高度
  13. table.addCell(new PdfPCell(new Paragraph("任意高度",fontZH)));
  14. 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"));
  15. table.addCell(cell);
  16. //固定高度
  17. table.addCell(new PdfPCell(new Paragraph("固定高度",fontZH)));
  18. cell.setFixedHeight(50f);
  19. table.addCell(cell);
  20. //最小高度
  21. table.addCell(new PdfPCell(new Paragraph("最小高度",fontZH)));
  22. cell = new PdfPCell(new Paragraph("最小高度:50",fontZH));
  23. cell.setMinimumHeight(50f);
  24. table.addCell(cell);
  25. //最后一行拉长到page底部
  26. table.setExtendLastRow(true);
  27. table.addCell(new PdfPCell(new Paragraph("拉长最后一行",fontZH)));
  28. cell = new PdfPCell(new Paragraph("最后一行拉长到page底部",fontZH));
  29. table.addCell(cell);
  30. document.add(table);

27、设置单元格颜色

  1. PdfPTable table = new PdfPTable(4);
  2. PdfPCell cell;
  3. cell = new PdfPCell(new Paragraph("颜色测试",fontZH));
  4. table.addCell(cell);
  5. //红色背景,无边框
  6. cell = new PdfPCell(new Paragraph("红色背景,无边框",fontZH));
  7. cell.setBorder(Rectangle.NO_BORDER);
  8. cell.setBackgroundColor(BaseColor.RED);
  9. table.addCell(cell);
  10. //绿色背景,下边框
  11. cell = new PdfPCell(new Paragraph("绿色背景,下边框",fontZH));
  12. cell.setBorder(Rectangle.BOTTOM);
  13. cell.setBorderColorBottom(BaseColor.MAGENTA);
  14. cell.setBorderWidthBottom(5f);
  15. cell.setBackgroundColor(BaseColor.GREEN);
  16. table.addCell(cell);
  17. //蓝色背景,上边框
  18. cell = new PdfPCell(new Paragraph("蓝色背景,上边框",fontZH));
  19. cell.setBorder(Rectangle.TOP);
  20. cell.setUseBorderPadding(true);
  21. cell.setBorderWidthTop(5f);
  22. cell.setBorderColorTop(BaseColor.CYAN);
  23. cell.setBackgroundColor(BaseColor.BLUE);
  24. table.addCell(cell);
  25. cell = new PdfPCell(new Paragraph("背景灰色度",fontZH));
  26. table.addCell(cell);
  27. cell = new PdfPCell(new Paragraph("0.25"));
  28. cell.setBorder(Rectangle.NO_BORDER);
  29. cell.setGrayFill(0.25f);
  30. table.addCell(cell);
  31. cell = new PdfPCell(new Paragraph("0.5"));
  32. cell.setBorder(Rectangle.NO_BORDER);
  33. cell.setGrayFill(0.5f);
  34. table.addCell(cell);
  35. cell = new PdfPCell(new Paragraph("0.75"));
  36. cell.setBorder(Rectangle.NO_BORDER);
  37. cell.setGrayFill(0.75f);
  38. table.addCell(cell);
  39. document.add(table);

28、插入图像

  1. Image image = Image.getInstance("resource/test2.jpg");
  2. float[] widths = { 1f, 4f };
  3. PdfPTable table = new PdfPTable(widths);
  4. //插入图片
  5. table.addCell(new PdfPCell(new Paragraph("图片测试", fontZH)));
  6. table.addCell(image);
  7. //调整图片大小
  8. table.addCell("This two");
  9. table.addCell(new PdfPCell(image, true));
  10. //不调整
  11. table.addCell("This three");
  12. table.addCell(new PdfPCell(image, false));
  13. document.add(table);

29、设置表头

  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[] = { 9, 4, 8, 10, 8, 11, 9, 7, 9, 10, 4, 10 }; // 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. datatable.addCell("Clock #");
  14. datatable.addCell("Trans Type");
  15. datatable.addCell("Cusip");
  16. datatable.addCell("Long Name");
  17. datatable.addCell("Quantity");
  18. datatable.addCell("Fraction Price");
  19. datatable.addCell("Settle Date");
  20. datatable.addCell("Portfolio");
  21. datatable.addCell("ADP Number");
  22. datatable.addCell("Account ID");
  23. datatable.addCell("Reg Rep ID");
  24. datatable.addCell("Amt To Go ");
  25. datatable.setHeaderRows(1);
  26. //边框
  27. datatable.getDefaultCell().setBorderWidth(1);
  28. //背景色
  29. for (int i = 1; i < 1000; i++) {
  30. for (int x = 0; x < NumColumns; x++) {
  31. datatable.addCell(bogusData[x]);
  32. }
  33. }
  34. document.add(datatable);

30、分割表格

  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. table.writeSelectedRows(0, 5, 0, -1, 5, 700, cb);
  9. table.writeSelectedRows(5, -1, 0, -1, 210, 700, cb);

31、设置单元格留白

  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. document.newPage();
  21. table = new PdfPTable(2);
  22. table.addCell(new PdfPCell(new Paragraph("没有Leading",fontZH)));
  23. table.getDefaultCell().setLeading(0f, 0f);
  24. table.addCell("blah blah\nblah blah blah\nblah blah\nblah blah blah\nblah blah\nblah blah blah\nblah blah\nblah blah blah\n");
  25. table.getDefaultCell().setLeading(14f, 0f);
  26. table.addCell(new PdfPCell(new Paragraph("固定Leading:14pt",fontZH)));
  27. table.addCell("blah blah\nblah blah blah\nblah blah\nblah blah blah\nblah blah\nblah blah blah\nblah blah\nblah blah blah\n");
  28. table.addCell(new PdfPCell(new Paragraph("相对于字体",fontZH)));
  29. table.getDefaultCell().setLeading(0f, 1.0f);
  30. table.addCell("blah blah\nblah blah blah\nblah blah\nblah blah blah\nblah blah\nblah blah blah\nblah blah\nblah blah blah\n");
  31. document.add(table);

32、设置单元格边框

  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. document.newPage();
  10. Rectangle b1 = new Rectangle(0f, 0f);
  11. b1.setBorderWidthLeft(6f);
  12. b1.setBorderWidthBottom(5f);
  13. b1.setBorderWidthRight(4f);
  14. b1.setBorderWidthTop(2f);
  15. b1.setBorderColorLeft(BaseColor.RED);
  16. b1.setBorderColorBottom(BaseColor.ORANGE);
  17. b1.setBorderColorRight(BaseColor.YELLOW);
  18. b1.setBorderColorTop(BaseColor.GREEN);
  19. PdfPTable table2 = new PdfPTable(1);
  20. PdfPCell cell =  new PdfPCell(new Paragraph("Cell 1"));
  21. cell.cloneNonPositionParameters(b1);
  22. table2.addCell(cell);
  23. document.add(table2);

33、PdfPTableEvent

34、PdfPCellEvent

35、PdfPageEventHelper

36、生成Barcode QRCode

  1. String myString = "http://www.google.com";
  2. Barcode128 code128 = new Barcode128();
  3. code128.setCode(myString.trim());
  4. code128.setCodeType(Barcode128.CODE128);
  5. Image code128Image = code128.createImageWithBarcode(cb, null, null);
  6. code128Image.setAbsolutePosition(10,700);
  7. code128Image.scalePercent(125);
  8. doc.add(code128Image);
  9. BarcodeQRCode qrcode = new BarcodeQRCode(myString.trim(), 1, 1, null);
  10. Image qrcodeImage = qrcode.getImage();
  11. qrcodeImage.setAbsolutePosition(10,600);
  12. qrcodeImage.scalePercent(200);
  13. doc.add(qrcodeImage);

37、HTML to PDF

  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();

 

转 Java操作PDF之iText详细入门的更多相关文章

  1. Java操作PDF之iText超入门

    iText是著名的开放项目,是用于生成PDF文档的一个java类库.通过iText不仅可以生成PDF或rtf的文档,而且可以将XML.Html文件转化为PDF文件. http://itextpdf.c ...

  2. Java操作PDF之itext入门

    转载:http://lichunhui.iteye.com/blog/1550584 iText是著名的开放项目,是用于生成PDF文档的一个java类库.通过iText不仅可以生成PDF或rtf的文档 ...

  3. Java 操作pdf与excel

    java 操作pdf组件  itextpdf <dependency> <groupId>com.itextpdf</groupId> <artifactId ...

  4. Java操作pdf: JarsperReport的简单使用

    在企业级应用开发中,报表生成.报表打印下载是其重要的一个环节.除了 Excel 报表之外,PDF 报表也有广泛的应用场景. 目前世面上比较流行的制作 PDF 报表的工具如下: iText PDF :i ...

  5. java操作pdf添加页眉条码添加水印图片

    添加条码页眉以及图片水印 1. 引入jar包     1. itext-4.2.1.jar     2. itext-asian-5.2.0.jar     3. jbarcode-0.2.8.jar ...

  6. java生成PDF文件(itext)

    itextpdf-5.4.3.jar下载地址: http://www.kuaipan.cn/file/id_58980483773788178.htm 导入itextpdf-5.4.3.jar ToP ...

  7. java操作pdf

    使用pdf模板生成pdf 1,工具 Adobe Acrobat X Pro 2,pom文件配置 <dependency> <groupId>com.itextpdf</g ...

  8. Java 借助poi操作PDF工具类

    ​ 一直以来说写一个关于Java操作PDF的工具类,也没有时间去写,今天抽空写一个简单的工具类,拥有PDF中 换行,字体大小,字体设置,字体颜色,首行缩进,居中,居左,居右,增加新一页等功能,如果需要 ...

  9. java操作Excel、PDF文件

    java操作Excel.PDF文件 分享者:Vashon 分享来源:CSDN博客 下面这些是在开发中用到的一些东西,有的代码贴的不是完整的,只是贴出了关于操作EXCEL的代码: jxl是一个*国人写的 ...

随机推荐

  1. Git全面应用

    Git是一个免费的开源分布式版本控制系统,旨在快速高效地处理从小型到大型项目的所有事务. Git易于学习,占地面积小,具有闪电般快速的性能. 它超越了Subversion,CVS,Perforce和C ...

  2. [持续交付实践] Jenkins Pipeline 高可用设计方法

    前言 这篇写好一段时间了,一直也没发布上来,今天稍微整理下了交下作业,部分内容偷懒引用了一些别人的内容.使用Jenkins做持续集成/持续交付,当业务达到一定规模的时候,Jenkins本身就很容易成为 ...

  3. Javascript 继承和多态

    近期通过一些巧合 或者说 思想转变吧 ... 想通过blog && 公众号 (个人公众号: KeepinJS)去记录自己的Javascript深度学习的内容,从而达到 进一步的自我提升 ...

  4. java实现HTTP Basic认证

    这两天一直在调试EMQ的API,通过HTTP的GET请求,可以查询到订阅列表信息,在浏览器中测试时,需要输入用户名和密码,然后才能显示出结果,输错或者不输入会返回401错误. 通过浏览器输入用户名和密 ...

  5. asp.net ajax get 调用(和post不一样,直接返回json才行,否则报错;post不能返回json)

    <script type="text/javascript" > $(document).ready(function () { $('#Label1').click( ...

  6. django 之 ContentType的使用

    1. ContentType 是干什么用的呢: 1. ContentType: 主要的作用就是Django orm的创建表的时候,可以方便多表查询使用,简化多表查询的过程 2.ContentType ...

  7. 性能学习随笔(1)--负载均衡之f5负载均衡

    负载均衡设计涉及软件负载和硬件负载,下文转自CSDN中一篇文章涉及f5硬负载知识 ----转载:https://blog.csdn.net/tvk872/article/details/8063489 ...

  8. git 创建新项目 本地仓库和远程仓库的合并

    1.$ git pull origin master --allow-unrelated-histories 告诉系统允许合并不相关历史的内容 2.git branch --set-upstream ...

  9. Java环境变量PATH和CLASSPATH

    Java开发中常用到环境变量的配置,下面简单介绍下Java中经常配置的环境变量:PATH和CLASSPATH. 1.PATH环境变量 1.1 作用简介 安装完JDK(Java Development ...

  10. C# ASP.NET Forms身份认证

    原文:https://www.cnblogs.com/kyo-lynn/p/3418577.html 原文:https://www.cnblogs.com/fish-li/archive/2012/0 ...