itext生存pdf

iText生成pdf

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

版本: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(); 
//Step 1—Create a Document.
Document document = new Document();
//Step 2—Get a PdfWriter instance.
PdfWriter.getInstance(document, new FileOutputStream(FILE_DIR + "createSamplePDF.pdf"));
//Step 3—Open the Document.
document.open();
//Step 4—Add content.
document.add(new Paragraph("Hello World"));
//Step 5—Close the Document.
document.close();



2、页面大小,页面背景色,页边空白,Title,Author,Subject,Keywords

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

Document doc = new Document(rect);

PdfWriter writer = PdfWriter.getInstance(doc, out);

//PDF版本(默认1.4)
writer.setPdfVersion(PdfWriter.PDF_VERSION_1_2);

//文档属性
doc.addTitle("Title@sample");
doc.addAuthor("Author@rensanning");
doc.addSubject("Subject@iText sample");
doc.addKeywords("Keywords@iText");
doc.addCreator("Creator@iText");

//页边空白
doc.setMargins(10, 20, 30, 40);

doc.open();
doc.add(new Paragraph("Hello World"));




3、设置密码

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

// 设置密码为:"World"
writer.setEncryption("Hello".getBytes(), "World".getBytes(),
		PdfWriter.ALLOW_SCREENREADERS,
		PdfWriter.STANDARD_ENCRYPTION_128);

doc.open();
doc.add(new Paragraph("Hello World"));




4、添加Page

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

document.newPage();
writer.setPageEmpty(false);

document.newPage();
document.add(new Paragraph("New page"));



5、添加水印(背景图)

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

Image img = Image.getInstance("resource/watermark.jpg");
img.setAbsolutePosition(200, 400);
PdfContentByte under = stamp.getUnderContent(1);
under.addImage(img);

//文字水印
PdfContentByte over = stamp.getOverContent(2);
over.beginText();
BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI,
		BaseFont.EMBEDDED);
over.setFontAndSize(bf, 18);
over.setTextMatrix(30, 30);
over.showTextAligned(Element.ALIGN_LEFT, "DUPLICATE", 230, 430, 45);
over.endText();

//背景图
Image img2 = Image.getInstance("resource/test.jpg");
img2.setAbsolutePosition(0, 0);
PdfContentByte under2 = stamp.getUnderContent(3);
under2.addImage(img2);

stamp.close();
reader.close();



6、插入Chunk, Phrase, Paragraph, List

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

document.add(new Chunk("Japan"));
document.add(new Chunk(" "));
Font font2 = new Font(Font.FontFamily.HELVETICA, 6, Font.BOLD, BaseColor.WHITE);
Chunk id2 = new Chunk("japanese", font2);
id2.setBackground(BaseColor.BLACK, 1f, 0.5f, 1f, 1.5f);
id2.setTextRise(6);
id2.setUnderline(0.2f, -2f);
document.add(id2);
document.add(Chunk.NEWLINE);

//Phrase对象: a List of Chunks with leading
document.newPage();
document.add(new Phrase("Phrase page"));

Phrase director = new Phrase();
Chunk name = new Chunk("China");
name.setUnderline(0.2f, -2f);
director.add(name);
director.add(new Chunk(","));
director.add(new Chunk(" "));
director.add(new Chunk("chinese"));
director.setLeading(24);
document.add(director);

Phrase director2 = new Phrase();
Chunk name2 = new Chunk("Japan");
name2.setUnderline(0.2f, -2f);
director2.add(name2);
director2.add(new Chunk(","));
director2.add(new Chunk(" "));
director2.add(new Chunk("japanese"));
director2.setLeading(24);
document.add(director2);
		
//Paragraph对象: a Phrase with extra properties and a newline
document.newPage();
document.add(new Paragraph("Paragraph page"));

Paragraph info = new Paragraph();
info.add(new Chunk("China "));
info.add(new Chunk("chinese"));
info.add(Chunk.NEWLINE);
info.add(new Phrase("Japan "));
info.add(new Phrase("japanese"));
document.add(info);

//List对象: a sequence of Paragraphs called ListItem
document.newPage();
List list = new List(List.ORDERED);
for (int i = 0; i < 10; i++) {
	ListItem item = new ListItem(String.format("%s: %d movies",
			"country" + (i + 1), (i + 1) * 100), new Font(
			Font.FontFamily.HELVETICA, 6, Font.BOLD, BaseColor.WHITE));
	List movielist = new List(List.ORDERED, List.ALPHABETICAL);
	movielist.setLowercase(List.LOWERCASE);
	for (int j = 0; j < 5; j++) {
		ListItem movieitem = new ListItem("Title" + (j + 1));
		List directorlist = new List(List.UNORDERED);
		for (int k = 0; k < 3; k++) {
			directorlist.add(String.format("%s, %s", "Name1" + (k + 1),
					"Name2" + (k + 1)));
		}
		movieitem.add(directorlist);
		movielist.add(movieitem);
	}
	item.add(movielist);
	list.add(item);
}
document.add(list);



7、插入Anchor, Image, Chapter, Section

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

document.newPage();
Anchor toUS = new Anchor("Go to first page.", new Font(Font.FontFamily.HELVETICA, 14, Font.BOLD, BaseColor.BLUE));
toUS.setReference("#CN");//internal
document.add(toUS);

//Image对象
document.newPage();
Image img = Image.getInstance("resource/test.jpg");
img.setAlignment(Image.LEFT | Image.TEXTWRAP);
img.setBorder(Image.BOX);
img.setBorderWidth(10);
img.setBorderColor(BaseColor.WHITE);
img.scaleToFit(1000, 72);//大小
img.setRotationDegrees(-30);//旋转
document.add(img);

//Chapter, Section对象(目录)
document.newPage();
Paragraph title = new Paragraph("Title");
Chapter chapter = new Chapter(title, 1);

title = new Paragraph("Section A");
Section section = chapter.addSection(title);
section.setBookmarkTitle("bmk");
section.setIndentation(30);
section.setBookmarkOpen(false);
section.setNumberStyle(
Section.NUMBERSTYLE_DOTTED_WITHOUT_FINAL_DOT);

Section subsection = section.addSection(new Paragraph("Sub Section A"));
subsection.setIndentationLeft(20);
subsection.setNumberDepth(1);

document.add(chapter);



8、画图

Java代码 复制代码 收藏代码
  1. //左右箭头  
  2. document.add(new VerticalPositionMark() {  
  3.  
  4.     public void draw(PdfContentByte canvas, float llx, float lly,  
  5.             float urx, float ury, float y) {  
  6.         canvas.beginText();  
  7.         BaseFont bf = null;  
  8.         try {  
  9.             bf = BaseFont.createFont(BaseFont.ZAPFDINGBATS, "", BaseFont.EMBEDDED);  
  10.         } catch (Exception e) {  
  11.             e.printStackTrace();  
  12.         }  
  13.         canvas.setFontAndSize(bf, 12);  
  14.           
  15.         // LEFT  
  16.         canvas.showTextAligned(Element.ALIGN_CENTER, String.valueOf((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. //直线  
  25. Paragraph p1 = new Paragraph("LEFT");  
  26. p1.add(new Chunk(new LineSeparator()));  
  27. p1.add("R");  
  28. document.add(p1);  
  29. //点线  
  30. Paragraph p2 = new Paragraph("LEFT");  
  31. p2.add(new Chunk(new DottedLineSeparator()));  
  32. p2.add("R");  
  33. document.add(p2);  
  34. //下滑线  
  35. LineSeparator UNDERLINE = new LineSeparator(1, 100, null, Element.ALIGN_CENTER, -2);  
  36. Paragraph p3 = new Paragraph("NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN");  
  37. p3.add(UNDERLINE);  
  38. document.add(p3); 
//左右箭头
document.add(new VerticalPositionMark() {

	public void draw(PdfContentByte canvas, float llx, float lly,
			float urx, float ury, float y) {
		canvas.beginText();
		BaseFont bf = null;
		try {
			bf = BaseFont.createFont(BaseFont.ZAPFDINGBATS, "", BaseFont.EMBEDDED);
		} catch (Exception e) {
			e.printStackTrace();
		}
		canvas.setFontAndSize(bf, 12);
		
		// LEFT
		canvas.showTextAligned(Element.ALIGN_CENTER, String.valueOf((char) 220), llx - 10, y, 0);
		// RIGHT
		canvas.showTextAligned(Element.ALIGN_CENTER, String.valueOf((char) 220), urx + 10, y + 8, 180);
		
		canvas.endText();
	}
});

//直线
Paragraph p1 = new Paragraph("LEFT");
p1.add(new Chunk(new LineSeparator()));
p1.add("R");
document.add(p1);
//点线
Paragraph p2 = new Paragraph("LEFT");
p2.add(new Chunk(new DottedLineSeparator()));
p2.add("R");
document.add(p2);
//下滑线
LineSeparator UNDERLINE = new LineSeparator(1, 100, null, Element.ALIGN_CENTER, -2);
Paragraph p3 = new Paragraph("NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN");
p3.add(UNDERLINE);
document.add(p3);




9、设置段落

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

//默认
p.setAlignment(Element.ALIGN_JUSTIFIED);
document.add(p);

document.newPage();
p.setAlignment(Element.ALIGN_JUSTIFIED);
p.setIndentationLeft(1 * 15f);
p.setIndentationRight((5 - 1) * 15f);
document.add(p);

//居右
document.newPage();
p.setAlignment(Element.ALIGN_RIGHT);
p.setSpacingAfter(15f);
document.add(p);

//居左
document.newPage();
p.setAlignment(Element.ALIGN_LEFT);
p.setSpacingBefore(15f);
document.add(p);

//居中
document.newPage();
p.setAlignment(Element.ALIGN_CENTER);
p.setSpacingAfter(15f);
p.setSpacingBefore(15f);
document.add(p);



10、删除Page

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

Document document = new Document();

PdfWriter writer = PdfWriter.getInstance(document, out);

document.open();
document.add(new Paragraph("First page"));
document.add(new Paragraph(Document.getVersion()));

document.newPage();
writer.setPageEmpty(false);

document.newPage();
document.add(new Paragraph("New page"));

document.close();

PdfReader reader = new PdfReader(FILE_DIR + "deletePage.pdf");
reader.selectPages("1,3");
PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(FILE_DIR
		+ "deletePage2.pdf"));
stamp.close();
reader.close();



11、插入Page

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

Document document = new Document();

PdfWriter.getInstance(document, out);

document.open();
document.add(new Paragraph("1 page"));

document.newPage();
document.add(new Paragraph("2 page"));

document.newPage();
document.add(new Paragraph("3 page"));

document.close();

PdfReader reader = new PdfReader(FILE_DIR + "insertPage.pdf");
PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(FILE_DIR
		+ "insertPage2.pdf"));

stamp.insertPage(2, reader.getPageSize(1));

ColumnText ct = new ColumnText(null);
ct.addElement(new Paragraph(24, new Chunk("INSERT PAGE")));
ct.setCanvas(stamp.getOverContent(2));
ct.setSimpleColumn(36, 36, 559, 770);

stamp.close();
reader.close();



12、排序page

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

doc.open();
doc.add(new Paragraph("1 page"));
doc.newPage();
doc.add(new Paragraph("2 page"));
doc.newPage();
doc.add(new Paragraph("3 page"));
doc.newPage();
doc.add(new Paragraph("4 page"));
doc.newPage();
doc.add(new Paragraph("5 page"));

int[] order = {4,3,2,1};
writer.reorderPages(order);



13、目录

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

document.newPage();
document.add(new Chunk("Chapter 2").setLocalDestination("2"));
document.add(new Paragraph(new Chunk("Sub 2.1").setLocalDestination("2.1")));
document.add(new Paragraph(new Chunk("Sub 2.2").setLocalDestination("2.2")));

document.newPage();
document.add(new Chunk("Chapter 3").setLocalDestination("3"));

// Code 2
PdfContentByte cb = writer.getDirectContent();
PdfOutline root = cb.getRootOutline();

// Code 3
@SuppressWarnings("unused")
PdfOutline oline1 = new PdfOutline(root, PdfAction.gotoLocalPage("1", false), "Chapter 1");

PdfOutline oline2 = new PdfOutline(root, PdfAction.gotoLocalPage("2", false), "Chapter 2");
oline2.setOpen(false);

@SuppressWarnings("unused")
PdfOutline oline2_1 = new PdfOutline(oline2, PdfAction.gotoLocalPage("2.1", false), "Sub 2.1");
@SuppressWarnings("unused")
PdfOutline oline2_2 = new PdfOutline(oline2, PdfAction.gotoLocalPage("2.2", false), "Sub 2.2");

@SuppressWarnings("unused")
PdfOutline oline3 = new PdfOutline(root, PdfAction.gotoLocalPage("3", false), "Chapter 3");




14、Header, Footer

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

writer.setPageEvent(new PdfPageEventHelper() {

	public void onEndPage(PdfWriter writer, Document document) {
		
		PdfContentByte cb = writer.getDirectContent();
        cb.saveState();

        cb.beginText();
		BaseFont bf = null;
		try {
			bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED);
		} catch (Exception e) {
			e.printStackTrace();
		}
		cb.setFontAndSize(bf, 10);
		
        //Header
		float x = document.top(-20);
		
        //左
        cb.showTextAligned(PdfContentByte.ALIGN_LEFT,
                           "H-Left",
                           document.left(), x, 0);
        //中
        cb.showTextAligned(PdfContentByte.ALIGN_CENTER,
        					writer.getPageNumber()+ " page",
                           (document.right() + document.left())/2,
                           x, 0);
        //右
        cb.showTextAligned(PdfContentByte.ALIGN_RIGHT,
                           "H-Right",
                           document.right(), x, 0);

        //Footer
        float y = document.bottom(-20);

        //左
        cb.showTextAligned(PdfContentByte.ALIGN_LEFT,
                           "F-Left",
                           document.left(), y, 0);
        //中
        cb.showTextAligned(PdfContentByte.ALIGN_CENTER,
        					writer.getPageNumber()+" page",
                           (document.right() + document.left())/2,
                           y, 0);
        //右
        cb.showTextAligned(PdfContentByte.ALIGN_RIGHT,
                           "F-Right",
                           document.right(), y, 0);

        cb.endText();
        
        cb.restoreState();
	}
});

doc.open();
doc.add(new Paragraph("1 page"));        
doc.newPage();
doc.add(new Paragraph("2 page"));        
doc.newPage();
doc.add(new Paragraph("3 page"));        
doc.newPage();
doc.add(new Paragraph("4 page"));



15、左右文字

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

document.open();

PdfContentByte canvas = writer.getDirectContent();

Phrase phrase1 = new Phrase("This is a test!left");
Phrase phrase2 = new Phrase("This is a test!right");
Phrase phrase3 = new Phrase("This is a test!center");
ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, phrase1, 10, 500, 0);
ColumnText.showTextAligned(canvas, Element.ALIGN_RIGHT, phrase2, 10, 536, 0);
ColumnText.showTextAligned(canvas, Element.ALIGN_CENTER, phrase3, 10, 572, 0);



16、幻灯片放映

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

writer.setPdfVersion(PdfWriter.VERSION_1_5);

writer.setViewerPreferences(PdfWriter.PageModeFullScreen);//全屏
writer.setPageEvent(new PdfPageEventHelper() {
	public void onStartPage(PdfWriter writer, Document document) {
		writer.setTransition(new PdfTransition(PdfTransition.DISSOLVE, 3));
		writer.setDuration(5);//间隔时间
	}
});

doc.open();
doc.add(new Paragraph("1 page"));
doc.newPage();
doc.add(new Paragraph("2 page"));
doc.newPage();
doc.add(new Paragraph("3 page"));
doc.newPage();
doc.add(new Paragraph("4 page"));
doc.newPage();
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(); 
ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(FILE_DIR + "zipPDF.zip"));
for (int i = 1; i <= 3; i++) {
	ZipEntry entry = new ZipEntry("hello_" + i + ".pdf");
	zip.putNextEntry(entry);
	Document document = new Document();
	PdfWriter writer = PdfWriter.getInstance(document, zip);
	writer.setCloseStream(false);
	document.open();
	document.add(new Paragraph("Hello " + i));
	document.close();
	zip.closeEntry();
}
zip.close();




18、分割PDF

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

Document document = new Document();

PdfWriter.getInstance(document, out);

document.open();
document.add(new Paragraph("1 page"));

document.newPage();
document.add(new Paragraph("2 page"));

document.newPage();
document.add(new Paragraph("3 page"));

document.newPage();
document.add(new Paragraph("4 page"));

document.close();

PdfReader reader = new PdfReader(FILE_DIR + "splitPDF.pdf");

Document dd = new Document();
PdfWriter writer = PdfWriter.getInstance(dd, new FileOutputStream(FILE_DIR + "splitPDF1.pdf"));
dd.open();
PdfContentByte cb = writer.getDirectContent();
dd.newPage();
cb.addTemplate(writer.getImportedPage(reader, 1), 0, 0);
dd.newPage();
cb.addTemplate(writer.getImportedPage(reader, 2), 0, 0);
dd.close();
writer.close();

Document dd2 = new Document();
PdfWriter writer2 = PdfWriter.getInstance(dd2, new FileOutputStream(FILE_DIR + "splitPDF2.pdf"));
dd2.open();
PdfContentByte cb2 = writer2.getDirectContent();
dd2.newPage();
cb2.addTemplate(writer2.getImportedPage(reader, 3), 0, 0);
dd2.newPage();
cb2.addTemplate(writer2.getImportedPage(reader, 4), 0, 0);
dd2.close();
writer2.close();



19、合并PDF

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

FileOutputStream out = new FileOutputStream(FILE_DIR + "mergePDF.pdf");

Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, out);

document.open();
PdfContentByte cb = writer.getDirectContent();

int totalPages = 0;
totalPages += reader1.getNumberOfPages();
totalPages += reader2.getNumberOfPages();

java.util.List<PdfReader> readers = new ArrayList<PdfReader>();
readers.add(reader1);
readers.add(reader2);

int pageOfCurrentReaderPDF = 0;
Iterator<PdfReader> iteratorPDFReader = readers.iterator();

// Loop through the PDF files and add to the output.
while (iteratorPDFReader.hasNext()) {
	PdfReader pdfReader = iteratorPDFReader.next();

	// Create a new page in the target for each source page.
	while (pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) {
		document.newPage();
		pageOfCurrentReaderPDF++;
		PdfImportedPage page = writer.getImportedPage(pdfReader, pageOfCurrentReaderPDF);
		cb.addTemplate(page, 0, 0);
	}
	pageOfCurrentReaderPDF = 0;
}
out.flush();
document.close();
out.close();



20、Annotation

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

doc.open();
doc.add(new Paragraph("1 page"));
doc.add(new Annotation("Title", "This is a annotation!"));

doc.newPage();
doc.add(new Paragraph("2 page"));
Chunk chunk = new Chunk("\u00a0");
chunk.setAnnotation(PdfAnnotation.createText(writer, null, "Title", "This is a another annotation!", false, "Comment"));
doc.add(chunk);

//添加附件
doc.newPage();
doc.add(new Paragraph("3 page"));
Chunk chunk2 = new Chunk("\u00a0\u00a0");
PdfAnnotation annotation = PdfAnnotation.createFileAttachment(
		writer, null, "Title", null,
		"resource/test2.jpg",
		"img.jpg");
annotation.put(PdfName.NAME,
		new PdfString("Paperclip"));
chunk2.setAnnotation(annotation);
doc.add(chunk2);




21、插入一个Table

Java代码 复制代码 收藏代码
  1. PdfPTable table = new PdfPTable(3);  
  2. PdfPCell cell;  
  3. cell = new PdfPCell(new Phrase("Cell with colspan 3"));  
  4. cell.setColspan(3);  
  5. table.addCell(cell);  
  6. cell = new PdfPCell(new Phrase("Cell with rowspan 2"));  
  7. cell.setRowspan(2);  
  8. table.addCell(cell);  
  9. table.addCell("row 1; cell 1");  
  10. table.addCell("row 1; cell 2");  
  11. table.addCell("row 2; cell 1");  
  12. table.addCell("row 2; cell 2");  
  13.  
  14. document.add(table); 
PdfPTable table = new PdfPTable(3);
PdfPCell cell;
cell = new PdfPCell(new Phrase("Cell with colspan 3"));
cell.setColspan(3);
table.addCell(cell);
cell = new PdfPCell(new Phrase("Cell with rowspan 2"));
cell.setRowspan(2);
table.addCell(cell);
table.addCell("row 1; cell 1");
table.addCell("row 1; cell 2");
table.addCell("row 2; cell 1");
table.addCell("row 2; cell 2");

document.add(table);



22、表格嵌套

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

//1行2列
PdfPTable nested1 = new PdfPTable(2);
nested1.addCell("1.1");
nested1.addCell("1.2");

//2行1列
PdfPTable nested2 = new PdfPTable(1);
nested2.addCell("2.1");
nested2.addCell("2.2");

//将表格插入到指定位置
for (int k = 0; k < 24; ++k) {
    if (k == 1) {
        table.addCell(nested1);
    } else if (k == 20) {
        table.addCell(nested2);
    } else {
        table.addCell("cell " + k);
    }
}

document.add(table);



23、设置表格宽度

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

//100%
table.setWidthPercentage(100);
document.add(table);        
document.add(new Paragraph("\n\n"));

//宽度50% 居左
table.setHorizontalAlignment(Element.ALIGN_LEFT);
document.add(table);
document.add(new Paragraph("\n\n"));

//宽度50% 居中
table.setHorizontalAlignment(Element.ALIGN_CENTER);
document.add(table);
document.add(new Paragraph("\n\n"));

//宽度50% 居右
table.setWidthPercentage(50);
table.setHorizontalAlignment(Element.ALIGN_RIGHT);
document.add(table);
document.add(new Paragraph("\n\n"));

//固定宽度
table.setTotalWidth(300);
table.setLockedWidth(true);
document.add(table);



24、设置表格前后间隔

Java代码 复制代码 收藏代码
  1. PdfPTable table = new PdfPTable(3);  
  2. PdfPCell cell = new PdfPCell(new Paragraph("合并3个单元格",fontZH));  
  3. cell.setColspan(3);  
  4. table.addCell(cell);  
  5. table.addCell("1.1");  
  6. table.addCell("2.1");  
  7. table.addCell("3.1");  
  8. table.addCell("1.2");  
  9. table.addCell("2.2");  
  10. table.addCell("3.2");  
  11.  
  12. cell = new PdfPCell(new Paragraph("红色边框",fontZH));  
  13. cell.setBorderColor(new BaseColor(255, 0, 0));  
  14. table.addCell(cell);  
  15.  
  16. cell = new PdfPCell(new Paragraph("合并单2个元格",fontZH));  
  17. cell.setColspan(2);  
  18. cell.setBackgroundColor(new BaseColor(0xC0, 0xC0, 0xC0));  
  19. table.addCell(cell);  
  20.  
  21. table.setWidthPercentage(50);  
  22.  
  23. document.add(new Paragraph("追加2个表格",fontZH));  
  24. document.add(table);  
  25. document.add(table);  
  26.  
  27. document.newPage();  
  28. document.add(new Paragraph("使用'SpacingBefore'和'setSpacingAfter'",fontZH));  
  29. table.setSpacingBefore(15f);  
  30. document.add(table);  
  31. document.add(table);  
  32. document.add(new Paragraph("这里没有间隔",fontZH));  
  33. table.setSpacingAfter(15f); 
PdfPTable table = new PdfPTable(3);
PdfPCell cell = new PdfPCell(new Paragraph("合并3个单元格",fontZH));
cell.setColspan(3);
table.addCell(cell);
table.addCell("1.1");
table.addCell("2.1");
table.addCell("3.1");
table.addCell("1.2");
table.addCell("2.2");
table.addCell("3.2");

cell = new PdfPCell(new Paragraph("红色边框",fontZH));
cell.setBorderColor(new BaseColor(255, 0, 0));
table.addCell(cell);

cell = new PdfPCell(new Paragraph("合并单2个元格",fontZH));
cell.setColspan(2);
cell.setBackgroundColor(new BaseColor(0xC0, 0xC0, 0xC0));
table.addCell(cell);

table.setWidthPercentage(50);

document.add(new Paragraph("追加2个表格",fontZH));
document.add(table);
document.add(table);

document.newPage();
document.add(new Paragraph("使用'SpacingBefore'和'setSpacingAfter'",fontZH));
table.setSpacingBefore(15f);
document.add(table);
document.add(table);
document.add(new Paragraph("这里没有间隔",fontZH));
table.setSpacingAfter(15f);



25、设置单元格宽度

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

//调整比例
widths[0] = 20f;
widths[1] = 20f;
widths[2] = 10f;
widths[3] = 50f;
table.setWidths(widths);
document.add(table);

//按绝对值设置单元格宽度
widths[0] = 40f;
widths[1] = 40f;
widths[2] = 20f;
widths[3] = 300f;
Rectangle r = new Rectangle(PageSize.A4.getRight(72), PageSize.A4.getTop(72));
table.setWidthPercentage(widths, r);
document.add(new Paragraph("\n\n"));
document.add(table);



26、设置单元格高度

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

PdfPCell cell;

//折行
table.addCell(new PdfPCell(new Paragraph("折行", fontZH)));
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"));
cell.setNoWrap(false);
table.addCell(cell);

//不折行
table.addCell(new PdfPCell(new Paragraph("不折行", fontZH)));
cell.setNoWrap(true);
table.addCell(cell);

//设置高度
table.addCell(new PdfPCell(new Paragraph("任意高度",fontZH)));
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"));
table.addCell(cell);

//固定高度
table.addCell(new PdfPCell(new Paragraph("固定高度",fontZH)));
cell.setFixedHeight(50f);
table.addCell(cell);

//最小高度
table.addCell(new PdfPCell(new Paragraph("最小高度",fontZH)));
cell = new PdfPCell(new Paragraph("最小高度:50",fontZH));
cell.setMinimumHeight(50f);
table.addCell(cell);

//最后一行拉长到page底部
table.setExtendLastRow(true);
table.addCell(new PdfPCell(new Paragraph("拉长最后一行",fontZH)));
cell = new PdfPCell(new Paragraph("最后一行拉长到page底部",fontZH));
table.addCell(cell);

document.add(table);



27、设置单元格颜色

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

//红色背景,无边框
cell = new PdfPCell(new Paragraph("红色背景,无边框",fontZH));
cell.setBorder(Rectangle.NO_BORDER);
cell.setBackgroundColor(BaseColor.RED);
table.addCell(cell);

//绿色背景,下边框
cell = new PdfPCell(new Paragraph("绿色背景,下边框",fontZH));
cell.setBorder(Rectangle.BOTTOM);
cell.setBorderColorBottom(BaseColor.MAGENTA);
cell.setBorderWidthBottom(5f);
cell.setBackgroundColor(BaseColor.GREEN);
table.addCell(cell);

//蓝色背景,上边框
cell = new PdfPCell(new Paragraph("蓝色背景,上边框",fontZH));
cell.setBorder(Rectangle.TOP);
cell.setUseBorderPadding(true);
cell.setBorderWidthTop(5f);
cell.setBorderColorTop(BaseColor.CYAN);
cell.setBackgroundColor(BaseColor.BLUE);
table.addCell(cell);

cell = new PdfPCell(new Paragraph("背景灰色度",fontZH));
table.addCell(cell);
cell = new PdfPCell(new Paragraph("0.25"));
cell.setBorder(Rectangle.NO_BORDER);
cell.setGrayFill(0.25f);
table.addCell(cell);
cell = new PdfPCell(new Paragraph("0.5"));
cell.setBorder(Rectangle.NO_BORDER);
cell.setGrayFill(0.5f);
table.addCell(cell);
cell = new PdfPCell(new Paragraph("0.75"));
cell.setBorder(Rectangle.NO_BORDER);
cell.setGrayFill(0.75f);
table.addCell(cell);

document.add(table);



28、插入图像

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

PdfPTable table = new PdfPTable(widths);

//插入图片
table.addCell(new PdfPCell(new Paragraph("图片测试", fontZH)));
table.addCell(image);

//调整图片大小
table.addCell("This two");
table.addCell(new PdfPCell(image, true));

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

datatable.addCell("Clock #");
datatable.addCell("Trans Type");
datatable.addCell("Cusip");
datatable.addCell("Long Name");
datatable.addCell("Quantity");
datatable.addCell("Fraction Price");
datatable.addCell("Settle Date");
datatable.addCell("Portfolio");
datatable.addCell("ADP Number");
datatable.addCell("Account ID");
datatable.addCell("Reg Rep ID");
datatable.addCell("Amt To Go ");

datatable.setHeaderRows(1);

//边框
datatable.getDefaultCell().setBorderWidth(1);

//背景色
for (int i = 1; i < 1000; i++) {
    for (int x = 0; x < NumColumns; x++) {
        datatable.addCell(bogusData[x]);
    }
}

document.add(datatable);



30、分割表格

Java代码 复制代码 收藏代码
  1. //横向分割  
  2. PdfContentByte cb = writer.getDirectContent();  
  3. PdfPTable table = new PdfPTable(10);  
  4. for (int k = 1; k <= 100; ++k) {  
  5.     table.addCell("The number " + k);  
  6. }  
  7. table.setTotalWidth(400);  
  8.  
  9. table.writeSelectedRows(0, 5, 0, -1, 5, 700, cb);  
  10. table.writeSelectedRows(5, -1, 0, -1, 210, 700, cb); 
//横向分割
PdfContentByte cb = writer.getDirectContent();
PdfPTable table = new PdfPTable(10);
for (int k = 1; k <= 100; ++k) {
    table.addCell("The number " + k);
}
table.setTotalWidth(400);

table.writeSelectedRows(0, 5, 0, -1, 5, 700, cb);
table.writeSelectedRows(5, -1, 0, -1, 210, 700, cb);



31、设置单元格留白

Java代码 复制代码 收藏代码
  1. PdfPTable table = new PdfPTable(2);  
  2. PdfPCell cell;  
  3. Paragraph p = new Paragraph("Quick brown fox jumps over the lazy dog. Quick brown fox jumps over the lazy dog.");  
  4. table.addCell(new PdfPCell(new Paragraph("默认",fontZH)));  
  5. table.addCell(p);  
  6. table.addCell(new PdfPCell(new Paragraph("Padding:10",fontZH)));  
  7. cell = new PdfPCell(p);  
  8. cell.setPadding(10f);  
  9. table.addCell(cell);  
  10. table.addCell(new PdfPCell(new Paragraph("Padding:0",fontZH)));  
  11. cell = new PdfPCell(p);  
  12. cell.setPadding(0f);  
  13. table.addCell(cell);  
  14. table.addCell(new PdfPCell(new Paragraph("上Padding:0 左Padding:20",fontZH)));  
  15. cell = new PdfPCell(p);  
  16. cell.setPaddingTop(0f);  
  17. cell.setPaddingLeft(20f);  
  18. table.addCell(cell);  
  19. document.add(table);  
  20.  
  21. document.newPage();  
  22. table = new PdfPTable(2);  
  23. table.addCell(new PdfPCell(new Paragraph("没有Leading",fontZH)));  
  24. table.getDefaultCell().setLeading(0f, 0f);  
  25. table.addCell("blah blah\nblah blah blah\nblah blah\nblah blah blah\nblah blah\nblah blah blah\nblah blah\nblah blah blah\n");  
  26. table.getDefaultCell().setLeading(14f, 0f);  
  27. table.addCell(new PdfPCell(new Paragraph("固定Leading:14pt",fontZH)));  
  28. table.addCell("blah blah\nblah blah blah\nblah blah\nblah blah blah\nblah blah\nblah blah blah\nblah blah\nblah blah blah\n");  
  29. table.addCell(new PdfPCell(new Paragraph("相对于字体",fontZH)));  
  30. table.getDefaultCell().setLeading(0f, 1.0f);  
  31. table.addCell("blah blah\nblah blah blah\nblah blah\nblah blah blah\nblah blah\nblah blah blah\nblah blah\nblah blah blah\n");  
  32. document.add(table); 
PdfPTable table = new PdfPTable(2);
PdfPCell cell;
Paragraph p = new Paragraph("Quick brown fox jumps over the lazy dog. Quick brown fox jumps over the lazy dog.");
table.addCell(new PdfPCell(new Paragraph("默认",fontZH)));
table.addCell(p);
table.addCell(new PdfPCell(new Paragraph("Padding:10",fontZH)));
cell = new PdfPCell(p);
cell.setPadding(10f);
table.addCell(cell);
table.addCell(new PdfPCell(new Paragraph("Padding:0",fontZH)));
cell = new PdfPCell(p);
cell.setPadding(0f);
table.addCell(cell);
table.addCell(new PdfPCell(new Paragraph("上Padding:0 左Padding:20",fontZH)));
cell = new PdfPCell(p);
cell.setPaddingTop(0f);
cell.setPaddingLeft(20f);
table.addCell(cell);
document.add(table);

document.newPage();
table = new PdfPTable(2);
table.addCell(new PdfPCell(new Paragraph("没有Leading",fontZH)));
table.getDefaultCell().setLeading(0f, 0f);
table.addCell("blah blah\nblah blah blah\nblah blah\nblah blah blah\nblah blah\nblah blah blah\nblah blah\nblah blah blah\n");
table.getDefaultCell().setLeading(14f, 0f);
table.addCell(new PdfPCell(new Paragraph("固定Leading:14pt",fontZH)));
table.addCell("blah blah\nblah blah blah\nblah blah\nblah blah blah\nblah blah\nblah blah blah\nblah blah\nblah blah blah\n");
table.addCell(new PdfPCell(new Paragraph("相对于字体",fontZH)));
table.getDefaultCell().setLeading(0f, 1.0f);
table.addCell("blah blah\nblah blah blah\nblah blah\nblah blah blah\nblah blah\nblah blah blah\nblah blah\nblah blah blah\n");
document.add(table);



32、设置单元格边框

Java代码 复制代码 收藏代码
  1. //没有边框  
  2. PdfPTable table1 = new PdfPTable(3);    
  3. table1.getDefaultCell().setBorder(PdfPCell.NO_BORDER);    
  4. table1.addCell(new Paragraph("Cell 1"));   
  5. table1.addCell(new Paragraph("Cell 2"));   
  6. table1.addCell(new Paragraph("Cell 3"));   
  7. document.add(table1);  
  8.  
  9. //边框粗细颜色  
  10. document.newPage();  
  11. Rectangle b1 = new Rectangle(0f, 0f);  
  12. b1.setBorderWidthLeft(6f);  
  13. b1.setBorderWidthBottom(5f);  
  14. b1.setBorderWidthRight(4f);  
  15. b1.setBorderWidthTop(2f);  
  16. b1.setBorderColorLeft(BaseColor.RED);  
  17. b1.setBorderColorBottom(BaseColor.ORANGE);  
  18. b1.setBorderColorRight(BaseColor.YELLOW);  
  19. b1.setBorderColorTop(BaseColor.GREEN);  
  20. PdfPTable table2 = new PdfPTable(1);  
  21. PdfPCell cell =  new PdfPCell(new Paragraph("Cell 1"));  
  22. cell.cloneNonPositionParameters(b1);  
  23. table2.addCell(cell);  
  24. document.add(table2); 
//没有边框
PdfPTable table1 = new PdfPTable(3);  
table1.getDefaultCell().setBorder(PdfPCell.NO_BORDER);  
table1.addCell(new Paragraph("Cell 1")); 
table1.addCell(new Paragraph("Cell 2")); 
table1.addCell(new Paragraph("Cell 3")); 
document.add(table1);

//边框粗细颜色
document.newPage();
Rectangle b1 = new Rectangle(0f, 0f);
b1.setBorderWidthLeft(6f);
b1.setBorderWidthBottom(5f);
b1.setBorderWidthRight(4f);
b1.setBorderWidthTop(2f);
b1.setBorderColorLeft(BaseColor.RED);
b1.setBorderColorBottom(BaseColor.ORANGE);
b1.setBorderColorRight(BaseColor.YELLOW);
b1.setBorderColorTop(BaseColor.GREEN);
PdfPTable table2 = new PdfPTable(1);
PdfPCell cell =  new PdfPCell(new Paragraph("Cell 1"));
cell.cloneNonPositionParameters(b1);
table2.addCell(cell);
document.add(table2);



33、PdfPTableEvent

34、PdfPCellEvent

35、PdfPageEventHelper

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值