iText入门(2012.07.10)

该文转载于博友( http://lichunhui.iteye.com/blog/1550584

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

http://itextpdf.com/

版本:itextpdf-5.2.1.jar

1、生成一个PDF

Java代码 收藏代码
  1. //Step1—CreateaDocument.
  2. Documentdocument=newDocument();
  3. //Step2—GetaPdfWriterinstance.
  4. PdfWriter.getInstance(document,newFileOutputStream(FILE_DIR+"createSamplePDF.pdf"));
  5. //Step3—OpentheDocument.
  6. document.open();
  7. //Step4—Addcontent.
  8. document.add(newParagraph("HelloWorld"));
  9. //Step5—ClosetheDocument.
  10. document.close();



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

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


iText入门(2012.07.10)

3、设置密码

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


iText入门(2012.07.10)

4、添加Page

Java代码 收藏代码
  1. document.open();
  2. document.add(newParagraph("Firstpage"));
  3. document.add(newParagraph(Document.getVersion()));
  4. document.newPage();
  5. writer.setPageEmpty(false);
  6. document.newPage();
  7. document.add(newParagraph("Newpage"));



5、添加水印(背景图)

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



6、插入Chunk, Phrase, Paragraph, List

Java代码 收藏代码
  1. //Chunk对象:aString,aFont,andsomeattributes
  2. document.add(newChunk("China"));
  3. document.add(newChunk(""));
  4. Fontfont=newFont(Font.FontFamily.HELVETICA,6,Font.BOLD,BaseColor.WHITE);
  5. Chunkid=newChunk("chinese",font);
  6. id.setBackground(BaseColor.BLACK,1f,0.5f,1f,1.5f);
  7. id.setTextRise(6);
  8. document.add(id);
  9. document.add(Chunk.NEWLINE);
  10. document.add(newChunk("Japan"));
  11. document.add(newChunk(""));
  12. Fontfont2=newFont(Font.FontFamily.HELVETICA,6,Font.BOLD,BaseColor.WHITE);
  13. Chunkid2=newChunk("japanese",font2);
  14. id2.setBackground(BaseColor.BLACK,1f,0.5f,1f,1.5f);
  15. id2.setTextRise(6);
  16. id2.setUnderline(0.2f,-2f);
  17. document.add(id2);
  18. document.add(Chunk.NEWLINE);
  19. //Phrase对象:aListofChunkswithleading
  20. document.newPage();
  21. document.add(newPhrase("Phrasepage"));
  22. Phrasedirector=newPhrase();
  23. Chunkname=newChunk("China");
  24. name.setUnderline(0.2f,-2f);
  25. director.add(name);
  26. director.add(newChunk(","));
  27. director.add(newChunk(""));
  28. director.add(newChunk("chinese"));
  29. director.setLeading(24);
  30. document.add(director);
  31. Phrasedirector2=newPhrase();
  32. Chunkname2=newChunk("Japan");
  33. name2.setUnderline(0.2f,-2f);
  34. director2.add(name2);
  35. director2.add(newChunk(","));
  36. director2.add(newChunk(""));
  37. director2.add(newChunk("japanese"));
  38. director2.setLeading(24);
  39. document.add(director2);
  40. //Paragraph对象:aPhrasewithextrapropertiesandanewline
  41. document.newPage();
  42. document.add(newParagraph("Paragraphpage"));
  43. Paragraphinfo=newParagraph();
  44. info.add(newChunk("China"));
  45. info.add(newChunk("chinese"));
  46. info.add(Chunk.NEWLINE);
  47. info.add(newPhrase("Japan"));
  48. info.add(newPhrase("japanese"));
  49. document.add(info);
  50. //List对象:asequenceofParagraphscalledListItem
  51. document.newPage();
  52. Listlist=newList(List.ORDERED);
  53. for(inti=0;i<10;i++){
  54. ListItemitem=newListItem(String.format("%s:%dmovies",
  55. "country"+(i+1),(i+1)*100),newFont(
  56. Font.FontFamily.HELVETICA,6,Font.BOLD,BaseColor.WHITE));
  57. Listmovielist=newList(List.ORDERED,List.ALPHABETICAL);
  58. movielist.setLowercase(List.LOWERCASE);
  59. for(intj=0;j<5;j++){
  60. ListItemmovieitem=newListItem("Title"+(j+1));
  61. Listdirectorlist=newList(List.UNORDERED);
  62. for(intk=0;k<3;k++){
  63. directorlist.add(String.format("%s,%s","Name1"+(k+1),
  64. "Name2"+(k+1)));
  65. }
  66. movieitem.add(directorlist);
  67. movielist.add(movieitem);
  68. }
  69. item.add(movielist);
  70. list.add(item);
  71. }
  72. document.add(list);



7、插入Anchor, Image, Chapter, Section

Java代码 收藏代码
  1. //Anchor对象:internalandexternallinks
  2. Paragraphcountry=newParagraph();
  3. Anchordest=newAnchor("china",newFont(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(":%dsites",10000));
  8. document.add(country);
  9. document.newPage();
  10. AnchortoUS=newAnchor("Gotofirstpage.",newFont(Font.FontFamily.HELVETICA,14,Font.BOLD,BaseColor.BLUE));
  11. toUS.setReference("#CN");//internal
  12. document.add(toUS);
  13. //Image对象
  14. document.newPage();
  15. Imageimg=Image.getInstance("resource/test.jpg");
  16. img.setAlignment(Image.LEFT|Image.TEXTWRAP);
  17. img.setBorder(Image.BOX);
  18. img.setBorderWidth(10);
  19. img.setBorderColor(BaseColor.WHITE);
  20. img.scaleToFit(1000,72);//大小
  21. img.setRotationDegrees(-30);//旋转
  22. document.add(img);
  23. //Chapter,Section对象(目录)
  24. document.newPage();
  25. Paragraphtitle=newParagraph("Title");
  26. Chapterchapter=newChapter(title,1);
  27. title=newParagraph("SectionA");
  28. Sectionsection=chapter.addSection(title);
  29. section.setBookmarkTitle("bmk");
  30. section.setIndentation(30);
  31. section.setBookmarkOpen(false);
  32. section.setNumberStyle(
  33. Section.NUMBERSTYLE_DOTTED_WITHOUT_FINAL_DOT);
  34. Sectionsubsection=section.addSection(newParagraph("SubSectionA"));
  35. subsection.setIndentationLeft(20);
  36. subsection.setNumberDepth(1);
  37. document.add(chapter);



8、画图

Java代码 收藏代码
  1. //左右箭头
  2. document.add(newVerticalPositionMark(){
  3. publicvoiddraw(PdfContentBytecanvas,floatllx,floatlly,
  4. floaturx,floatury,floaty){
  5. canvas.beginText();
  6. BaseFontbf=null;
  7. try{
  8. bf=BaseFont.createFont(BaseFont.ZAPFDINGBATS,"",BaseFont.EMBEDDED);
  9. }catch(Exceptione){
  10. e.printStackTrace();
  11. }
  12. canvas.setFontAndSize(bf,12);
  13. //LEFT
  14. canvas.showTextAligned(Element.ALIGN_CENTER,String.valueOf((char)220),llx-10,y,0);
  15. //RIGHT
  16. canvas.showTextAligned(Element.ALIGN_CENTER,String.valueOf((char)220),urx+10,y+8,180);
  17. canvas.endText();
  18. }
  19. });
  20. //直线
  21. Paragraphp1=newParagraph("LEFT");
  22. p1.add(newChunk(newLineSeparator()));
  23. p1.add("R");
  24. document.add(p1);
  25. //点线
  26. Paragraphp2=newParagraph("LEFT");
  27. p2.add(newChunk(newDottedLineSeparator()));
  28. p2.add("R");
  29. document.add(p2);
  30. //下滑线
  31. LineSeparatorUNDERLINE=newLineSeparator(1,100,null,Element.ALIGN_CENTER,-2);
  32. Paragraphp3=newParagraph("NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN");
  33. p3.add(UNDERLINE);
  34. document.add(p3);


iText入门(2012.07.10)

9、设置段落

Java代码 收藏代码
  1. Paragraphp=newParagraph("Inthepreviousexample,youaddedaheaderandfooterwiththeshowTextAligned()method.Thisexampledemonstratesthatit’ssometimesmoreinterestingtousePdfPTableandwriteSelectedRows().Youcandefineabottomborderforeachcellsothattheheaderisunderlined.Thisisthemostelegantwaytoaddheadersandfooters,becausethetablemechanismallowsyoutopositionandalignlines,images,andtext.");
  2. //默认
  3. p.setAlignment(Element.ALIGN_JUSTIFIED);
  4. document.add(p);
  5. document.newPage();
  6. p.setAlignment(Element.ALIGN_JUSTIFIED);
  7. p.setIndentationLeft(1*15f);
  8. p.setIndentationRight((5-1)*15f);
  9. document.add(p);
  10. //居右
  11. document.newPage();
  12. p.setAlignment(Element.ALIGN_RIGHT);
  13. p.setSpacingAfter(15f);
  14. document.add(p);
  15. //居左
  16. document.newPage();
  17. p.setAlignment(Element.ALIGN_LEFT);
  18. p.setSpacingBefore(15f);
  19. document.add(p);
  20. //居中
  21. document.newPage();
  22. p.setAlignment(Element.ALIGN_CENTER);
  23. p.setSpacingAfter(15f);
  24. p.setSpacingBefore(15f);
  25. document.add(p);



10、删除Page

Java代码 收藏代码
  1. FileOutputStreamout=newFileOutputStream(FILE_DIR+"deletePage.pdf");
  2. Documentdocument=newDocument();
  3. PdfWriterwriter=PdfWriter.getInstance(document,out);
  4. document.open();
  5. document.add(newParagraph("Firstpage"));
  6. document.add(newParagraph(Document.getVersion()));
  7. document.newPage();
  8. writer.setPageEmpty(false);
  9. document.newPage();
  10. document.add(newParagraph("Newpage"));
  11. document.close();
  12. PdfReaderreader=newPdfReader(FILE_DIR+"deletePage.pdf");
  13. reader.selectPages("1,3");
  14. PdfStamperstamp=newPdfStamper(reader,newFileOutputStream(FILE_DIR
  15. +"deletePage2.pdf"));
  16. stamp.close();
  17. reader.close();



11、插入Page

Java代码 收藏代码
  1. FileOutputStreamout=newFileOutputStream(FILE_DIR+"insertPage.pdf");
  2. Documentdocument=newDocument();
  3. PdfWriter.getInstance(document,out);
  4. document.open();
  5. document.add(newParagraph("1page"));
  6. document.newPage();
  7. document.add(newParagraph("2page"));
  8. document.newPage();
  9. document.add(newParagraph("3page"));
  10. document.close();
  11. PdfReaderreader=newPdfReader(FILE_DIR+"insertPage.pdf");
  12. PdfStamperstamp=newPdfStamper(reader,newFileOutputStream(FILE_DIR
  13. +"insertPage2.pdf"));
  14. stamp.insertPage(2,reader.getPageSize(1));
  15. ColumnTextct=newColumnText(null);
  16. ct.addElement(newParagraph(24,newChunk("INSERTPAGE")));
  17. ct.setCanvas(stamp.getOverContent(2));
  18. ct.setSimpleColumn(36,36,559,770);
  19. stamp.close();
  20. reader.close();



12、排序page

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



13、目录

Java代码 收藏代码
  1. //Code1
  2. document.add(newChunk("Chapter1").setLocalDestination("1"));
  3. document.newPage();
  4. document.add(newChunk("Chapter2").setLocalDestination("2"));
  5. document.add(newParagraph(newChunk("Sub2.1").setLocalDestination("2.1")));
  6. document.add(newParagraph(newChunk("Sub2.2").setLocalDestination("2.2")));
  7. document.newPage();
  8. document.add(newChunk("Chapter3").setLocalDestination("3"));
  9. //Code2
  10. PdfContentBytecb=writer.getDirectContent();
  11. PdfOutlineroot=cb.getRootOutline();
  12. //Code3
  13. @SuppressWarnings("unused")
  14. PdfOutlineoline1=newPdfOutline(root,PdfAction.gotoLocalPage("1",false),"Chapter1");
  15. PdfOutlineoline2=newPdfOutline(root,PdfAction.gotoLocalPage("2",false),"Chapter2");
  16. oline2.setOpen(false);
  17. @SuppressWarnings("unused")
  18. PdfOutlineoline2_1=newPdfOutline(oline2,PdfAction.gotoLocalPage("2.1",false),"Sub2.1");
  19. @SuppressWarnings("unused")
  20. PdfOutlineoline2_2=newPdfOutline(oline2,PdfAction.gotoLocalPage("2.2",false),"Sub2.2");
  21. @SuppressWarnings("unused")
  22. PdfOutlineoline3=newPdfOutline(root,PdfAction.gotoLocalPage("3",false),"Chapter3");


iText入门(2012.07.10)

14、Header, Footer

Java代码 收藏代码
  1. PdfWriterwriter=PdfWriter.getInstance(doc,newFileOutputStream(FILE_DIR+"setHeaderFooter.pdf"));
  2. writer.setPageEvent(newPdfPageEventHelper(){
  3. publicvoidonEndPage(PdfWriterwriter,Documentdocument){
  4. PdfContentBytecb=writer.getDirectContent();
  5. cb.saveState();
  6. cb.beginText();
  7. BaseFontbf=null;
  8. try{
  9. bf=BaseFont.createFont(BaseFont.HELVETICA,BaseFont.WINANSI,BaseFont.EMBEDDED);
  10. }catch(Exceptione){
  11. e.printStackTrace();
  12. }
  13. cb.setFontAndSize(bf,10);
  14. //Header
  15. floatx=document.top(-20);
  16. //左
  17. cb.showTextAligned(PdfContentByte.ALIGN_LEFT,
  18. "H-Left",
  19. document.left(),x,0);
  20. //中
  21. cb.showTextAligned(PdfContentByte.ALIGN_CENTER,
  22. writer.getPageNumber()+"page",
  23. (document.right()+document.left())/2,
  24. x,0);
  25. //右
  26. cb.showTextAligned(PdfContentByte.ALIGN_RIGHT,
  27. "H-Right",
  28. document.right(),x,0);
  29. //Footer
  30. floaty=document.bottom(-20);
  31. //左
  32. cb.showTextAligned(PdfContentByte.ALIGN_LEFT,
  33. "F-Left",
  34. document.left(),y,0);
  35. //中
  36. cb.showTextAligned(PdfContentByte.ALIGN_CENTER,
  37. writer.getPageNumber()+"page",
  38. (document.right()+document.left())/2,
  39. y,0);
  40. //右
  41. cb.showTextAligned(PdfContentByte.ALIGN_RIGHT,
  42. "F-Right",
  43. document.right(),y,0);
  44. cb.endText();
  45. cb.restoreState();
  46. }
  47. });
  48. doc.open();
  49. doc.add(newParagraph("1page"));
  50. doc.newPage();
  51. doc.add(newParagraph("2page"));
  52. doc.newPage();
  53. doc.add(newParagraph("3page"));
  54. doc.newPage();
  55. doc.add(newParagraph("4page"));



15、左右文字

Java代码 收藏代码
  1. PdfWriterwriter=PdfWriter.getInstance(document,out);
  2. document.open();
  3. PdfContentBytecanvas=writer.getDirectContent();
  4. Phrasephrase1=newPhrase("Thisisatest!left");
  5. Phrasephrase2=newPhrase("Thisisatest!right");
  6. Phrasephrase3=newPhrase("Thisisatest!center");
  7. ColumnText.showTextAligned(canvas,Element.ALIGN_LEFT,phrase1,10,500,0);
  8. ColumnText.showTextAligned(canvas,Element.ALIGN_RIGHT,phrase2,10,536,0);
  9. ColumnText.showTextAligned(canvas,Element.ALIGN_CENTER,phrase3,10,572,0);



16、幻灯片放映

Java代码 收藏代码
  1. PdfWriterwriter=PdfWriter.getInstance(doc,out);
  2. writer.setPdfVersion(PdfWriter.VERSION_1_5);
  3. writer.setViewerPreferences(PdfWriter.PageModeFullScreen);//全屏
  4. writer.setPageEvent(newPdfPageEventHelper(){
  5. publicvoidonStartPage(PdfWriterwriter,Documentdocument){
  6. writer.setTransition(newPdfTransition(PdfTransition.DISSOLVE,3));
  7. writer.setDuration(5);//间隔时间
  8. }
  9. });
  10. doc.open();
  11. doc.add(newParagraph("1page"));
  12. doc.newPage();
  13. doc.add(newParagraph("2page"));
  14. doc.newPage();
  15. doc.add(newParagraph("3page"));
  16. doc.newPage();
  17. doc.add(newParagraph("4page"));
  18. doc.newPage();
  19. doc.add(newParagraph("5page"));



17、压缩PDF到Zip

Java代码 收藏代码
  1. ZipOutputStreamzip=newZipOutputStream(newFileOutputStream(FILE_DIR+"zipPDF.zip"));
  2. for(inti=1;i<=3;i++){
  3. ZipEntryentry=newZipEntry("hello_"+i+".pdf");
  4. zip.putNextEntry(entry);
  5. Documentdocument=newDocument();
  6. PdfWriterwriter=PdfWriter.getInstance(document,zip);
  7. writer.setCloseStream(false);
  8. document.open();
  9. document.add(newParagraph("Hello"+i));
  10. document.close();
  11. zip.closeEntry();
  12. }
  13. zip.close();


iText入门(2012.07.10)

18、分割PDF

Java代码 收藏代码
  1. FileOutputStreamout=newFileOutputStream(FILE_DIR+"splitPDF.pdf");
  2. Documentdocument=newDocument();
  3. PdfWriter.getInstance(document,out);
  4. document.open();
  5. document.add(newParagraph("1page"));
  6. document.newPage();
  7. document.add(newParagraph("2page"));
  8. document.newPage();
  9. document.add(newParagraph("3page"));
  10. document.newPage();
  11. document.add(newParagraph("4page"));
  12. document.close();
  13. PdfReaderreader=newPdfReader(FILE_DIR+"splitPDF.pdf");
  14. Documentdd=newDocument();
  15. PdfWriterwriter=PdfWriter.getInstance(dd,newFileOutputStream(FILE_DIR+"splitPDF1.pdf"));
  16. dd.open();
  17. PdfContentBytecb=writer.getDirectContent();
  18. dd.newPage();
  19. cb.addTemplate(writer.getImportedPage(reader,1),0,0);
  20. dd.newPage();
  21. cb.addTemplate(writer.getImportedPage(reader,2),0,0);
  22. dd.close();
  23. writer.close();
  24. Documentdd2=newDocument();
  25. PdfWriterwriter2=PdfWriter.getInstance(dd2,newFileOutputStream(FILE_DIR+"splitPDF2.pdf"));
  26. dd2.open();
  27. PdfContentBytecb2=writer2.getDirectContent();
  28. dd2.newPage();
  29. cb2.addTemplate(writer2.getImportedPage(reader,3),0,0);
  30. dd2.newPage();
  31. cb2.addTemplate(writer2.getImportedPage(reader,4),0,0);
  32. dd2.close();
  33. writer2.close();



19、合并PDF

Java代码 收藏代码
  1. PdfReaderreader1=newPdfReader(FILE_DIR+"splitPDF1.pdf");
  2. PdfReaderreader2=newPdfReader(FILE_DIR+"splitPDF2.pdf");
  3. FileOutputStreamout=newFileOutputStream(FILE_DIR+"mergePDF.pdf");
  4. Documentdocument=newDocument();
  5. PdfWriterwriter=PdfWriter.getInstance(document,out);
  6. document.open();
  7. PdfContentBytecb=writer.getDirectContent();
  8. inttotalPages=0;
  9. totalPages+=reader1.getNumberOfPages();
  10. totalPages+=reader2.getNumberOfPages();
  11. java.util.List<PdfReader>readers=newArrayList<PdfReader>();
  12. readers.add(reader1);
  13. readers.add(reader2);
  14. intpageOfCurrentReaderPDF=0;
  15. Iterator<PdfReader>iteratorPDFReader=readers.iterator();
  16. //LoopthroughthePDFfilesandaddtotheoutput.
  17. while(iteratorPDFReader.hasNext()){
  18. PdfReaderpdfReader=iteratorPDFReader.next();
  19. //Createanewpageinthetargetforeachsourcepage.
  20. while(pageOfCurrentReaderPDF<pdfReader.getNumberOfPages()){
  21. document.newPage();
  22. pageOfCurrentReaderPDF++;
  23. PdfImportedPagepage=writer.getImportedPage(pdfReader,pageOfCurrentReaderPDF);
  24. cb.addTemplate(page,0,0);
  25. }
  26. pageOfCurrentReaderPDF=0;
  27. }
  28. out.flush();
  29. document.close();
  30. out.close();



20、Annotation

Java代码 收藏代码
  1. PdfWriterwriter=PdfWriter.getInstance(doc,out);
  2. writer.setLinearPageMode();
  3. doc.open();
  4. doc.add(newParagraph("1page"));
  5. doc.add(newAnnotation("Title","Thisisaannotation!"));
  6. doc.newPage();
  7. doc.add(newParagraph("2page"));
  8. Chunkchunk=newChunk("\u00a0");
  9. chunk.setAnnotation(PdfAnnotation.createText(writer,null,"Title","Thisisaanotherannotation!",false,"Comment"));
  10. doc.add(chunk);
  11. //添加附件
  12. doc.newPage();
  13. doc.add(newParagraph("3page"));
  14. Chunkchunk2=newChunk("\u00a0\u00a0");
  15. PdfAnnotationannotation=PdfAnnotation.createFileAttachment(
  16. writer,null,"Title",null,
  17. "resource/test2.jpg",
  18. "img.jpg");
  19. annotation.put(PdfName.NAME,
  20. newPdfString("Paperclip"));
  21. chunk2.setAnnotation(annotation);
  22. doc.add(chunk2);


iText入门(2012.07.10)

21、插入一个Table

Java代码 收藏代码
  1. PdfPTabletable=newPdfPTable(3);
  2. PdfPCellcell;
  3. cell=newPdfPCell(newPhrase("Cellwithcolspan3"));
  4. cell.setColspan(3);
  5. table.addCell(cell);
  6. cell=newPdfPCell(newPhrase("Cellwithrowspan2"));
  7. cell.setRowspan(2);
  8. table.addCell(cell);
  9. table.addCell("row1;cell1");
  10. table.addCell("row1;cell2");
  11. table.addCell("row2;cell1");
  12. table.addCell("row2;cell2");
  13. document.add(table);



22、表格嵌套

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



23、设置表格宽度

Java代码 收藏代码
  1. PdfPTabletable=newPdfPTable(3);
  2. PdfPCellcell;
  3. cell=newPdfPCell(newPhrase("Cellwithcolspan3"));
  4. cell.setColspan(3);
  5. table.addCell(cell);
  6. cell=newPdfPCell(newPhrase("Cellwithrowspan2"));
  7. cell.setRowspan(2);
  8. table.addCell(cell);
  9. table.addCell("row1;cell1");
  10. table.addCell("row1;cell2");
  11. table.addCell("row2;cell1");
  12. table.addCell("row2;cell2");
  13. //100%
  14. table.setWidthPercentage(100);
  15. document.add(table);
  16. document.add(newParagraph("\n\n"));
  17. //宽度50%居左
  18. table.setHorizontalAlignment(Element.ALIGN_LEFT);
  19. document.add(table);
  20. document.add(newParagraph("\n\n"));
  21. //宽度50%居中
  22. table.setHorizontalAlignment(Element.ALIGN_CENTER);
  23. document.add(table);
  24. document.add(newParagraph("\n\n"));
  25. //宽度50%居右
  26. table.setWidthPercentage(50);
  27. table.setHorizontalAlignment(Element.ALIGN_RIGHT);
  28. document.add(table);
  29. document.add(newParagraph("\n\n"));
  30. //固定宽度
  31. table.setTotalWidth(300);
  32. table.setLockedWidth(true);
  33. document.add(table);



24、设置表格前后间隔

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



25、设置单元格宽度

Java代码 收藏代码
  1. //按比例设置单元格宽度
  2. float[]widths={0.1f,0.1f,0.05f,0.75f};
  3. PdfPTabletable=newPdfPTable(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(newParagraph("\n\n"));
  22. //调整比例
  23. widths[0]=20f;
  24. widths[1]=20f;
  25. widths[2]=10f;
  26. widths[3]=50f;
  27. table.setWidths(widths);
  28. document.add(table);
  29. //按绝对值设置单元格宽度
  30. widths[0]=40f;
  31. widths[1]=40f;
  32. widths[2]=20f;
  33. widths[3]=300f;
  34. Rectangler=newRectangle(PageSize.A4.getRight(72),PageSize.A4.getTop(72));
  35. table.setWidthPercentage(widths,r);
  36. document.add(newParagraph("\n\n"));
  37. document.add(table);



26、设置单元格高度

Java代码 收藏代码
  1. PdfPTabletable=newPdfPTable(2);
  2. PdfPCellcell;
  3. //折行
  4. table.addCell(newPdfPCell(newParagraph("折行",fontZH)));
  5. cell=newPdfPCell(newParagraph("blahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblah"));
  6. cell.setNoWrap(false);
  7. table.addCell(cell);
  8. //不折行
  9. table.addCell(newPdfPCell(newParagraph("不折行",fontZH)));
  10. cell.setNoWrap(true);
  11. table.addCell(cell);
  12. //设置高度
  13. table.addCell(newPdfPCell(newParagraph("任意高度",fontZH)));
  14. cell=newPdfPCell(newParagraph("1.blahblah\n2.blahblahblah\n3.blahblah\n4.blahblahblah\n5.blahblah\n6.blahblahblah\n7.blahblah\n8.blahblahblah"));
  15. table.addCell(cell);
  16. //固定高度
  17. table.addCell(newPdfPCell(newParagraph("固定高度",fontZH)));
  18. cell.setFixedHeight(50f);
  19. table.addCell(cell);
  20. //最小高度
  21. table.addCell(newPdfPCell(newParagraph("最小高度",fontZH)));
  22. cell=newPdfPCell(newParagraph("最小高度:50",fontZH));
  23. cell.setMinimumHeight(50f);
  24. table.addCell(cell);
  25. //最后一行拉长到page底部
  26. table.setExtendLastRow(true);
  27. table.addCell(newPdfPCell(newParagraph("拉长最后一行",fontZH)));
  28. cell=newPdfPCell(newParagraph("最后一行拉长到page底部",fontZH));
  29. table.addCell(cell);
  30. document.add(table);



27、设置单元格颜色

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



28、插入图像

Java代码 收藏代码
  1. Imageimage=Image.getInstance("resource/test2.jpg");
  2. float[]widths={1f,4f};
  3. PdfPTabletable=newPdfPTable(widths);
  4. //插入图片
  5. table.addCell(newPdfPCell(newParagraph("图片测试",fontZH)));
  6. table.addCell(image);
  7. //调整图片大小
  8. table.addCell("Thistwo");
  9. table.addCell(newPdfPCell(image,true));
  10. //不调整
  11. table.addCell("Thisthree");
  12. table.addCell(newPdfPCell(image,false));
  13. document.add(table);



29、设置表头

Java代码 收藏代码
  1. String[]bogusData={"M0065920","SL","FR86000P","PCGOLD",
  2. "119000","9606","2001-08-13","4350","6011648299",
  3. "FLFLMTGP","153","119000.00"};
  4. intNumColumns=12;
  5. //12
  6. PdfPTabledatatable=newPdfPTable(NumColumns);
  7. intheaderwidths[]={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. datatable.addCell("Clock#");
  14. datatable.addCell("TransType");
  15. datatable.addCell("Cusip");
  16. datatable.addCell("LongName");
  17. datatable.addCell("Quantity");
  18. datatable.addCell("FractionPrice");
  19. datatable.addCell("SettleDate");
  20. datatable.addCell("Portfolio");
  21. datatable.addCell("ADPNumber");
  22. datatable.addCell("AccountID");
  23. datatable.addCell("RegRepID");
  24. datatable.addCell("AmtToGo");
  25. datatable.setHeaderRows(1);
  26. //边框
  27. datatable.getDefaultCell().setBorderWidth(1);
  28. //背景色
  29. for(inti=1;i<1000;i++){
  30. for(intx=0;x<NumColumns;x++){
  31. datatable.addCell(bogusData[x]);
  32. }
  33. }
  34. document.add(datatable);



30、分割表格

Java代码 收藏代码
  1. //横向分割
  2. PdfContentBytecb=writer.getDirectContent();
  3. PdfPTabletable=newPdfPTable(10);
  4. for(intk=1;k<=100;++k){
  5. table.addCell("Thenumber"+k);
  6. }
  7. table.setTotalWidth(400);
  8. table.writeSelectedRows(0,5,0,-1,5,700,cb);
  9. table.writeSelectedRows(5,-1,0,-1,210,700,cb);



31、设置单元格留白

Java代码 收藏代码
  1. PdfPTabletable=newPdfPTable(2);
  2. PdfPCellcell;
  3. Paragraphp=newParagraph("Quickbrownfoxjumpsoverthelazydog.Quickbrownfoxjumpsoverthelazydog.");
  4. table.addCell(newPdfPCell(newParagraph("默认",fontZH)));
  5. table.addCell(p);
  6. table.addCell(newPdfPCell(newParagraph("Padding:10",fontZH)));
  7. cell=newPdfPCell(p);
  8. cell.setPadding(10f);
  9. table.addCell(cell);
  10. table.addCell(newPdfPCell(newParagraph("Padding:0",fontZH)));
  11. cell=newPdfPCell(p);
  12. cell.setPadding(0f);
  13. table.addCell(cell);
  14. table.addCell(newPdfPCell(newParagraph("上Padding:0左Padding:20",fontZH)));
  15. cell=newPdfPCell(p);
  16. cell.setPaddingTop(0f);
  17. cell.setPaddingLeft(20f);
  18. table.addCell(cell);
  19. document.add(table);
  20. document.newPage();
  21. table=newPdfPTable(2);
  22. table.addCell(newPdfPCell(newParagraph("没有Leading",fontZH)));
  23. table.getDefaultCell().setLeading(0f,0f);
  24. table.addCell("blahblah\nblahblahblah\nblahblah\nblahblahblah\nblahblah\nblahblahblah\nblahblah\nblahblahblah\n");
  25. table.getDefaultCell().setLeading(14f,0f);
  26. table.addCell(newPdfPCell(newParagraph("固定Leading:14pt",fontZH)));
  27. table.addCell("blahblah\nblahblahblah\nblahblah\nblahblahblah\nblahblah\nblahblahblah\nblahblah\nblahblahblah\n");
  28. table.addCell(newPdfPCell(newParagraph("相对于字体",fontZH)));
  29. table.getDefaultCell().setLeading(0f,1.0f);
  30. table.addCell("blahblah\nblahblahblah\nblahblah\nblahblahblah\nblahblah\nblahblahblah\nblahblah\nblahblahblah\n");
  31. document.add(table);



32、设置单元格边框

Java代码 收藏代码
  1. //没有边框
  2. PdfPTabletable1=newPdfPTable(3);
  3. table1.getDefaultCell().setBorder(PdfPCell.NO_BORDER);
  4. table1.addCell(newParagraph("Cell1"));
  5. table1.addCell(newParagraph("Cell2"));
  6. table1.addCell(newParagraph("Cell3"));
  7. document.add(table1);
  8. //边框粗细颜色
  9. document.newPage();
  10. Rectangleb1=newRectangle(0f,0f);
  11. b1.setBorderWidthLeft(6f);
  12. b1.setBorderWidthBottom(5f);
  13. b1.setBorderWidthRight(4f);
  14. b1.setBorderWidthTop(2f);
  15. b1.setBorderColorLeft(BaseColor.RED);
  16. b1.setBorderColorBottom(BaseColor.ORANGE);
  17. b1.setBorderColorRight(BaseColor.YELLOW);
  18. b1.setBorderColorTop(BaseColor.GREEN);
  19. PdfPTabletable2=newPdfPTable(1);
  20. PdfPCellcell=newPdfPCell(newParagraph("Cell1"));
  21. cell.cloneNonPositionParameters(b1);
  22. table2.addCell(cell);
  23. document.add(table2);



33、PdfPTableEvent

34、PdfPCellEvent

35、PdfPageEventHelper

你可能感兴趣的:(itext)