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. 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(10203040);
  17. doc.open();
  18. doc.add(new Paragraph("Hello World"));

3、设置密码

Java代码  收藏代码
  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

Java代码  收藏代码
  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、添加水印(背景图)

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. Image img = Image.getInstance("resource/watermark.jpg");
  6. img.setAbsolutePosition(200400);
  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(3030);
  16. over.showTextAligned(Element.ALIGN_LEFT, "DUPLICATE"23043045);
  17. over.endText();
  18. //背景图
  19. Image img2 = Image.getInstance("resource/test.jpg");
  20. img2.setAbsolutePosition(00);
  21. PdfContentByte under2 = stamp.getUnderContent(3);
  22. under2.addImage(img2);
  23. stamp.close();
  24. 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. 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

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. 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(100072);//大小
  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、画图

Java代码  收藏代码
  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((char220), llx - 10, y, 0);
  15. // RIGHT
  16. canvas.showTextAligned(Element.ALIGN_CENTER, String.valueOf((char220), urx + 10, y + 8180);
  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(1100null, Element.ALIGN_CENTER, -2);
  32. Paragraph p3 = new Paragraph("NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN");
  33. p3.add(UNDERLINE);
  34. 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. 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

Java代码  收藏代码
  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

Java代码  收藏代码
  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(24new Chunk("INSERT PAGE")));
  17. ct.setCanvas(stamp.getOverContent(2));
  18. ct.setSimpleColumn(3636559770);
  19. stamp.close();
  20. reader.close();

12、排序page

Java代码  收藏代码
  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、目录

Java代码  收藏代码
  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

Java代码  收藏代码
  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、左右文字

Java代码  收藏代码
  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, 105000);
  8. ColumnText.showTextAligned(canvas, Element.ALIGN_RIGHT, phrase2, 105360);
  9. ColumnText.showTextAligned(canvas, Element.ALIGN_CENTER, phrase3, 105720);

16、幻灯片放映

Java代码  收藏代码
  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

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. 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), 00);
  20. dd.newPage();
  21. cb.addTemplate(writer.getImportedPage(reader, 2), 00);
  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), 00);
  30. dd2.newPage();
  31. cb2.addTemplate(writer2.getImportedPage(reader, 4), 00);
  32. dd2.close();
  33. writer2.close();

19、合并PDF

Java代码  收藏代码
  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, 00);
  25. }
  26. pageOfCurrentReaderPDF = 0;
  27. }
  28. out.flush();
  29. document.close();
  30. out.close();

20、Annotation

Java代码  收藏代码
  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

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

22、表格嵌套

Java代码  收藏代码
  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、设置表格宽度

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. //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、设置表格前后间隔

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. cell = new PdfPCell(new Paragraph("红色边框",fontZH));
  12. cell.setBorderColor(new BaseColor(25500));
  13. table.addCell(cell);
  14. cell = new PdfPCell(new Paragraph("合并单2个元格",fontZH));
  15. cell.setColspan(2);
  16. cell.setBackgroundColor(new BaseColor(0xC00xC00xC0));
  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、设置单元格宽度

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. 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、设置单元格高度

Java代码  收藏代码
  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、设置单元格颜色

Java代码  收藏代码
  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、插入图像

Java代码  收藏代码
  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、设置表头

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. 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、分割表格

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. table.writeSelectedRows(050, -15700, cb);
  9. 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. 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、设置单元格边框

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. 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

Java代码  收藏代码
  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, nullnull);
  6. code128Image.setAbsolutePosition(10,700);
  7. code128Image.scalePercent(125);
  8. doc.add(code128Image);
  9. BarcodeQRCode qrcode = new BarcodeQRCode(myString.trim(), 11null);
  10. Image qrcodeImage = qrcode.getImage();
  11. qrcodeImage.setAbsolutePosition(10,600);
  12. qrcodeImage.scalePercent(200);
  13. 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();

  • 大小: 4.5 KB
  • 大小: 6 KB
  • 大小: 3.7 KB
  • 大小: 6.1 KB
  • 大小: 14.1 KB
  • 大小: 2.4 KB
  • iText_in_Action_第2版_.part2.rar (4.3 MB)
  • 下载次数: 1410
  • iText_in_Action_第2版_.part1.rar (8.3 MB)
  • 下载次数: 1511
  • iTextTest.rar (6.7 MB)
  • 下载次数: 1551
  • 大小: 5.4 KB
  • 大小: 10.1 KB

java操作pdf itext入门相关推荐

  1. Java操作PDF之iText超入门

    转自:https://www.cnblogs.com/liaojie970/p/7132475.html Java操作PDF之iText超入门 iText是著名的开放项目,是用于生成PDF文档的一个j ...

  2. 【Java 代码实例 13】Java操作pdf的工具类itext

    目录 一.什么是iText? 二.引入jar 1.项目要使用iText,必须引入jar包 2.输出中文,还要引入下面```itext-asian.jar```包 3.设置pdf文件密码,还要引入下面` ...

  3. JAVA操作pdf——创建表格

    JAVA操作pdf--创建表格 一.前言 在实习的时候遇到了需要将查询到的数据构建成为PDF的情况,于是在网上查找到了相关的Java操作pdf的教程,看到大部分的文章都是使用ITextPdf操作的,于 ...

  4. java 操作 PDF

    近来收到一个需求, 制作 PDF 制作发票. 类似于制作这样的发票 技术选型我选择java 在网上寻找了一些操作PDF的框架决定用iText制作, 因为它比较活跃, 而且后期做签章和插入图片二维码都有 ...

  5. java操作pdf制作电子签章

    #java操作pdf制作电子签章 ##电子签章简介 电子签章,与我们所使用的数字证书一样,是用来做为身份验证的一种手段,泛指所有以电子形式存在,依附在电子文件并与其逻辑关联,可用以辨识电子文件签署者身 ...

  6. java操作PDF文件,可支持分页、合并、图片转PDF等

    java操作PDF,有一个很好用的工具--pdfbox.只需要引入依赖,即可使用. <dependency><groupId>org.apache.pdfbox</gro ...

  7. Java操作PDF大全

    PDF预览 /*** pdf文件预览* @param request* @param response* @return* @throws IOException*/ @RequestMapping( ...

  8. java操作PDF实现简单盖章功能(未签字)

    最近有一个电子签章的功能需求,网上相关的资料比较少,我查阅了相关资料,做了一个简单的盖章功能的demo 首先需要导个依赖,这里选用的是itextpdf来操作pdf <dependencies&g ...

  9. java在模板图片中填写文字,java 操作pdf模板(向指定域添加文本内容和图片)

    项目需求涉及到操作pdf模板,根据生成好的模板向里面填充数据 用到的jar包是iText-5.0.6.jar 和iTextAsian.jar 上代码: public static void main( ...

最新文章

  1. 美团提出基于隐式条件位置编码的Transformer,性能优于ViT和DeiT
  2. DymSLAM: 基于几何和运动分割的4D动态场景重建( RAL)
  3. 稳定直播服务器主板,云直播服务器
  4. C# 文件操作详解(三)---------Directory类
  5. Description Resource Path Location Type Java compiler level does not match the version of the insta
  6. MySQL删除重复数据保留1条
  7. orchard文档之-搜索和索引
  8. Charles破解安装
  9. Mac应用程序无法打开提示不明开发者?别着急看这里
  10. conda安装包时提示当前用户没有权限
  11. Unity Json 编写及读取
  12. 【方法】Latex使用BibTeX生成参考文献列表
  13. GitHub 小白入门
  14. 李昀飞:兴业数金金融行业云 中小银行转型重要引擎
  15. JavaScript 页面资源加载:onload,onerror
  16. flume+kafka+storm整合02---问题
  17. 维克森林大学计算机专业,维克森林大学计算机专业
  18. 自适应遗忘因子/带遗忘因子最小二乘锂电池二阶RC电路等效模型参数识别
  19. 什么是WHQL微软徽标认证?为什么需要这项认证?
  20. 使用js、php制作99乘法表

热门文章

  1. linux第三方串口,[原创]Linux下的第三方登录认证实现
  2. php+yii框架,yii框架源码分析(一)
  3. python如何创建txt_python创建txt文件
  4. java注册提示,java提示注册成功代码
  5. cocos2d-x支持c++、js、lua开发
  6. 记一次vue项目打包优化
  7. W2k8应用vista主题
  8. matplotlib 笔记:修改xlabel,ylabel 字体
  9. PPt插入视频同时播放
  10. 联通将推自有品牌手机“沃Phone” -- 中国人就继续无知的雷到死吧...