【PDF】java使用Itext生成pdf文档--详解

我是研究僧i 提交于 2020-01-01 22:20:51
API接口 


一、Itext简介

  1. API地址:javadoc/index.html;如 D:/MyJAR/原JAR包/PDF/itext-5.5.3/itextpdf-5.5.3-javadoc/index.html
  2. 功能:a Free Java-PDF;
  3. 中文支持:iTextAsian.jar,现在高版本Itext不支持语言包。
  4. 使用的版本:iTextpdf-5.0.0.jar, iTextAsian-2.0.jar,或者不用 iTextAsian-2.0.jar,直接使用ttf或ttc字体库


二、Itext API

(一)PDF文档生成的5步

  1. /** 
  2.      * 5步生成一个PDF 
  3.      */  
  4.     public void createPdf() throws Exception {  
  5.         // 1-创建文本对象 Document  
  6.         Document document = new Document(PageSize.A4, 5001505050);  
  7.   
  8.         // 2-初始化 pdf输出对象 PdfWriter  
  9.         PdfWriter.getInstance(document, out);  
  10.   
  11.         // 3-打开 Document  
  12.         document.open();  
  13.   
  14.         // 4-往 Document 添加内容  
  15.         document.add(new Paragraph("Hello! PDF!!!"));  
  16.   
  17.         // 5-关闭 Document  
  18.         document.close();  
  19.     }  
  20. </span>  


(二)文档对象:Document、Rectangle、PageSize

1、 Document — PDF对象

1)构造方法:

①、Document(Rectangle pageSize, float marginLeft, float marginRight, float marginTop,

  float marginBottom):分别指pdf页面大小和内容距离文档边的距离。

②、默认 Document()为:A4,36,36,36,36

2)属性:

①、基本属性:版本(PdfVersionImp)、标题(Title)、作者(Author)、主题(Subject)、关键字(Keywords)、创建者(Creator)等等

②、其他属性:页面空白(Margins和marginLeft各个方位)

3)方法:

①、 add()-添加内容,newPage()-下一页, addDocListener-监听器

② 、getPageNumber()-第几页 ,getPageSize-页面大小 ,

top|left|right|bottom-页面预定义位置,置页眉页脚或者页码时有用,内部调用Rectangle的属性

setJavaScript_onLoad(添加js)等等

  1. // 2-2 横向打印  
  2.         document = new Document(PageSize.A4.rotate());// 横向打印  
  3.         document = new Document(tRectangle.rotate());// 横向打印  
  4.   
  5.         try {  
  6.             // 解析器  
  7.             PdfWriter writer= PdfWriter.getInstance(document, new FileOutputStream("pdf/pdfText.pdf"));  
  8.   
  9.             // 3-为pdf添加属性信息  
  10.             document.addAuthor("作者");  
  11.             document.addTitle("标题");  
  12.             document.addSubject("主题");  
  13.             document.addKeywords("关键字");  
  14.               
  15.             //页边空白    
  16.             document.setMargins(10203040);    
  17.               
  18.             document.open();  
  19.               
  20.             // 4-PDF添加内容  
  21.             document.add(new Paragraph("Hello world"));  
  22.               
  23.               
  24.             // 5-添加Page  
  25.             document.newPage();    
  26. //          writer.setPageEmpty(false);//显示空内容的页  
  27.             writer.setPageEmpty(true);//不会显示空内容的页  
  28.                 
  29.             document.newPage();    
  30.             document.add(new Paragraph("New page"));    
  31.   
  32.             logger.debug("PDF创建结束....");  

2、 Rectangle— 页面对象

1)构造方法:

 Rectangle(final float llx, final float lly, final float urx, final float ury)

 Rectangle(PageSize.A4) -PageSize  封装常用的 Rectangle 

2)属性

①、NO_BORDER-无边框(单元格),left|top|right|bottom

3)方法

①、rotate()-横向打印

②、setBackgroundColor()-背景色, 

setBorder()-边框, 

setBorderColor()-边框颜色

// 1-创建一个pdf文档,document  
  1.         Document document = null;  
  2.         document = new Document();// 默认PageSize.A4, 36, 36, 36, 36  
  3.         document = new Document(PageSize.A4);// 等效于上面的  
  4.         document = new Document(PageSize.A4, 50505050);// PageSize封装了大量常用的Rectangle数据  
  5.   
  6.         // 2-Rectangle(pdf页面)创建Document  
  7.         // 一般是四个参数表示:左下角的坐标和右上角的坐标  
  8.         Rectangle tRectangle = null;  
  9.         tRectangle = PageSize.A4;// PageSize封装了大量常用的Rectangle数据  
  10.         tRectangle = new Rectangle(800600);// 长宽  
  11.         tRectangle = new Rectangle(00800600);// 等于上面  
  12.   
  13.         // 2-1 其他页面属性:不能和PageSize封装的静态一起使用  
  14.         tRectangle.setBackgroundColor(BaseColor.BLACK);// 背景色  
  15.         tRectangle.setBorder(1220);// 边框  
  16.         tRectangle.setBorderColor(BaseColor.BLUE);  
  17.         tRectangle.setBorderWidth(244.2f);  
  18.   
  19.         document = new Document(tRectangle);</span>  

3、综合案例代码:

  1. <span style="font-family:SimSun;">    /** 
  2.      * 页面大小,页面背景色,页边空白,Title,Author,Subject,Keywords 
  3.      *  
  4.      * @throws DocumentException 
  5.      */  
  6.     public void myPDF() throws DocumentException {  
  7.   
  8.         // 1- 页面的属性  
  9.         Rectangle tRectangle = new Rectangle(PageSize.A4); // 页面大小  
  10.         // tRectangle = new Rectangle(0, 0, 800, 600);  
  11.   
  12.         tRectangle.setBackgroundColor(BaseColor.ORANGE); // 页面背景色  
  13.         tRectangle.setBorder(1220);// 边框  
  14.         tRectangle.setBorderColor(BaseColor.BLUE);// 边框颜色  
  15.         tRectangle.setBorderWidth(244.2f);// 边框宽度  
  16.   
  17.         Document doc = new Document(tRectangle);// 定义文档  
  18.         doc = new Document(tRectangle.rotate());// 横向打印  
  19.   
  20.         PdfWriter writer = PdfWriter.getInstance(doc, out);// 书写器  
  21.   
  22.         // PDF版本(默认1.4)  
  23.         writer.setPdfVersion(PdfWriter.PDF_VERSION_1_2);  
  24.   
  25.         // 2-PDF文档属性  
  26.         doc.addTitle("Title@sample");// 标题  
  27.         doc.addAuthor("Author@rensanning");// 作者  
  28.         doc.addSubject("Subject@iText sample");// 主题  
  29.         doc.addKeywords("Keywords@iText");// 关键字  
  30.         doc.addCreator("Creator@iText");// 谁创建的  
  31.   
  32.         // 3-综合属性:  
  33.         doc.setMargins(10203040);// 页边空白  
  34.   
  35.         doc.open();// 打开文档  
  36.         doc.add(new Paragraph("Hello World"));// 添加内容  
  37.   
  38.         // 4-添加下一页  
  39.         doc.newPage();  
  40.         writer.setPageEmpty(true);// fasle-显示空内容的页;true-不会显示  
  41.   
  42.         doc.newPage();  
  43.         doc.add(new Paragraph("New page"));  
  44.   
  45.         doc.close();  
  46.     }  
  47. </span>  

(三)内容对象:

1、中文支持:

1)BaseFont-确认支持中文

2)Font-字体的设置,如颜色,字体,大小等

3)固定用法如下:

[java] view plaic
  1. <span style="font-family:SimSun;">    /** 
  2.      * 支持中文 
  3.      *  
  4.      * @return 
  5.      */  
  6.     public Font getChineseFont() {  
  7.         BaseFont bfChinese;  
  8.         Font fontChinese = null;  
  9.         try {  
  10.             bfChinese = BaseFont.createFont("STSongStd-Light""UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);  
  11.             // fontChinese = new Font(bfChinese, 12, Font.NORMAL);  
  12.             fontChinese = new Font(bfChinese, 12, Font.NORMAL, BaseColor.BLUE);  
  13.         } catch (DocumentException e) {  
  14.             e.printStackTrace();  
  15.         } catch (IOException e) {  
  16.             e.printStackTrace();  
  17.         }  
  18.         return fontChinese;  
  19.   
  20.     }  
  21. }  
  22. </span>  

2、Element接口

1)内容对象基本都实现这个接口。如Chunk、 Phrase、 Paragraph

2)一些有用的方位参数: 

ALIGN_LEFT, ALIGN_CENTER、 ALIGN_RIGHT, ALIGN_JUSTIFIED 。

如设置居中对齐:setAlignment(Element.ALIGN_CENTER)



3、 Chunk

1)块对象: a String, a Font, and some attributes

2)方法:Chunk.NEWLINE-换行,

setUnderline(0.2f, -2f)- 下划线

setTextRise(6)-上浮

  1. <span style="font-family:SimSun;">// 1-Chunk块对象: a String, a Font, and some attributes  
  2.         document.add(new Chunk("中文输出: ", getChineseFont()));  
  3.   
  4.         Chunk tChunk2 = new Chunk("输出的内容", getChineseFont());  
  5.         tChunk2.setBackground(BaseColor.CYAN, 1f, 0.5f, 1f, 1.5f); // 设置背景色  
  6.         tChunk2.setTextRise(6); // 上浮  
  7.         tChunk2.setUnderline(0.2f, -2f); // 下划线  
  8.         document.add(tChunk2);  
  9.   
  10.         document.add(Chunk.NEWLINE); // 新建一行  
  11.         // document.add(new Phrase("Phrase page  :")); //会上浮,不知道原因??</span>

4、 Phrase

1)Phrase短语对象: a List of Chunks with leading

2)方法:add(Element)-添加方法,add(Chunk.NEWLINE)-内部换行

setLeading(14f)-行间距

  1. <span style="font-family:SimSun;">        // 2-Phrase短语对象: a List of Chunks with leading  
  2.         document.add(new Phrase("Phrase page  :"));  
  3.   
  4.         Phrase tPhrase = new Phrase();  
  5.         Chunk name = new Chunk("China");  
  6.         name.setUnderline(0.2f, -2f);  
  7.         tPhrase.add(name);  
  8.         tPhrase.add(Chunk.NEWLINE);// 放在容器中好用  
  9.         tPhrase.add(new Chunk("换行了 :", getChineseFont()));  
  10.         tPhrase.add(new Chunk("chinese"));  
  11.         tPhrase.setLeading(14f);// 行间距  
  12.         document.add(tPhrase);  
  13.   
  14.         // 这边就好用,上面是Chunk,就不好用  
  15.         // 放在段落或短语中又好用  
  16.         document.add(Chunk.NEWLINE);  
  17.   
  18.         Phrase director2 = new Phrase();  
  19.         Chunk name2 = new Chunk("换行了---Japan", getChineseFont());  
  20.         name2.setUnderline(0.2f, -2f);  
  21.         director2.add(name2);  
  22.         director2.add(new Chunk(","));  
  23.         director2.add(new Chunk(" "));  
  24.         director2.add(new Chunk("japanese上浮下", getChineseFont()).setTextRise(3f));  
  25.         director2.setLeading(24);  
  26.         document.add(director2);</span>

5、 Paragraph—(新段落另起一行)

1)段落对象: a Phrase with extra properties and a newline

2)方法:

add(Element)-添加; setLeading(20f)-行间距,一个Paragraph只有一个行间距;

setIndentationLeft()-左缩进, setIndentationRight-右缩进, setFirstLineIndent-首行缩进;

setSpacingBefore-设置上空白, setSpacingAfter(10f)-设置段落下空;

setAlignment(Element.ALIGN_CENTER)-居中对齐;

  1. <span style="font-family:SimSun;">// 3-Paragraph段落对象: a Phrase with extra properties and a newline  
  2.         document.add(new Paragraph("Paragraph page"));  
  3.         Paragraph info = new Paragraph();  
  4.         info.add(new Chunk("China "));  
  5.         info.add(new Chunk("chinese"));  
  6.         info.add(Chunk.NEWLINE); // 好用的  
  7.         info.add(new Phrase("Japan "));  
  8.         info.add(new Phrase("japanese"));  
  9.         info.setSpacingAfter(10f);// 设置段落下空白  
  10.         document.add(info);  
  11.   
  12.         // 段落是比较好用的  
  13.         Paragraph tParagraph = new Paragraph("段落是文章中最基本的单位。内容上它具有一个相对完整的意思;在文章中,段具有换行的标。段是由句子或句群组成的,在文章中用于体现作者的思路发展或全篇文章的层次。有的段落只有一个句子,称为独句段,独句段一般是文章的开头段、结尾段、"  
  14.                 + "过渡段强调段等特殊的段落。多数段落包括不止一个句子或句群,叫多句段。中文段落开头前一般空两个格。", getChineseFont());  
  15.         tParagraph.setAlignment(Element.ALIGN_JUSTIFIED);// 对齐方式  
  16.   
  17.         tParagraph.setIndentationLeft(12);// 左缩进  
  18.         tParagraph.setIndentationRight(12);// 右缩进  
  19.         tParagraph.setFirstLineIndent(24);// 首行缩进  
  20.   
  21.         tParagraph.setLeading(20f);// 行间距  
  22.         tParagraph.setSpacingBefore(5f);// 设置上空白  
  23.         tParagraph.setSpacingAfter(10f);// 设置段落下空白  
  24.         document.add(tParagraph);  
  25.   
  26.         // 每个新的段落会另起一行  
  27.         tParagraph = new Paragraph("新的段落", getChineseFont());  
  28.         tParagraph.setAlignment(Element.ALIGN_CENTER);// 居中  
  29.         document.add(tParagraph);  
  30. </span>  

综合代码如下:

  1. <span style="font-family:SimSun;">    /** 
  2.      * 添加内容 插入Chunk, Phrase, Paragraph, List 
  3.      *  
  4.      * @author ShaoMin 
  5.      * @throws Exception 
  6.      */  
  7.     public void addContent() throws Exception {  
  8.         Document document = new Document(PageSize.A4);  
  9.         PdfWriter.getInstance(document, out);  
  10.         document.open();  
  11.   
  12.         // 1-Chunk块对象: a String, a Font, and some attributes  
  13.         document.add(new Chunk("中文输出: ", getChineseFont()));  
  14.   
  15.         Chunk tChunk2 = new Chunk("输出的内容", getChineseFont());  
  16.         tChunk2.setBackground(BaseColor.CYAN, 1f, 0.5f, 1f, 1.5f); // 设置背景色  
  17.         tChunk2.setTextRise(6); // 上浮  
  18.         tChunk2.setUnderline(0.2f, -2f); // 下划线  
  19.         document.add(tChunk2);  
  20.   
  21.         document.add(Chunk.NEWLINE); // 新建一行  
  22.         // document.add(new Phrase("Phrase page  :")); //会上浮,不知道原因??  
  23.   
  24.         // 2-Phrase短语对象: a List of Chunks with leading  
  25.         document.add(new Phrase("Phrase page  :"));  
  26.   
  27.         Phrase tPhrase = new Phrase();  
  28.         Chunk name = new Chunk("China");  
  29.         name.setUnderline(0.2f, -2f);  
  30.         tPhrase.add(name);  
  31.         tPhrase.add(Chunk.NEWLINE);// 放在容器中好用  
  32.         tPhrase.add(new Chunk("换行了 :", getChineseFont()));  
  33.         tPhrase.add(new Chunk("chinese"));  
  34.         tPhrase.setLeading(14f);// 行间距  
  35.         document.add(tPhrase);  
  36.   
  37.         // 这边就好用,上面是Chunk,就不好用  
  38.         // 放在段落或短语中又好用  
  39.         document.add(Chunk.NEWLINE);  
  40.   
  41.         Phrase director2 = new Phrase();  
  42.         Chunk name2 = new Chunk("换行了---Japan", getChineseFont());  
  43.         name2.setUnderline(0.2f, -2f);  
  44.         director2.add(name2);  
  45.         director2.add(new Chunk(","));  
  46.         director2.add(new Chunk(" "));  
  47.         director2.add(new Chunk("japanese上浮下", getChineseFont()).setTextRise(3f));  
  48.         director2.setLeading(24);  
  49.         document.add(director2);  
  50.   
  51.         // 3-Paragraph段落对象: a Phrase with extra properties and a newline  
  52.         document.add(new Paragraph("Paragraph page"));  
  53.         Paragraph info = new Paragraph();  
  54.         info.add(new Chunk("China "));  
  55.         info.add(new Chunk("chinese"));  
  56.         info.add(Chunk.NEWLINE); // 好用的  
  57.         info.add(new Phrase("Japan "));  
  58.         info.add(new Phrase("japanese"));  
  59.         info.setSpacingAfter(10f);// 设置段落下空白  
  60.         document.add(info);  
  61.   
  62.         // 段落是比较好用的  
  63.         Paragraph tParagraph = new Paragraph("段落是文章中最基本的单位。内容上它具有一个相对完整的意思;在文章中,段具有换行的标。段是由句子或句群组成的,在文章中用于体现作者的思路发展或全篇文章的层次。有的段落只有一个句子,称为独句段,独句段一般是文章的开头段、结尾段、"  
  64.                 + "过渡段强调段等特殊的段落。多数段落包括不止一个句子或句群,叫多句段。中文段落开头前一般空两个格。", getChineseFont());  
  65.         tParagraph.setAlignment(Element.ALIGN_JUSTIFIED);// 对齐方式  
  66.   
  67.         tParagraph.setIndentationLeft(12);// 左缩进  
  68.         tParagraph.setIndentationRight(12);// 右缩进  
  69.         tParagraph.setFirstLineIndent(24);// 首行缩进  
  70.   
  71.         tParagraph.setLeading(20f);// 行间距  
  72.         tParagraph.setSpacingBefore(5f);// 设置上空白  
  73.         tParagraph.setSpacingAfter(10f);// 设置段落下空白  
  74.         document.add(tParagraph);  
  75.   
  76.         // 每个新的段落会另起一行  
  77.         tParagraph = new Paragraph("新的段落", getChineseFont());  
  78.         tParagraph.setAlignment(Element.ALIGN_CENTER);// 居中  
  79.         document.add(tParagraph);  
  80.   
  81.         document.close();  
  82.     }  
  83. </span>

6、Image继承自Rectangle

1)、初始化:Image img = Image.getInstance("source/imag/bage.png")

2)、方法:

setAlignment(Image.LEFT)-对齐方式,setBorder(Image.BOX)-边框,

setBorderWidth(10)-边框宽度,setBorderColor(BaseColor.WHITE)-边框颜色,  

scaleToFit(1000, 72)-大小,setRotationDegrees(-30)-旋转,

setAbsolutePosition()-绝对位置

<span style="font-family:SimSun;">        // 图片Image对象  
  1.         Image img = Image.getInstance("source/imag/bage.png");  
  2.         img.setAlignment(Image.LEFT);  
  3.         img.setBorder(Image.BOX);  
  4.         img.setBorderWidth(10);  
  5.         img.setBorderColor(BaseColor.WHITE);  
  6.         img.scaleToFit(100072);// 大小  
  7.         img.setRotationDegrees(-30);// 旋转  
  8.         document.add(img);</span>

7、Anchor(锚点、超链接) 、Chapter、Section(目录章节)等:

  1. <span style="font-family:SimSun;">    /** 
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!