Java操作PDF之iText超入门

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

http://itextpdf.com/

版本:itextpdf-5.2.1.jar

1、生成一个PDF
01//Step 1—Create a Document.
02Document document = new Document();
03//Step 2—Get a PdfWriter instance.
04PdfWriter.getInstance(document, new FileOutputStream(FILE_DIR + "createSamplePDF.pdf"));
05//Step 3—Open the Document.
06document.open();
07//Step 4—Add content.
08document.add(new Paragraph("Hello World"));
09//Step 5—Close the Document.
10document.close();


2、页面大小,页面背景色,页边空白,Title,Author,Subject,Keywords
01//页面大小
02Rectangle rect = new Rectangle(PageSize.B5.rotate());
03//页面背景色
04rect.setBackgroundColor(BaseColor.ORANGE);
05 
06Document doc = new Document(rect);
07 
08PdfWriter writer = PdfWriter.getInstance(doc, out);
09 
10//PDF版本(默认1.4)
11writer.setPdfVersion(PdfWriter.PDF_VERSION_1_2);
12 
13//文档属性
14doc.addTitle("Title@sample");
15doc.addAuthor("Author@rensanning");
16doc.addSubject("Subject@iText sample");
17doc.addKeywords("Keywords@iText");
18doc.addCreator("Creator@iText");
19 
20//页边空白
21doc.setMargins(10, 20, 30, 40);
22 
23doc.open();
24doc.add(new Paragraph("Hello World"));

d1.gif

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

d2.gif

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


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


6、插入Chunk, Phrase, Paragraph, List
01//Chunk对象: a String, a Font, and some attributes
02document.add(new Chunk("China"));
03document.add(new Chunk(" "));
04Font font = new Font(Font.FontFamily.HELVETICA, 6, Font.BOLD, BaseColor.WHITE);
05Chunk id = new Chunk("chinese", font);
06id.setBackground(BaseColor.BLACK, 1f, 0.5f, 1f, 1.5f);
07id.setTextRise(6);
08document.add(id);
09document.add(Chunk.NEWLINE);
10 
11document.add(new Chunk("Japan"));
12document.add(new Chunk(" "));
13Font font2 = new Font(Font.FontFamily.HELVETICA, 6, Font.BOLD, BaseColor.WHITE);
14Chunk id2 = new Chunk("japanese", font2);
15id2.setBackground(BaseColor.BLACK, 1f, 0.5f, 1f, 1.5f);
16id2.setTextRise(6);
17id2.setUnderline(0.2f, -2f);
18document.add(id2);
19document.add(Chunk.NEWLINE);
20 
21//Phrase对象: a List of Chunks with leading
22document.newPage();
23document.add(new Phrase("Phrase page"));
24 
25Phrase director = new Phrase();
26Chunk name = new Chunk("China");
27name.setUnderline(0.2f, -2f);
28director.add(name);
29director.add(new Chunk(","));
30director.add(new Chunk(" "));
31director.add(new Chunk("chinese"));
32director.setLeading(24);
33document.add(director);
34 
35Phrase director2 = new Phrase();
36Chunk name2 = new Chunk("Japan");
37name2.setUnderline(0.2f, -2f);
38director2.add(name2);
39director2.add(new Chunk(","));
40director2.add(new Chunk(" "));
41director2.add(new Chunk("japanese"));
42director2.setLeading(24);
43document.add(director2);
44       
45//Paragraph对象: a Phrase with extra properties and a newline
46document.newPage();
47document.add(new Paragraph("Paragraph page"));
48 
49Paragraph info = new Paragraph();
50info.add(new Chunk("China "));
51info.add(new Chunk("chinese"));
52info.add(Chunk.NEWLINE);
53info.add(new Phrase("Japan "));
54info.add(new Phrase("japanese"));
55document.add(info);
56 
57//List对象: a sequence of Paragraphs called ListItem
58document.newPage();
59List list = new List(List.ORDERED);
60for (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}
79document.add(list);


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


8、画图
01//左右箭头
02document.add(new VerticalPositionMark() {
03 
04    public void draw(PdfContentByte canvas, float llx, float lly,
05            float urx, float ury, float y) {
06        canvas.beginText();
07        BaseFont bf = null;
08        try {
09            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((char) 220), llx - 10, y, 0);
17        // RIGHT
18        canvas.showTextAligned(Element.ALIGN_CENTER, String.valueOf((char) 220), urx + 10, y + 8, 180);
19       
20        canvas.endText();
21    }
22});
23 
24//直线
25Paragraph p1 = new Paragraph("LEFT");
26p1.add(new Chunk(new LineSeparator()));
27p1.add("R");
28document.add(p1);
29//点线
30Paragraph p2 = new Paragraph("LEFT");
31p2.add(new Chunk(new DottedLineSeparator()));
32p2.add("R");
33document.add(p2);
34//下滑线
35LineSeparator UNDERLINE = new LineSeparator(1, 100, null, Element.ALIGN_CENTER, -2);
36Paragraph p3 = new Paragraph("NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN");
37p3.add(UNDERLINE);
38document.add(p3);

d3.gif

9、设置段落
01Paragraph 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.");
02 
03//默认
04p.setAlignment(Element.ALIGN_JUSTIFIED);
05document.add(p);
06 
07document.newPage();
08p.setAlignment(Element.ALIGN_JUSTIFIED);
09p.setIndentationLeft(1 * 15f);
10p.setIndentationRight((5 - 1) * 15f);
11document.add(p);
12 
13//居右
14document.newPage();
15p.setAlignment(Element.ALIGN_RIGHT);
16p.setSpacingAfter(15f);
17document.add(p);
18 
19//居左
20document.newPage();
21p.setAlignment(Element.ALIGN_LEFT);
22p.setSpacingBefore(15f);
23document.add(p);
24 
25//居中
26document.newPage();
27p.setAlignment(Element.ALIGN_CENTER);
28p.setSpacingAfter(15f);
29p.setSpacingBefore(15f);
30document.add(p);


10、删除Page
01FileOutputStream out = new FileOutputStream(FILE_DIR + "deletePage.pdf");
02 
03Document document = new Document();
04 
05PdfWriter writer = PdfWriter.getInstance(document, out);
06 
07document.open();
08document.add(new Paragraph("First page"));
09document.add(new Paragraph(Document.getVersion()));
10 
11document.newPage();
12writer.setPageEmpty(false);
13 
14document.newPage();
15document.add(new Paragraph("New page"));
16 
17document.close();
18 
19PdfReader reader = new PdfReader(FILE_DIR + "deletePage.pdf");
20reader.selectPages("1,3");
21PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(FILE_DIR
22        + "deletePage2.pdf"));
23stamp.close();
24reader.close();


11、插入Page
01FileOutputStream out = new FileOutputStream(FILE_DIR + "insertPage.pdf");
02 
03Document document = new Document();
04 
05PdfWriter.getInstance(document, out);
06 
07document.open();
08document.add(new Paragraph("1 page"));
09 
10document.newPage();
11document.add(new Paragraph("2 page"));
12 
13document.newPage();
14document.add(new Paragraph("3 page"));
15 
16document.close();
17 
18PdfReader reader = new PdfReader(FILE_DIR + "insertPage.pdf");
19PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(FILE_DIR
20        + "insertPage2.pdf"));
21 
22stamp.insertPage(2, reader.getPageSize(1));
23 
24ColumnText ct = new ColumnText(null);
25ct.addElement(new Paragraph(24, new Chunk("INSERT PAGE")));
26ct.setCanvas(stamp.getOverContent(2));
27ct.setSimpleColumn(36, 36, 559, 770);
28 
29stamp.close();
30reader.close();


12、排序page
01PdfWriter writer = PdfWriter.getInstance(doc, out);
02writer.setLinearPageMode();
03 
04doc.open();
05doc.add(new Paragraph("1 page"));
06doc.newPage();
07doc.add(new Paragraph("2 page"));
08doc.newPage();
09doc.add(new Paragraph("3 page"));
10doc.newPage();
11doc.add(new Paragraph("4 page"));
12doc.newPage();
13doc.add(new Paragraph("5 page"));
14 
15int[] order = {4,3,2,1};
16writer.reorderPages(order);


13、目录
01// Code 1
02document.add(new Chunk("Chapter 1").setLocalDestination("1"));
03 
04document.newPage();
05document.add(new Chunk("Chapter 2").setLocalDestination("2"));
06document.add(new Paragraph(new Chunk("Sub 2.1").setLocalDestination("2.1")));
07document.add(new Paragraph(new Chunk("Sub 2.2").setLocalDestination("2.2")));
08 
09document.newPage();
10document.add(new Chunk("Chapter 3").setLocalDestination("3"));
11 
12// Code 2
13PdfContentByte cb = writer.getDirectContent();
14PdfOutline root = cb.getRootOutline();
15 
16// Code 3
17@SuppressWarnings("unused")
18PdfOutline oline1 = new PdfOutline(root, PdfAction.gotoLocalPage("1", false), "Chapter 1");
19 
20PdfOutline oline2 = new PdfOutline(root, PdfAction.gotoLocalPage("2", false), "Chapter 2");
21oline2.setOpen(false);
22 
23@SuppressWarnings("unused")
24PdfOutline oline2_1 = new PdfOutline(oline2, PdfAction.gotoLocalPage("2.1", false), "Sub 2.1");
25@SuppressWarnings("unused")
26PdfOutline oline2_2 = new PdfOutline(oline2, PdfAction.gotoLocalPage("2.2", false), "Sub 2.2");
27 
28@SuppressWarnings("unused")
29PdfOutline oline3 = new PdfOutline(root, PdfAction.gotoLocalPage("3", false), "Chapter 3");

d4.gif

14、Header, Footer
01PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(FILE_DIR + "setHeaderFooter.pdf"));
02 
03writer.setPageEvent(new PdfPageEventHelper() {
04 
05    public void onEndPage(PdfWriter writer, Document document) {
06       
07        PdfContentByte cb = writer.getDirectContent();
08        cb.saveState();
09 
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 
59doc.open();
60doc.add(new Paragraph("1 page"));       
61doc.newPage();
62doc.add(new Paragraph("2 page"));       
63doc.newPage();
64doc.add(new Paragraph("3 page"));       
65doc.newPage();
66doc.add(new Paragraph("4 page"));


15、左右文字
01PdfWriter writer = PdfWriter.getInstance(document, out);
02 
03document.open();
04 
05PdfContentByte canvas = writer.getDirectContent();
06 
07Phrase phrase1 = new Phrase("This is a test!left");
08Phrase phrase2 = new Phrase("This is a test!right");
09Phrase phrase3 = new Phrase("This is a test!center");
10ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, phrase1, 10, 500, 0);
11ColumnText.showTextAligned(canvas, Element.ALIGN_RIGHT, phrase2, 10, 536, 0);
12ColumnText.showTextAligned(canvas, Element.ALIGN_CENTER, phrase3, 10, 572, 0);


16、幻灯片放映
01PdfWriter writer = PdfWriter.getInstance(doc, out);
02 
03writer.setPdfVersion(PdfWriter.VERSION_1_5);
04 
05writer.setViewerPreferences(PdfWriter.PageModeFullScreen);//全屏
06writer.setPageEvent(new PdfPageEventHelper() {
07    public void onStartPage(PdfWriter writer, Document document) {
08        writer.setTransition(new PdfTransition(PdfTransition.DISSOLVE, 3));
09        writer.setDuration(5);//间隔时间
10    }
11});
12 
13doc.open();
14doc.add(new Paragraph("1 page"));
15doc.newPage();
16doc.add(new Paragraph("2 page"));
17doc.newPage();
18doc.add(new Paragraph("3 page"));
19doc.newPage();
20doc.add(new Paragraph("4 page"));
21doc.newPage();
22doc.add(new Paragraph("5 page"));


17、压缩PDF到Zip
01ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(FILE_DIR + "zipPDF.zip"));
02for (int i = 1; i <= 3; i++) {
03    ZipEntry entry = new ZipEntry("hello_" + i + ".pdf");
04    zip.putNextEntry(entry);
05    Document document = new Document();
06    PdfWriter writer = PdfWriter.getInstance(document, zip);
07    writer.setCloseStream(false);
08    document.open();
09    document.add(new Paragraph("Hello " + i));
10    document.close();
11    zip.closeEntry();
12}
13zip.close();

d5.gif

18、分割PDF
01FileOutputStream out = new FileOutputStream(FILE_DIR + "splitPDF.pdf");
02 
03Document document = new Document();
04 
05PdfWriter.getInstance(document, out);
06 
07document.open();
08document.add(new Paragraph("1 page"));
09 
10document.newPage();
11document.add(new Paragraph("2 page"));
12 
13document.newPage();
14document.add(new Paragraph("3 page"));
15 
16document.newPage();
17document.add(new Paragraph("4 page"));
18 
19document.close();
20 
21PdfReader reader = new PdfReader(FILE_DIR + "splitPDF.pdf");
22 
23Document dd = new Document();
24PdfWriter writer = PdfWriter.getInstance(dd, new FileOutputStream(FILE_DIR + "splitPDF1.pdf"));
25dd.open();
26PdfContentByte cb = writer.getDirectContent();
27dd.newPage();
28cb.addTemplate(writer.getImportedPage(reader, 1), 0, 0);
29dd.newPage();
30cb.addTemplate(writer.getImportedPage(reader, 2), 0, 0);
31dd.close();
32writer.close();
33 
34Document dd2 = new Document();
35PdfWriter writer2 = PdfWriter.getInstance(dd2, new FileOutputStream(FILE_DIR + "splitPDF2.pdf"));
36dd2.open();
37PdfContentByte cb2 = writer2.getDirectContent();
38dd2.newPage();
39cb2.addTemplate(writer2.getImportedPage(reader, 3), 0, 0);
40dd2.newPage();
41cb2.addTemplate(writer2.getImportedPage(reader, 4), 0, 0);
42dd2.close();
43writer2.close();


19、合并PDF
01PdfReader reader1 = new PdfReader(FILE_DIR + "splitPDF1.pdf");
02PdfReader reader2 = new PdfReader(FILE_DIR + "splitPDF2.pdf");
03 
04FileOutputStream out = new FileOutputStream(FILE_DIR + "mergePDF.pdf");
05 
06Document document = new Document();
07PdfWriter writer = PdfWriter.getInstance(document, out);
08 
09document.open();
10PdfContentByte cb = writer.getDirectContent();
11 
12int totalPages = 0;
13totalPages += reader1.getNumberOfPages();
14totalPages += reader2.getNumberOfPages();
15 
16java.util.List<PdfReader> readers = new ArrayList<PdfReader>();
17readers.add(reader1);
18readers.add(reader2);
19 
20int pageOfCurrentReaderPDF = 0;
21Iterator<PdfReader> iteratorPDFReader = readers.iterator();
22 
23// Loop through the PDF files and add to the output.
24while (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, 0, 0);
33    }
34    pageOfCurrentReaderPDF = 0;
35}
36out.flush();
37document.close();
38out.close();


20、Annotation
01PdfWriter writer = PdfWriter.getInstance(doc, out);
02writer.setLinearPageMode();
03 
04doc.open();
05doc.add(new Paragraph("1 page"));
06doc.add(new Annotation("Title", "This is a annotation!"));
07 
08doc.newPage();
09doc.add(new Paragraph("2 page"));
10Chunk chunk = new Chunk("\u00a0");
11chunk.setAnnotation(PdfAnnotation.createText(writer, null, "Title", "This is a another annotation!", false, "Comment"));
12doc.add(chunk);
13 
14//添加附件
15doc.newPage();
16doc.add(new Paragraph("3 page"));
17Chunk chunk2 = new Chunk("\u00a0\u00a0");
18PdfAnnotation annotation = PdfAnnotation.createFileAttachment(
19        writer, null, "Title", null,
20        "resource/test2.jpg",
21        "img.jpg");
22annotation.put(PdfName.NAME,
23        new PdfString("Paperclip"));
24chunk2.setAnnotation(annotation);
25doc.add(chunk2);

d6.gif

21、插入一个Table
01PdfPTable table = new PdfPTable(3);
02PdfPCell cell;
03cell = new PdfPCell(new Phrase("Cell with colspan 3"));
04cell.setColspan(3);
05table.addCell(cell);
06cell = new PdfPCell(new Phrase("Cell with rowspan 2"));
07cell.setRowspan(2);
08table.addCell(cell);
09table.addCell("row 1; cell 1");
10table.addCell("row 1; cell 2");
11table.addCell("row 2; cell 1");
12table.addCell("row 2; cell 2");
13 
14document.add(table);


22、表格嵌套
01PdfPTable table = new PdfPTable(4);
02 
03//1行2列
04PdfPTable nested1 = new PdfPTable(2);
05nested1.addCell("1.1");
06nested1.addCell("1.2");
07 
08//2行1列
09PdfPTable nested2 = new PdfPTable(1);
10nested2.addCell("2.1");
11nested2.addCell("2.2");
12 
13//将表格插入到指定位置
14for (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 
24document.add(table);


23、设置表格宽度
01PdfPTable table = new PdfPTable(3);
02PdfPCell cell;
03cell = new PdfPCell(new Phrase("Cell with colspan 3"));
04cell.setColspan(3);
05table.addCell(cell);
06cell = new PdfPCell(new Phrase("Cell with rowspan 2"));
07cell.setRowspan(2);
08table.addCell(cell);
09table.addCell("row 1; cell 1");
10table.addCell("row 1; cell 2");
11table.addCell("row 2; cell 1");
12table.addCell("row 2; cell 2");
13 
14//100%
15table.setWidthPercentage(100);
16document.add(table);       
17document.add(new Paragraph("\n\n"));
18 
19//宽度50% 居左
20table.setHorizontalAlignment(Element.ALIGN_LEFT);
21document.add(table);
22document.add(new Paragraph("\n\n"));
23 
24//宽度50% 居中
25table.setHorizontalAlignment(Element.ALIGN_CENTER);
26document.add(table);
27document.add(new Paragraph("\n\n"));
28 
29//宽度50% 居右
30table.setWidthPercentage(50);
31table.setHorizontalAlignment(Element.ALIGN_RIGHT);
32document.add(table);
33document.add(new Paragraph("\n\n"));
34 
35//固定宽度
36table.setTotalWidth(300);
37table.setLockedWidth(true);
38document.add(table);


24、设置表格前后间隔
01PdfPTable table = new PdfPTable(3);
02PdfPCell cell = new PdfPCell(new Paragraph("合并3个单元格",fontZH));
03cell.setColspan(3);
04table.addCell(cell);
05table.addCell("1.1");
06table.addCell("2.1");
07table.addCell("3.1");
08table.addCell("1.2");
09table.addCell("2.2");
10table.addCell("3.2");
11 
12cell = new PdfPCell(new Paragraph("红色边框",fontZH));
13cell.setBorderColor(new BaseColor(255, 0, 0));
14table.addCell(cell);
15 
16cell = new PdfPCell(new Paragraph("合并单2个元格",fontZH));
17cell.setColspan(2);
18cell.setBackgroundColor(new BaseColor(0xC0, 0xC0, 0xC0));
19table.addCell(cell);
20 
21table.setWidthPercentage(50);
22 
23document.add(new Paragraph("追加2个表格",fontZH));
24document.add(table);
25document.add(table);
26 
27document.newPage();
28document.add(new Paragraph("使用'SpacingBefore'和'setSpacingAfter'",fontZH));
29table.setSpacingBefore(15f);
30document.add(table);
31document.add(table);
32document.add(new Paragraph("这里没有间隔",fontZH));
33table.setSpacingAfter(15f);


25、设置单元格宽度
01//按比例设置单元格宽度
02float[] widths = {0.1f, 0.1f, 0.05f, 0.75f};
03PdfPTable table = new PdfPTable(widths);
04table.addCell("10%");
05table.addCell("10%");
06table.addCell("5%");
07table.addCell("75%");
08table.addCell("aa");
09table.addCell("aa");
10table.addCell("a");
11table.addCell("aaaaaaaaaaaaaaa");
12table.addCell("bb");
13table.addCell("bb");
14table.addCell("b");
15table.addCell("bbbbbbbbbbbbbbb");
16table.addCell("cc");
17table.addCell("cc");
18table.addCell("c");
19table.addCell("ccccccccccccccc");
20document.add(table);
21document.add(new Paragraph("\n\n"));
22 
23//调整比例
24widths[0] = 20f;
25widths[1] = 20f;
26widths[2] = 10f;
27widths[3] = 50f;
28table.setWidths(widths);
29document.add(table);
30 
31//按绝对值设置单元格宽度
32widths[0] = 40f;
33widths[1] = 40f;
34widths[2] = 20f;
35widths[3] = 300f;
36Rectangle r = new Rectangle(PageSize.A4.getRight(72), PageSize.A4.getTop(72));
37table.setWidthPercentage(widths, r);
38document.add(new Paragraph("\n\n"));
39document.add(table);


26、设置单元格高度
01PdfPTable table = new PdfPTable(2);
02 
03PdfPCell cell;
04 
05//折行
06table.addCell(new PdfPCell(new Paragraph("折行", fontZH)));
07cell = new PdfPCell(new Paragraph("blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah"));
08cell.setNoWrap(false);
09table.addCell(cell);
10 
11//不折行
12table.addCell(new PdfPCell(new Paragraph("不折行", fontZH)));
13cell.setNoWrap(true);
14table.addCell(cell);
15 
16//设置高度
17table.addCell(new PdfPCell(new Paragraph("任意高度",fontZH)));
18cell = 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"));
19table.addCell(cell);
20 
21//固定高度
22table.addCell(new PdfPCell(new Paragraph("固定高度",fontZH)));
23cell.setFixedHeight(50f);
24table.addCell(cell);
25 
26//最小高度
27table.addCell(new PdfPCell(new Paragraph("最小高度",fontZH)));
28cell = new PdfPCell(new Paragraph("最小高度:50",fontZH));
29cell.setMinimumHeight(50f);
30table.addCell(cell);
31 
32//最后一行拉长到page底部
33table.setExtendLastRow(true);
34table.addCell(new PdfPCell(new Paragraph("拉长最后一行",fontZH)));
35cell = new PdfPCell(new Paragraph("最后一行拉长到page底部",fontZH));
36table.addCell(cell);
37 
38document.add(table);


27、设置单元格颜色
01PdfPTable table = new PdfPTable(4);
02PdfPCell cell;
03cell = new PdfPCell(new Paragraph("颜色测试",fontZH));
04table.addCell(cell);
05 
06//红色背景,无边框
07cell = new PdfPCell(new Paragraph("红色背景,无边框",fontZH));
08cell.setBorder(Rectangle.NO_BORDER);
09cell.setBackgroundColor(BaseColor.RED);
10table.addCell(cell);
11 
12//绿色背景,下边框
13cell = new PdfPCell(new Paragraph("绿色背景,下边框",fontZH));
14cell.setBorder(Rectangle.BOTTOM);
15cell.setBorderColorBottom(BaseColor.MAGENTA);
16cell.setBorderWidthBottom(5f);
17cell.setBackgroundColor(BaseColor.GREEN);
18table.addCell(cell);
19 
20//蓝色背景,上边框
21cell = new PdfPCell(new Paragraph("蓝色背景,上边框",fontZH));
22cell.setBorder(Rectangle.TOP);
23cell.setUseBorderPadding(true);
24cell.setBorderWidthTop(5f);
25cell.setBorderColorTop(BaseColor.CYAN);
26cell.setBackgroundColor(BaseColor.BLUE);
27table.addCell(cell);
28 
29cell = new PdfPCell(new Paragraph("背景灰色度",fontZH));
30table.addCell(cell);
31cell = new PdfPCell(new Paragraph("0.25"));
32cell.setBorder(Rectangle.NO_BORDER);
33cell.setGrayFill(0.25f);
34table.addCell(cell);
35cell = new PdfPCell(new Paragraph("0.5"));
36cell.setBorder(Rectangle.NO_BORDER);
37cell.setGrayFill(0.5f);
38table.addCell(cell);
39cell = new PdfPCell(new Paragraph("0.75"));
40cell.setBorder(Rectangle.NO_BORDER);
41cell.setGrayFill(0.75f);
42table.addCell(cell);
43 
44document.add(table);


28、插入图像
01Image image = Image.getInstance("resource/test2.jpg");
02float[] widths = { 1f, 4f };
03 
04PdfPTable table = new PdfPTable(widths);
05 
06//插入图片
07table.addCell(new PdfPCell(new Paragraph("图片测试", fontZH)));
08table.addCell(image);
09 
10//调整图片大小
11table.addCell("This two");
12table.addCell(new PdfPCell(image, true));
13 
14//不调整
15table.addCell("This three");
16table.addCell(new PdfPCell(image, false));
17document.add(table);


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


30、分割表格
01//横向分割
02PdfContentByte cb = writer.getDirectContent();
03PdfPTable table = new PdfPTable(10);
04for (int k = 1; k <= 100; ++k) {
05    table.addCell("The number " + k);
06}
07table.setTotalWidth(400);
08 
09table.writeSelectedRows(0, 5, 0, -1, 5, 700, cb);
10table.writeSelectedRows(5, -1, 0, -1, 210, 700, cb);


31、设置单元格留白
01PdfPTable table = new PdfPTable(2);
02PdfPCell cell;
03Paragraph p = new Paragraph("Quick brown fox jumps over the lazy dog. Quick brown fox jumps over the lazy dog.");
04table.addCell(new PdfPCell(new Paragraph("默认",fontZH)));
05table.addCell(p);
06table.addCell(new PdfPCell(new Paragraph("Padding:10",fontZH)));
07cell = new PdfPCell(p);
08cell.setPadding(10f);
09table.addCell(cell);
10table.addCell(new PdfPCell(new Paragraph("Padding:0",fontZH)));
11cell = new PdfPCell(p);
12cell.setPadding(0f);
13table.addCell(cell);
14table.addCell(new PdfPCell(new Paragraph("上Padding:0 左Padding:20",fontZH)));
15cell = new PdfPCell(p);
16cell.setPaddingTop(0f);
17cell.setPaddingLeft(20f);
18table.addCell(cell);
19document.add(table);
20 
21document.newPage();
22table = new PdfPTable(2);
23table.addCell(new PdfPCell(new Paragraph("没有Leading",fontZH)));
24table.getDefaultCell().setLeading(0f, 0f);
25table.addCell("blah blah\nblah blah blah\nblah blah\nblah blah blah\nblah blah\nblah blah blah\nblah blah\nblah blah blah\n");
26table.getDefaultCell().setLeading(14f, 0f);
27table.addCell(new PdfPCell(new Paragraph("固定Leading:14pt",fontZH)));
28table.addCell("blah blah\nblah blah blah\nblah blah\nblah blah blah\nblah blah\nblah blah blah\nblah blah\nblah blah blah\n");
29table.addCell(new PdfPCell(new Paragraph("相对于字体",fontZH)));
30table.getDefaultCell().setLeading(0f, 1.0f);
31table.addCell("blah blah\nblah blah blah\nblah blah\nblah blah blah\nblah blah\nblah blah blah\nblah blah\nblah blah blah\n");
32document.add(table);


32、设置单元格边框
01//没有边框
02PdfPTable table1 = new PdfPTable(3); 
03table1.getDefaultCell().setBorder(PdfPCell.NO_BORDER); 
04table1.addCell(new Paragraph("Cell 1"));
05table1.addCell(new Paragraph("Cell 2"));
06table1.addCell(new Paragraph("Cell 3"));
07document.add(table1);
08 
09//边框粗细颜色
10document.newPage();
11Rectangle b1 = new Rectangle(0f, 0f);
12b1.setBorderWidthLeft(6f);
13b1.setBorderWidthBottom(5f);
14b1.setBorderWidthRight(4f);
15b1.setBorderWidthTop(2f);
16b1.setBorderColorLeft(BaseColor.RED);
17b1.setBorderColorBottom(BaseColor.ORANGE);
18b1.setBorderColorRight(BaseColor.YELLOW);
19b1.setBorderColorTop(BaseColor.GREEN);
20PdfPTable table2 = new PdfPTable(1);
21PdfPCell cell =  new PdfPCell(new Paragraph("Cell 1"));
22cell.cloneNonPositionParameters(b1);
23table2.addCell(cell);
24document.add(table2);



33、PdfPTableEvent

34、PdfPCellEvent

35、PdfPageEventHelper

http://www.open-open.com/lib/view/open1339726488115.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值