如何运用Java组件itext生成pdf

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何运用Java组件itext生成pdf相关的知识,希望对你有一定的参考价值。

  如何使用Java组件itext 生成pdf?iText是一个能够快速产生PDF文件的java类库。iText的java类对于那些要产生包含文本,表格,图形的只读文档是很有用的。它的类库尤其与java Servlet有很好的给合。使用iText与PDF能够使你正确的控制Servlet的输出。

  在企业的信息系统中,报表处理一直占比较重要的作用,Java组件——iText可以非常快速的生成PDF报表。iText是着名的开放源码的站点sourceforge一个项目,是用于生成PDF文档的一个java类库。通过iText不仅可以生成PDF或rtf的文档,而且可以将XML、 html文件转化为PDF文件。通过在服务器端使用Jsp或JavaBean生成PDF报表,客户端采用超级连接显示或下载得到生成的报表,这样就很好的解决了B/S系统的报表处理问题了。
  一、iText介绍
  iText是着名的开放源码的站点sourceforge一个项目,是用于生成PDF文档的一个java类库。通过iText不仅可以生成PDF或rtf的文档,而且可以将XML、Html文件转化为PDF文件。
  iText的安装非常方便,在http://www.lowagie.com/iText/download.html - download 网站上下载iText.jar文件后,只需要在系统的CLASSPATH中加入iText.jar的路径,在程序中就可以使用iText类库了。
  二、建立第一个PDF文档
  用iText生成PDF文档需要5个步骤:
  ①建立com.lowagie.text.Document对象的实例。
  Document document = new Document();
  ②建立一个书写器(Writer)与document对象关联,通过书写器(Writer)可以将文档写入到磁盘中。
  PDFWriter.getInstance(document, new FileOutputStream("Helloworld.PDF"));
  ③打开文档。
  document.open();
  ④向文档中添加内容。
  document.add(new Paragraph("Hello World"));
  ⑤关闭文档。
  document.close();
  通过上面的5个步骤,就能产生一个Helloworld.PDF的文件,文件内容为"Hello World"。
  建立com.lowagie.text.Document对象的实例
  com.lowagie.text.Document对象的构建函数有三个,分别是:
  public Document();
  public Document(Rectangle pageSize);
  public Document(Rectangle pageSize,
  int marginLeft,
  int marginRight,
  int marginTop,
  int marginBottom);
  构建函数的参数pageSize是文档页面的大小,对于第一个构建函数,页面的大小为A4,同Document(PageSize.A4)的效果一样;对于第三个构建函数,参数marginLeft、marginRight、marginTop、marginBottom分别为左、右、上、下的页边距。
  通过参数pageSize可以设定页面大小、面背景色、以及页面横向/纵向等属性。iText定义了A0-A10、AL、LETTER、 HALFLETTER、_11x17、LEDGER、NOTE、B0-B5、ARCH_A-ARCH_E、FLSA 和FLSE等纸张类型,也可以通过Rectangle pageSize = new Rectangle(144, 720);自定义纸张。通过Rectangle方法rotate()可以将页面设置成横向。
  书写器(Writer)对象
  一旦文档(document)对象建立好之后,需要建立一个或多个书写器(Writer)对象与之关联。通过书写器(Writer)对象可以将具体文档存盘成需要的格式,如com.lowagie.text.PDF.PDFWriter可以将文档存成PDF文件, com.lowagie.text.html.HtmlWriter可以将文档存成html文件。
  设定文档属性
  在文档打开之前,可以设定文档的标题、主题、作者、关键字、装订方式、创建者、生产者、创建日期等属性,调用的方法分别是:
  public boolean addTitle(String title)
  public boolean addSubject(String subject)
  public boolean addKeywords(String keywords)
  public boolean addAuthor(String author)
  public boolean addCreator(String creator)
  public boolean addProducer()
  public boolean addCreationDate()
  public boolean addHeader(String name, String content)
  其中方法addHeader对于PDF文档无效,addHeader仅对html文档有效,用于添加文档的头信息。
  当新的页面产生之前,可以设定页面的大小、书签、脚注(HeaderFooter)等信息,调用的方法是:
  public boolean setPageSize(Rectangle pageSize)
  public boolean add(Watermark watermark)
  public void removeWatermark()
  public void setHeader(HeaderFooter header)
  public void resetHeader()
  public void setFooter(HeaderFooter footer)
  public void resetFooter()
  public void resetPageCount()
  public void setPageCount(int pageN)
  如果要设定第一页的页面属性,这些方法必须在文档打开之前调用。
  对于PDF文档,iText还提供了文档的显示属性,通过调用书写器的setViewerPreferences方法可以控制文档打开时Acrobat Reader的显示属性,如是否单页显示、是否全屏显示、是否隐藏状态条等属性。
  另外,iText也提供了对PDF文件的安全保护,通过书写器(Writer)的setEncryption方法,可以设定文档的用户口令、只读、可打印等属性。
  添加文档内容
  所有向文档添加的内容都是以对象为单位的,如Phrase、Paragraph、Table、Graphic对象等。比较常用的是段落(Paragraph)对象,用于向文档中添加一段文字。
  三、文本处理
  iText中用文本块(Chunk)、短语(Phrase)和段落(paragraph)处理文本。
  文本块(Chunk)是处理文本的最小单位,有一串带格式(包括字体、颜色、大小)的字符串组成。如以下代码就是产生一个字体为HELVETICA、大小为10、带下划线的字符串:
  Chunk chunk1 = new Chunk("This text is underlined", FontFactory.getFont(FontFactory.HELVETICA, 12, Font.UNDERLINE));
  短语(Phrase)由一个或多个文本块(Chunk)组成,短语(Phrase)也可以设定字体,但对于其中以设定过字体的文本块 (Chunk)无效。通过短语(Phrase)成员函数add可以将一个文本块(Chunk)加到短语(Phrase)中,如:phrase6.add(chunk);
  段落(paragraph)由一个或多个文本块(Chunk)或短语(Phrase)组成,相当于WORD文档中的段落概念,同样可以设定段落的字体大小、颜色等属性。另外也可以设定段落的首行缩进、对齐方式(左对齐、右对齐、居中对齐)。通过函数setAlignment可以设定段落的对齐方式, setAlignment的参数1为居中对齐、2为右对齐、3为左对齐,默认为左对齐。
  四、表格处理
  iText中处理表格的类为:com.lowagie.text.Table和com.lowagie.text.PDF.PDFPTable,对于比较简单的表格处理可以用com.lowagie.text.Table,但是如果要处理复杂的表格,这就需要 com.lowagie.text.PDF.PDFPTable进行处理。这里就类com.lowagie.text.Table进行说明。
  类com.lowagie.text.Table的构造函数有三个:
  ①Table (int columns)
  ②Table(int columns, int rows)
  ③Table(Properties attributes)
  参数columns、rows、attributes分别为表格的列数、行数、表格属性。创建表格时必须指定表格的列数,而对于行数可以不用指定。
  建立表格之后,可以设定表格的属性,如:边框宽度、边框颜色、衬距(padding space 即单元格之间的间距)大小等属性。下面通过一个简单的例子说明如何使用表格,代码如下:
  1:Table table = new Table(3);
  2:table.setBorderWidth(1);
  3:table.setBorderColor(new Color(0, 0, 255));
  4:table.setPadding(5);
  5:table.setSpacing(5);
  6:Cell cell = new Cell("header");
  7:cell.setHeader(true);
  8:cell.setColspan(3);
  9:table.addCell(cell);
  10:table.endHeaders();
  11:cell = new Cell("example cell with colspan 1 and rowspan 2");
  12:cell.setRowspan(2);
  13:cell.setBorderColor(new Color(255, 0, 0));
  14:table.addCell(cell);
  15:table.addCell("1.1");
  16:table.addCell("2.1");
  17:table.addCell("1.2");
  18:table.addCell("2.2");
  19:table.addCell("cell test1");
  20:cell = new Cell("big cell");
  21:cell.setRowspan(2);
  22:cell.setColspan(2);
  23:table.addCell(cell);
  24:table.addCell("cell test2");
  运行结果如下:
  header
  example cell with colspan 1 and rowspan 2 1.1 2.1
  1.2 2.2
  cell test1 big cell
  cell test2
  代码1-5行用于新建一个表格,如代码所示,建立了一个列数为3的表格,并将边框宽度设为1,颜色为蓝色,衬距为5。
  代码6-10行用于设定表格的表头,第7行cell.setHeader(true);是将该单元格作为表头信息显示;第8行 cell.setColspan(3);指定了该单元格占3列;为表格添加表头信息时,要注意的是一旦表头信息添加完了之后,必须调用 endHeaders()方法,如第10行,否则当表格跨页后,表头信息不会再显示。
  代码11-14行是向表格中添加一个宽度占一列,长度占二行的单元格。
  往表格中添加单元格(cell)时,按自左向右、从上而下的次序添加。如执行完11行代码后,表格的右下方出现2行2列的空白,这是再往表格添加单元格时,先填满这个空白,然后再另起一行,15-24行代码说明了这种添加顺序。
  五、图像处理
  iText中处理表格的类为com.lowagie.text.Image,目前iText支持的图像格式有:GIF, Jpeg, PNG, wmf等格式,对于不同的图像格式,iText用同样的构造函数自动识别图像格式。通过下面的代码分别获得gif、jpg、png图像的实例。
  Image gif = Image.getInstance("vonnegut.gif");
  Image jpeg = Image.getInstance("myKids.jpg");
  Image png = Image.getInstance("hitchcock.png");
  图像的位置
  图像的位置主要是指图像在文档中的对齐方式、图像和文本的位置关系。IText中通过函数public void setAlignment(int alignment)进行处理,参数alignment为Image.RIGHT、Image.MIDDLE、Image.LEFT分别指右对齐、居中、左对齐;当参数alignment为Image.TEXTWRAP、Image.UNDERLYING分别指文字绕图形显示、图形作为文字的背景显示。这两种参数可以结合以达到预期的效果,如setAlignment(Image.RIGHT|Image.TEXTWRAP)显示的效果为图像右对齐,文字围绕图像显示。
  图像的尺寸和旋转
  如果图像在文档中不按原尺寸显示,可以通过下面的函数进行设定:
  public void scaleAbsolute(int newWidth, int newHeight)
  public void scalePercent(int percent)
  public void scalePercent(int percentX, int percentY)
  函数public void scaleAbsolute(int newWidth, int newHeight)直接设定显示尺寸;函数public void scalePercent(int percent)设定显示比例,如scalePercent(50)表示显示的大小为原尺寸的50%;而函数scalePercent(int percentX, int percentY)则图像高宽的显示比例。
  如果图像需要旋转一定角度之后在文档中显示,可以通过函数public void setRotation(double r)设定,参数r为弧度,如果旋转角度为30度,则参数r= Math.PI / 6。
  六、中文处理
  默认的iText字体设置不支持中文字体,需要下载远东字体包iTextAsian.jar,否则不能往PDF文档中输出中文字体。通过下面的代码就可以在文档中使用中文了:
  BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
  com.lowagie.text.Font FontChinese = new com.lowagie.text.Font(bfChinese, 12, com.lowagie.text.Font.NORMAL);
  Paragraph pragraph=new Paragraph("你好", FontChinese);
参考技术A 首先你要New一个类

转 Java操作PDF之iText详细入门

Java操作PDF之iText详细入门

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

http://itextpdf.com/ 

版本:itextpdf-5.2.1.jar 

1、生成一个PDF 
Java代码  技术分享图片
  1. //Step 1—Create a Document.  
  2. Document document = new Document();  
  3. //Step 2—Get a PdfWriter instance.  
  4. PdfWriter.getInstance(document, new FileOutputStream(FILE_DIR + "createSamplePDF.pdf"));  
  5. //Step 3—Open the Document.  
  6. document.open();  
  7. //Step 4—Add content.  
  8. document.add(new Paragraph("Hello World"));  
  9. //Step 5—Close the Document.  
  10. document.close();  


2、页面大小,页面背景色,页边空白,Title,Author,Subject,Keywords 
Java代码  技术分享图片
  1. //页面大小  
  2. Rectangle rect = new Rectangle(PageSize.B5.rotate());  
  3. //页面背景色  
  4. rect.setBackgroundColor(BaseColor.ORANGE);  
  5.   
  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("[email protected]");  
  15. doc.addAuthor("[email protected]");  
  16. doc.addSubject("[email protected] sample");  
  17. doc.addKeywords("[email protected]");  
  18. doc.addCreator("[email protected]");  
  19.   
  20. //页边空白  
  21. doc.setMargins(10, 20, 30, 40);  
  22.   
  23. doc.open();  
  24. 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"));  

技术分享图片 

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


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


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


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


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

技术分享图片 

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


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


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


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


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

技术分享图片 

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


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


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


17、压缩PDF到Zip 
Java代码  技术分享图片
  1. ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(FILE_DIR + "zipPDF.zip"));  
  2. for (int i = 1; i <= 3; i++) {  
  3.     ZipEntry entry = new ZipEntry("hello_" + i + ".pdf");  
  4.     zip.putNextEntry(entry);  
  5.     Document document = new Document();  
  6.     PdfWriter writer = PdfWriter.getInstance(document, zip);  
  7.     writer.setCloseStream(false);  
  8.     document.open();  
  9.     document.add(new Paragraph("Hello " + i));  
  10.     document.close();  
  11.     zip.closeEntry();  
  12. }  
  13. zip.close();  

技术分享图片 

18、分割PDF 
Java代码  技术分享图片
  1. FileOutputStream out = new FileOutputStream(FILE_DIR + "splitPDF.pdf");  
  2.   
  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();  


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


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

技术分享图片 

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


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


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


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


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


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


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


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


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


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


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


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


33、PdfPTableEvent 

34、PdfPCellEvent 

35、PdfPageEventHelper 

36、生成Barcode QRCode 
Java代码  技术分享图片
  1. String myString = "http://www.google.com";  
  2.   
  3. Barcode128 code128 = new Barcode128();  
  4. code128.setCode(myString.trim());  
  5. code128.setCodeType(Barcode128.CODE128);  
  6. Image code128Image = code128.createImageWithBarcode(cb, null, null);  
  7. code128Image.setAbsolutePosition(10,700);  
  8. code128Image.scalePercent(125);  
  9. doc.add(code128Image);  
  10.   
  11. BarcodeQRCode qrcode = new BarcodeQRCode(myString.trim(), 1, 1, null);  
  12. Image qrcodeImage = qrcode.getImage();  
  13. qrcodeImage.setAbsolutePosition(10,600);  
  14. qrcodeImage.scalePercent(200);  
  15. doc.add(qrcodeImage);  

技术分享图片 

37、HTML to PDF 
Java代码  技术分享图片
  1. Document document = new Document(PageSize.LETTER);  
  2. PdfWriter.getInstance(document, new FileOutputStream("c://testpdf1.pdf"));  
  3. document.open();  
  4. HTMLWorker htmlWorker = new HTMLWorker(document);  
  5. htmlWorker.parse(new StringReader("<h1>This is a test!</h1>"));  
  6. document.close();  

技术分享图片 
























































































































以上是关于如何运用Java组件itext生成pdf的主要内容,如果未能解决你的问题,请参考以下文章

如何运用Java组件itext生成pdf

如何运用Java组件itext生成pdf

如何运用Java组件itext生成pdf

如何运用Java组件itext生成pdf

如何运用Java组件itext生成pdf

java 已经获取pdf代码,如何把他pdf文件保存到本机 要求用输出流做