Java操作PDF之iText超入门

2 篇文章 0 订阅
2 篇文章 0 订阅

Java操作PDF之iText超入门

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

1、生成一个PDF
 
01//Step 1—Create a Document.
02Document document = newDocument();
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(newParagraph("Hello World"));
09//Step 5—Close the Document.
10document.close();


2、页面大小,页面背景色,页边空白,Title,Author,Subject,Keywords
 
01//页面大小
02Rectangle rect = newRectangle(PageSize.B5.rotate());
03//页面背景色
04rect.setBackgroundColor(BaseColor.ORANGE);
05  
06Document doc = newDocument(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(newParagraph("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(newParagraph("Hello World"));

d2.gif

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


5、添加水印(背景图)
 
01//图片水印
02PdfReader reader = newPdfReader(FILE_DIR + "setWatermark.pdf");
03PdfStamper stamp = newPdfStamper(reader, newFileOutputStream(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(newChunk("China"));
03document.add(newChunk(" "));
04Font font = newFont(Font.FontFamily.HELVETICA, 6, Font.BOLD, BaseColor.WHITE);
05Chunk id = newChunk("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(newChunk("Japan"));
12document.add(newChunk(" "));
13Font font2 = newFont(Font.FontFamily.HELVETICA, 6, Font.BOLD, BaseColor.WHITE);
14Chunk id2 = newChunk("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(newPhrase("Phrase page"));
24  
25Phrase director = newPhrase();
26Chunk name = newChunk("China");
27name.setUnderline(0.2f, -2f);
28director.add(name);
29director.add(newChunk(","));
30director.add(newChunk(" "));
31director.add(newChunk("chinese"));
32director.setLeading(24);
33document.add(director);
34  
35Phrase director2 = newPhrase();
36Chunk name2 = newChunk("Japan");
37name2.setUnderline(0.2f, -2f);
38director2.add(name2);
39director2.add(newChunk(","));
40director2.add(newChunk(" "));
41director2.add(newChunk("japanese"));
42director2.setLeading(24);
43document.add(director2);
44          
45//Paragraph对象: a Phrase with extra properties and a newline
46document.newPage();
47document.add(newParagraph("Paragraph page"));
48  
49Paragraph info = newParagraph();
50info.add(newChunk("China "));
51info.add(newChunk("chinese"));
52info.add(Chunk.NEWLINE);
53info.add(newPhrase("Japan "));
54info.add(newPhrase("japanese"));
55document.add(info);
56  
57//List对象: a sequence of Paragraphs called ListItem
58document.newPage();
59List list = newList(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 = newParagraph();
03Anchor dest = newAnchor("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 = newAnchor("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 = newParagraph("Title");
29Chapter chapter = newChapter(title, 1);
30  
31title = newParagraph("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(newParagraph("Sub Section A"));
40subsection.setIndentationLeft(20);
41subsection.setNumberDepth(1);
42  
43document.add(chapter);


8、画图
 
01//左右箭头
02document.add(newVerticalPositionMark() {
03  
04    publicvoid draw(PdfContentByte canvas,float llx, float lly,
05            floaturx, 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 = newParagraph("LEFT");
26p1.add(newChunk(new LineSeparator()));
27p1.add("R");
28document.add(p1);
29//点线
30Paragraph p2 = newParagraph("LEFT");
31p2.add(newChunk(new DottedLineSeparator()));
32p2.add("R");
33document.add(p2);
34//下滑线
35LineSeparator UNDERLINE = newLineSeparator(1,100, null, Element.ALIGN_CENTER, -2);
36Paragraph p3 = newParagraph("NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN");
37p3.add(UNDERLINE);
38document.add(p3);

d3.gif

9、设置段落
 
01Paragraph p = newParagraph("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 = newFileOutputStream(FILE_DIR + "deletePage.pdf");
02  
03Document document = newDocument();
04  
05PdfWriter writer = PdfWriter.getInstance(document, out);
06  
07document.open();
08document.add(newParagraph("First page"));
09document.add(newParagraph(Document.getVersion()));
10  
11document.newPage();
12writer.setPageEmpty(false);
13  
14document.newPage();
15document.add(newParagraph("New page"));
16  
17document.close();
18  
19PdfReader reader = newPdfReader(FILE_DIR + "deletePage.pdf");
20reader.selectPages("1,3");
21PdfStamper stamp = newPdfStamper(reader, newFileOutputStream(FILE_DIR
22        +"deletePage2.pdf"));
23stamp.close();
24reader.close();


11、插入Page
 
01FileOutputStream out = newFileOutputStream(FILE_DIR + "insertPage.pdf");
02  
03Document document = newDocument();
04  
05PdfWriter.getInstance(document, out);
06  
07document.open();
08document.add(newParagraph("1 page"));
09  
10document.newPage();
11document.add(newParagraph("2 page"));
12  
13document.newPage();
14document.add(newParagraph("3 page"));
15  
16document.close();
17  
18PdfReader reader = newPdfReader(FILE_DIR + "insertPage.pdf");
19PdfStamper stamp = newPdfStamper(reader, newFileOutputStream(FILE_DIR
20        +"insertPage2.pdf"));
21  
22stamp.insertPage(2, reader.getPageSize(1));
23  
24ColumnText ct = newColumnText(null);
25ct.addElement(newParagraph(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(newParagraph("1 page"));
06doc.newPage();
07doc.add(newParagraph("2 page"));
08doc.newPage();
09doc.add(newParagraph("3 page"));
10doc.newPage();
11doc.add(newParagraph("4 page"));
12doc.newPage();
13doc.add(newParagraph("5 page"));
14  
15int[] order = {4,3,2,1};
16writer.reorderPages(order);


13、目录
 
01// Code 1
02document.add(newChunk("Chapter 1").setLocalDestination("1"));
03  
04document.newPage();
05document.add(newChunk("Chapter 2").setLocalDestination("2"));
06document.add(newParagraph(new Chunk("Sub 2.1").setLocalDestination("2.1")));
07document.add(newParagraph(new Chunk("Sub 2.2").setLocalDestination("2.2")));
08  
09document.newPage();
10document.add(newChunk("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 = newPdfOutline(root, PdfAction.gotoLocalPage("1",false), "Chapter 1");
19  
20PdfOutline oline2 = newPdfOutline(root, PdfAction.gotoLocalPage("2",false), "Chapter 2");
21oline2.setOpen(false);
22  
23@SuppressWarnings("unused")
24PdfOutline oline2_1 = newPdfOutline(oline2, PdfAction.gotoLocalPage("2.1",false), "Sub 2.1");
25@SuppressWarnings("unused")
26PdfOutline oline2_2 = newPdfOutline(oline2, PdfAction.gotoLocalPage("2.2",false), "Sub 2.2");
27  
28@SuppressWarnings("unused")
29PdfOutline oline3 = newPdfOutline(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(newPdfPageEventHelper() {
04  
05    publicvoid 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        floatx = 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        floaty = 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(newParagraph("1 page"));        
61doc.newPage();
62doc.add(newParagraph("2 page"));        
63doc.newPage();
64doc.add(newParagraph("3 page"));        
65doc.newPage();
66doc.add(newParagraph("4 page"));


15、左右文字
 
01PdfWriter writer = PdfWriter.getInstance(document, out);
02  
03document.open();
04  
05PdfContentByte canvas = writer.getDirectContent();
06  
07Phrase phrase1 = newPhrase("This is a test!left");
08Phrase phrase2 = newPhrase("This is a test!right");
09Phrase phrase3 = newPhrase("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(newPdfPageEventHelper() {
07    publicvoid onStartPage(PdfWriter writer, Document document) {
08        writer.setTransition(newPdfTransition(PdfTransition.DISSOLVE, 3));
09        writer.setDuration(5);//间隔时间
10    }
11});
12  
13doc.open();
14doc.add(newParagraph("1 page"));
15doc.newPage();
16doc.add(newParagraph("2 page"));
17doc.newPage();
18doc.add(newParagraph("3 page"));
19doc.newPage();
20doc.add(newParagraph("4 page"));
21doc.newPage();
22doc.add(newParagraph("5 page"));


17、压缩PDF到Zip
 
01ZipOutputStream zip = newZipOutputStream(newFileOutputStream(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(newParagraph("Hello "+ i));
10    document.close();
11    zip.closeEntry();
12}
13zip.close();

d5.gif

18、分割PDF
 
01FileOutputStream out = newFileOutputStream(FILE_DIR + "splitPDF.pdf");
02  
03Document document = newDocument();
04  
05PdfWriter.getInstance(document, out);
06  
07document.open();
08document.add(newParagraph("1 page"));
09  
10document.newPage();
11document.add(newParagraph("2 page"));
12  
13document.newPage();
14document.add(newParagraph("3 page"));
15  
16document.newPage();
17document.add(newParagraph("4 page"));
18  
19document.close();
20  
21PdfReader reader = newPdfReader(FILE_DIR + "splitPDF.pdf");
22  
23Document dd = newDocument();
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 = newDocument();
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 = newPdfReader(FILE_DIR + "splitPDF1.pdf");
02PdfReader reader2 = newPdfReader(FILE_DIR + "splitPDF2.pdf");
03  
04FileOutputStream out = newFileOutputStream(FILE_DIR + "mergePDF.pdf");
05  
06Document document = newDocument();
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(newParagraph("1 page"));
06doc.add(newAnnotation("Title","This is a annotation!"));
07  
08doc.newPage();
09doc.add(newParagraph("2 page"));
10Chunk chunk = newChunk("\u00a0");
11chunk.setAnnotation(PdfAnnotation.createText(writer,null, "Title","This is a another annotation!",false, "Comment"));
12doc.add(chunk);
13  
14//添加附件
15doc.newPage();
16doc.add(newParagraph("3 page"));
17Chunk chunk2 = newChunk("\u00a0\u00a0");
18PdfAnnotation annotation = PdfAnnotation.createFileAttachment(
19        writer,null, "Title",null,
20        "resource/test2.jpg",
21        "img.jpg");
22annotation.put(PdfName.NAME,
23        newPdfString("Paperclip"));
24chunk2.setAnnotation(annotation);
25doc.add(chunk2);

d6.gif

21、插入一个Table
 
01PdfPTable table = newPdfPTable(3);
02PdfPCell cell;
03cell = newPdfPCell(new Phrase("Cell with colspan 3"));
04cell.setColspan(3);
05table.addCell(cell);
06cell = newPdfPCell(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 = newPdfPTable(4);
02  
03//1行2列
04PdfPTable nested1 = newPdfPTable(2);
05nested1.addCell("1.1");
06nested1.addCell("1.2");
07  
08//2行1列
09PdfPTable nested2 = newPdfPTable(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 = newPdfPTable(3);
02PdfPCell cell;
03cell = newPdfPCell(new Phrase("Cell with colspan 3"));
04cell.setColspan(3);
05table.addCell(cell);
06cell = newPdfPCell(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(newParagraph("\n\n"));
18  
19//宽度50% 居左
20table.setHorizontalAlignment(Element.ALIGN_LEFT);
21document.add(table);
22document.add(newParagraph("\n\n"));
23  
24//宽度50% 居中
25table.setHorizontalAlignment(Element.ALIGN_CENTER);
26document.add(table);
27document.add(newParagraph("\n\n"));
28  
29//宽度50% 居右
30table.setWidthPercentage(50);
31table.setHorizontalAlignment(Element.ALIGN_RIGHT);
32document.add(table);
33document.add(newParagraph("\n\n"));
34  
35//固定宽度
36table.setTotalWidth(300);
37table.setLockedWidth(true);
38document.add(table);


24、设置表格前后间隔
 
01PdfPTable table = newPdfPTable(3);
02PdfPCell cell = newPdfPCell(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 = newPdfPCell(new Paragraph("红色边框",fontZH));
13cell.setBorderColor(newBaseColor(255,0, 0));
14table.addCell(cell);
15  
16cell = newPdfPCell(new Paragraph("合并单2个元格",fontZH));
17cell.setColspan(2);
18cell.setBackgroundColor(newBaseColor(0xC0,0xC0, 0xC0));
19table.addCell(cell);
20  
21table.setWidthPercentage(50);
22  
23document.add(newParagraph("追加2个表格",fontZH));
24document.add(table);
25document.add(table);
26  
27document.newPage();
28document.add(newParagraph("使用'SpacingBefore'和'setSpacingAfter'",fontZH));
29table.setSpacingBefore(15f);
30document.add(table);
31document.add(table);
32document.add(newParagraph("这里没有间隔",fontZH));
33table.setSpacingAfter(15f);


25、设置单元格宽度
 
01//按比例设置单元格宽度
02float[] widths = {0.1f,0.1f, 0.05f,0.75f};
03PdfPTable table = newPdfPTable(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(newParagraph("\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 = newRectangle(PageSize.A4.getRight(72), PageSize.A4.getTop(72));
37table.setWidthPercentage(widths, r);
38document.add(newParagraph("\n\n"));
39document.add(table);


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


27、设置单元格颜色
 
01PdfPTable table = newPdfPTable(4);
02PdfPCell cell;
03cell = newPdfPCell(new Paragraph("颜色测试",fontZH));
04table.addCell(cell);
05  
06//红色背景,无边框
07cell = newPdfPCell(new Paragraph("红色背景,无边框",fontZH));
08cell.setBorder(Rectangle.NO_BORDER);
09cell.setBackgroundColor(BaseColor.RED);
10table.addCell(cell);
11  
12//绿色背景,下边框
13cell = newPdfPCell(new Paragraph("绿色背景,下边框",fontZH));
14cell.setBorder(Rectangle.BOTTOM);
15cell.setBorderColorBottom(BaseColor.MAGENTA);
16cell.setBorderWidthBottom(5f);
17cell.setBackgroundColor(BaseColor.GREEN);
18table.addCell(cell);
19  
20//蓝色背景,上边框
21cell = newPdfPCell(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 = newPdfPCell(new Paragraph("背景灰色度",fontZH));
30table.addCell(cell);
31cell = newPdfPCell(new Paragraph("0.25"));
32cell.setBorder(Rectangle.NO_BORDER);
33cell.setGrayFill(0.25f);
34table.addCell(cell);
35cell = newPdfPCell(new Paragraph("0.5"));
36cell.setBorder(Rectangle.NO_BORDER);
37cell.setGrayFill(0.5f);
38table.addCell(cell);
39cell = newPdfPCell(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 = newPdfPTable(widths);
05  
06//插入图片
07table.addCell(newPdfPCell(new Paragraph("图片测试", fontZH)));
08table.addCell(image);
09  
10//调整图片大小
11table.addCell("This two");
12table.addCell(newPdfPCell(image, true));
13  
14//不调整
15table.addCell("This three");
16table.addCell(newPdfPCell(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 = newPdfPTable(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 = newPdfPTable(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 = newPdfPTable(2);
02PdfPCell cell;
03Paragraph p = newParagraph("Quick brown fox jumps over the lazy dog. Quick brown fox jumps over the lazy dog.");
04table.addCell(newPdfPCell(new Paragraph("默认",fontZH)));
05table.addCell(p);
06table.addCell(newPdfPCell(new Paragraph("Padding:10",fontZH)));
07cell = newPdfPCell(p);
08cell.setPadding(10f);
09table.addCell(cell);
10table.addCell(newPdfPCell(new Paragraph("Padding:0",fontZH)));
11cell = newPdfPCell(p);
12cell.setPadding(0f);
13table.addCell(cell);
14table.addCell(newPdfPCell(new Paragraph("上Padding:0 左Padding:20",fontZH)));
15cell = newPdfPCell(p);
16cell.setPaddingTop(0f);
17cell.setPaddingLeft(20f);
18table.addCell(cell);
19document.add(table);
20  
21document.newPage();
22table = newPdfPTable(2);
23table.addCell(newPdfPCell(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(newPdfPCell(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(newPdfPCell(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 = newPdfPTable(3);  
03table1.getDefaultCell().setBorder(PdfPCell.NO_BORDER);  
04table1.addCell(newParagraph("Cell 1")); 
05table1.addCell(newParagraph("Cell 2")); 
06table1.addCell(newParagraph("Cell 3")); 
07document.add(table1);
08  
09//边框粗细颜色
10document.newPage();
11Rectangle b1 = newRectangle(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 = newPdfPTable(1);
21PdfPCell cell =  newPdfPCell(new Paragraph("Cell 1"));
22cell.cloneNonPositionParameters(b1);
23table2.addCell(cell);
24document.add(table2);


转自:http://rensanning.iteye.com/blog/1538689
  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值