A. itext pdf文档生成
在日常开发过程中,若是想要把java中的某个对象中的内容,迅衡按某种排列方式输出到PDF中,有几种方式,此处只缺稿使用了itextpdf的方式。
itext pdf 文档
在gradle中伏昌孝只需要加入
新建一个Document对象,再定义PdfWriter,把document中的内容写入HelloWorld.pdf文件。
在添加内容到document之前需要执行document.open()才可以。
document可以添加Paragraph、 PdfPTable 等元素。
这两种方法中第一种不支持设置Leading为100,第二种方法支持设置Leading为100。除了在初始化Paragraph时可以设置Leading,还可以调用setLeading()来设置,第一个参数是固定的行间距,第二个参数是行间距为行高的倍数。
B. itext 生成 PDF(一)
itext 生成 PDF(二)
官网: http://itextsupport.com/apidocs/itext5/latest/
博文: https://blog.csdn.net/u010154380/article/details/78087663
博文: https://blog.csdn.net/u013129932/article/details/43889705
iText是著名的开放源码的站点sourceforge一个项目,是用于生成PDF文档的一个java类库。通过iText不仅可以生成PDF或rtf的文档,而且可以将XML、Html文件转化为PDF文件。
项目要使用iText,必须引入jar包。才能使用,maven依赖如下:
<dependency><groupId>com.itextpdf</groupId><artifactId>itextpdf</artifactId><version>5.5.10</version></dependency>
输出中文,还要引入下面itext-asian.jar包:
<dependency><groupId>com.itextpdf</groupId><artifactId>itext-asian</artifactId><version>5.2.0</version></dependency>
设置pdf文件密码,还要引入下面bcprov-jdk15on.jar包:
<dependency><groupId>org.bouncycastle</groupId><artifactId>bcprov-jdk15on</artifactId><version>1.54</version></dependency>
iText常用类
com.itextpdf.text.Document:这是iText库中最常用的类,它代表了一个pdf实例。如果你需要从零开始生成一个PDF文件,你需要使用这个Document类。首先创建(new)该实例,然后打开(open)它,并添加(add)内容,最后关闭(close)该实例,即可生成一个pdf文件。
com.itextpdf.text.Paragraph:表示一个缩进的文本段落,在段落中,你可以设置对齐方式,缩进,段落前后间隔等
com.itextpdf.text.Chapter:表示PDF的一个章节,他通过一个Paragraph类型的标题和整形章数创建
com.itextpdf.text.Font:这个类包含了所有规范好的字体,包括family of font,大小,样式和颜色,所有这些字体都被声明为静态常量
com.itextpdf.text.List:表示一个列表;
com.itextpdf.text.Anchor:表示一乱返磨个锚,类似于HTML页面的链接。
com.itextpdf.text.pdf.PdfWriter:当这个PdfWriter被添加到PdfDocument后,所有添哗斗加世铅到Document的内容将会写入到与文件或网络关联的输出流中。
com.itextpdf.text.pdf.PdfReader:用于读取PDF文件;
iText使用
创建一个简单的pdf文件,如下:
packagecom.hd.pdf;importjava.io.FileNotFoundException;importjava.io.FileOutputStream;importcom.itextpdf.text.Document;importcom.itextpdf.text.DocumentException;importcom.itextpdf.text.Paragraph;importcom.itextpdf.text.pdf.PdfWriter;publicclassTestPDFDemo1{publicstaticvoidmain(String[]args)throws FileNotFoundException,DocumentException{// 1.新建document对象Document document=newDocument();// 2.建立一个书写器(Writer)与document对象关联,通过书写器(Writer)可以将文档写入到磁盘中。// 创建 PdfWriter 对象 第一个参数是对文档对象的引用,第二个参数是文件的实际名称,在该名称中还会给出其输出路径。PdfWriter writer=PdfWriter.getInstance(document,newFileOutputStream("C:/Users/H__D/Desktop/test.pdf"));// 3.打开文档document.open();// 4.添加一个内容段落document.add(newParagraph("Hello World!"));// 5.关闭文档document.close();}}
打开文件
851491-20161209165247147-746087588.png
PDF中创建表格
publicstaticvoidmain(String[]args)throws DocumentException,FileNotFoundException{//创建文件Document document=newDocument();//建立一个书写器PdfWriter writer=PdfWriter.getInstance(document,newFileOutputStream("C:/Users/H__D/Desktop/test4.pdf"));//打开文件document.open();//添加内容document.add(newParagraph("HD content here"));// 3列的表.PdfPTable table=newPdfPTable(3);table.setWidthPercentage(100);// 宽度100%填充table.setSpacingBefore(10f);// 前间距table.setSpacingAfter(10f);// 后间距List<PdfPRow>listRow=table.getRows();//设置列宽float[]columnWidths={1f,2f,3f};table.setWidths(columnWidths);//行1PdfPCell cells1[]=newPdfPCell[3];PdfPRow row1=newPdfPRow(cells1);//单元格cells1[0]=newPdfPCell(newParagraph("111"));//单元格内容cells1[0].setBorderColor(BaseColor.BLUE);//边框验证cells1[0].setPaddingLeft(20);//左填充20cells1[0].setHorizontalAlignment(Element.ALIGN_CENTER);//水平居中cells1[0].setVerticalAlignment(Element.ALIGN_MIDDLE);//垂直居中cells1[1]=newPdfPCell(newParagraph("222"));cells1[2]=newPdfPCell(newParagraph("333"));//行2PdfPCell cells2[]=newPdfPCell[3];PdfPRow row2=newPdfPRow(cells2);cells2[0]=newPdfPCell(newParagraph("444"));//把第一行添加到集合listRow.add(row1);listRow.add(row2);//把表格添加到文件中document.add(table);//关闭文档document.close();//关闭书写器writer.close();}
打开图片
851491-20161209165247147-746087588.png
给PDF文件设置文件属性,例如:
publicstaticvoidmain(String[]args)throws FileNotFoundException,DocumentException{//创建文件Document document=newDocument();//建立一个书写器PdfWriter writer=PdfWriter.getInstance(document,newFileOutputStream("C:/Users/H__D/Desktop/test2.pdf"));//打开文件document.open();//添加内容document.add(newParagraph("Some content here"));//设置属性//标题document.addTitle("this is a title");//作者document.addAuthor("H__D");//主题document.addSubject("this is subject");//关键字document.addKeywords("Keywords");//创建时间document.addCreationDate();//应用程序document.addCreator("hd.com");//关闭文档document.close();//关闭书写器writer.close();}
打开文件
851491-20161209165247147-746087588.png
PDF中添加图片
publicstaticvoidmain(String[]args)throws DocumentException,IOException{//创建文件Document document=newDocument();//建立一个书写器PdfWriter writer=PdfWriter.getInstance(document,newFileOutputStream("C:/Users/H__D/Desktop/test3.pdf"));//打开文件document.open();//添加内容document.add(newParagraph("HD content here"));//图片1Image image1=Image.getInstance("C:/Users/H__D/Desktop/IMG_0109.JPG");//设置图片位置的x轴和y周image1.setAbsolutePosition(100f,550f);//设置图片的宽度和高度image1.scaleAbsolute(200,200);//将图片1添加到pdf文件中document.add(image1);//图片2Image image2=Image.getInstance(newURL("http://static.cnblogs.com/images/adminlogo.gif"));//将图片2添加到pdf文件中document.add(image2);//关闭文档document.close();//关闭书写器writer.close();}
打开图片
851491-20161209165247147-746087588.png
PDF中创建列表
publicstaticvoidmain(String[]args)throws DocumentException,FileNotFoundException{//创建文件Document document=newDocument();//建立一个书写器PdfWriter writer=PdfWriter.getInstance(document,newFileOutputStream("C:/Users/H__D/Desktop/test5.pdf"));//打开文件document.open();//添加内容document.add(newParagraph("HD content here"));//添加有序列表List orderedList=newList(List.ORDERED);orderedList.add(newListItem("Item one"));orderedList.add(newListItem("Item two"));orderedList.add(newListItem("Item three"));document.add(orderedList);//关闭文档document.close();//关闭书写器writer.close();}
打开文件
851491-20161209180029726-1168732515.png
PDF中设置样式/格式化输出,输出中文内容,必须引入itext-asian.jar
publicstaticvoidmain(String[]args)throws DocumentException,IOException{//创建文件Document document=newDocument();//建立一个书写器PdfWriter writer=PdfWriter.getInstance(document,newFileOutputStream("C:/Users/H__D/Desktop/test6.pdf"));//打开文件document.open();//中文字体,解决中文不能显示问题BaseFont bfChinese=BaseFont.createFont("STSong-Light","UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);//蓝色字体Font blueFont=newFont(bfChinese);blueFont.setColor(BaseColor.BLUE);//段落文本Paragraph paragraphBlue=newParagraph("paragraphOne blue front",blueFont);document.add(paragraphBlue);//绿色字体Font greenFont=newFont(bfChinese);greenFont.setColor(BaseColor.GREEN);//创建章节Paragraph chapterTitle=newParagraph("段落标题xxxx",greenFont);Chapter chapter1=newChapter(chapterTitle,1);chapter1.setNumberDepth(0);Paragraph sectionTitle=newParagraph("部分标题",greenFont);Section section1=chapter1.addSection(sectionTitle);Paragraph sectionContent=newParagraph("部分内容",blueFont);section1.add(sectionContent);//将章节添加到文章中document.add(chapter1);//关闭文档document.close();//关闭书写器writer.close();}
打开图片
![
851491-20161209180029726-1168732515.png
]
851491-20161209165247147-746087588.png
给PDF文件设置密码,需要引入bcprov-jdk15on.jar包:
publicstaticvoidmain(String[]args)throws DocumentException,IOException{// 创建文件Document document=newDocument();// 建立一个书写器PdfWriter writer=PdfWriter.getInstance(document,newFileOutputStream("C:/Users/H__D/Desktop/test8.pdf"));//用户密码String userPassword="123456";//拥有者密码String ownerPassword="hd";writer.setEncryption(userPassword.getBytes(),ownerPassword.getBytes(),PdfWriter.ALLOW_PRINTING,PdfWriter.ENCRYPTION_AES_128);// 打开文件document.open();//添加内容document.add(newParagraph("password !!!!"));// 关闭文档document.close();// 关闭书写器writer.close();}
打开图片
851491-20161209165247147-746087588.png
给PDF文件设置权限
publicstaticvoidmain(String[]args)throws DocumentException,IOException{// 创建文件Document document=newDocument();// 建立一个书写器PdfWriter writer=PdfWriter.getInstance(document,newFileOutputStream("C:/Users/H__D/Desktop/test9.pdf"));// 只读权限writer.setEncryption("".getBytes(),"".getBytes(),PdfWriter.ALLOW_PRINTING,PdfWriter.ENCRYPTION_AES_128);// 打开文件document.open();// 添加内容document.add(newParagraph("password !!!!"));// 关闭文档document.close();// 关闭书写器writer.close();}
读取/修改已有的PDF文件
publicstaticvoidmain(String[]args)throwsDocumentException,IOException{//读取pdf文件PdfReaderpdfReader=newPdfReader("C:/Users/H__D/Desktop/test1.pdf");//修改器PdfStamperpdfStamper=newPdfStamper(pdfReader,newFileOutputStream("C:/Users/H__D/Desktop/test10.pdf"));Imageimage=Image.getInstance("C:/Users/H__D/Desktop/IMG_0109.JPG");image.scaleAbsolute(50,50);image.setAbsolutePosition(0,700);for(inti=1;i<=pdfReader.getNumberOfPages();i++){PdfContentBytecontent=pdfStamper.getUnderContent(i);content.addImage(image);}pdfStamper.close();}
itext 生成 PDF(二)
链接:https://www.jianshu.com/p/20d4905383b4
C. 怎样用iText读取pdf文件
用iText读取pdf文件举例: (1)在Eclipse中新建一个Java工程。 (2)下载相应的iText-5.0.2.jar并放到对应的lib目录下。在工程坦宏枝中创建包并创建测试类,该类包含一个inspect方法用于从一个PDF中获取文本,它接受两个参数,分别是PDF文件路径和输出流,指定要提取的PDF文件的路径和读取PDF所用的输出流,比如:PDF路径为E://text.pdf。然后调用iText提供的PdfReader类和PdfTextExtractor类,将PDF格式的文本提取出来并写入txt文件中。部分代码如下: import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintWriter; import com.itextpdf.text.DocumentException; import com.itextpdf.text.pdf.PdfReader; import com.itextpdf.text.pdf.parser.PdfTextExtractor; public class PDF { /** The resulting text file with info about a PDF. */ public static final String RESULT = "d:/ceshi.txt";//存放由pdf转换成txt文件的路径。 /** * Main method. * @param args no arguments needed * @throws DocumentException * @throws IOException */ public static void main(String[] args) throws DocumentException, IOException { PrintWriter writer = new PrintWriter(new FileOutputStream(RESULT));//txt文件写入流 String string = "E:/text.pdf";//pdf文件路径 inspect(writer,string); //调用读取方法 writer.close(); } /** * Inspect a PDF file and write the info to a txt file * @param writer Writer to a text file * @param filename Path to the PDF file * @throws IOException */ public static void inspect(PrintWriter writer, String filename) throws IOException { PdfReader reader = new PdfReader(filename); //读取pdf所使用的输让敏出流 int num = reader.getNumberOfPages();//获得页数 String content = ""; //存放读取出的绝携文档内容 for (int i = 1; i < num; i++) { content += PdfTextExtractor.getTextFromPage(reader, i); //读取第i页的文档内容 } writer.write(content);//写入文件内容 writer.flush(); } }
D. Itextpdf 给pdf加密跟限制权限怎么解决
方法一:如果文档做保护时没有设置密码,找 acrobat pro设置为允许打印就可以了,如果设置了密码,就只能用暴力破解软件破解了,如果密码比较长就很难破解出来
方法二,用带OCR功能的转换器,比如abbyy fine reader、solid pdf converter进行转换,转换为word文档就可以打印了,但严重依赖于图片的扫描质量,另外公式、图表比较多的也比较难识别;
方法三:1)如果不是什么重要文件,网络中可以找到的很多的话,建议下载别的类似PDF文件试试,虽然PDF可能会出现以上原作者限制的情况,但并不是很多数,因此如果方便,建议重新查找类似内容PDF文件再打印。
2)如果是该文件很难找,则也是有办法的,不过我们需要借助一款软件:PDFSpliter。
PDFSpliter是一款十分热门的软件,主要功能是将多页大PDF,拆分成多个单页小PDF格式,并且可以可设置多个监测文件夹,自动批量转换。
破解pdf文件不能打印的解决办法如下:首先打开PDFSpliter软件,找到工具栏的“pdf合并”,打开无法打印的pdf文件,点击“打开”,之后点击“开始”合并。
等待PDF文件合并之后,我们将合并后的新文件另存为一个桌面,建议放在桌面上,之后再到桌面上找到该文件即可,之后我们去打印这个合并后的PDF文件会发现已经不受版权等口令限制,可以正常打印了,有兴趣的朋友不妨参考下。
其实这里用到是PDF文件合并工具,由于原始文件因为版权问题,原作者对文档进行诸如修改与打印限制,导致无法正常打印,不过我们借助专业的PDF文件合并软件,进行合并一下即可解决此类问题,当然大家也可以使用pdf recover、Alt PDF Password Recovery等工具来实现。
E. 如何运用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 addProcer()
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);
F. 使用Itext Doc怎么转换为PDF
用itext可以直接生成pdf或者rtf(doc),编程亩腊枯实迅洞现,生局物成的要转换需要用软件,比如Solid.Converter.PDF.Professional.v3.0 有绿色版
G. 如何利用iText文档转换为PDF文件
可以使用虚拟打印机来处理:
方法一:使用虚拟打印机pdf factory即可,而且其他格式文件只要回是能够打印,选答择这个虚拟打印机,都可以做成PDF文件,很简单实用;
方法二:用其他虚拟打印机转成PDF文件。
方法三:使用专门的转换软件,把文件转成PDF文件。
H. 如何运用Java组件itext生成pdf
iText是著名开放源码的站点一个项目,是用于生成PDF文档的一个java类库。通过iText不仅可以生成PDF或rtf的文档,而且可以将XML、Html文件转化为PDF文件。
使用如下:
1、首先下载 JAR 包 : itext-2.0.8.jar core-render.jar
2、创建一个html页面
<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<htmlxmlns="http://www.w3.org/1999/xhtml">
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8"/>
<title>pdf</title>
</head>
<body>
这是html内容
</body>
</html>
3、编写java代码
publicclassPDFUtil{
publicvoidcreatePdf()throwsException{
StringinputFile="index.html";
Stringurl=newFile(inputFile).toURI().toURL().toString();
StringoutputFile="index.pdf";
System.out.println(url);
OutputStreamos=newFileOutputStream(outputFile);
org.xhtmlrenderer.pdf.ITextRendererrenderer=newITextRenderer();
renderer.setDocument(url);
//step3解决中文支持
org.xhtmlrenderer.pdf.ITextFontResolverfontResolver=renderer.getFontResolver();
fontResolver.addFont("c:/Windows/Fonts/simsun.ttc",BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);
renderer.layout();
renderer.createPDF(os);
os.close();
System.out.println("createpdfdone!!");
}
publicstaticvoidmain(String[]args)throwsException{
Appapp=newApp();
app.createPdf();
}
}
这样就可以完成一个简单PDF生成功能了。
I. itext生成word文档方法
从事程序员职业的朋友可能都会遇到类似情况,经常需要将一个表格导出成word来供客户打印,这个解决问题的方法可以用itext生成word文档方法来实现。当然用excel导出也可以实现,但是如果表格主要是文字信息的话使用word文档更合适。
需要的jar包:iTextAsian.jar,iText-rtf-2.1.3.jar,iText-2.1.3.jar;
参考代码:
response.addHeader("Content-disposition", "attachment;filename="" + new String("信息处理表.doc".getBytes("gb2312"), "ISO8859-1"));
String letrId = request.getParameter("letrId");
// 创建word文档,并设置纸张的大小
com.lowagie.text.Document document = new com.lowagie.text.Document(PageSize.A4);
try{
RtfWriter2.getInstance(document,"e:123.doc");
document.open();
Fontf=newFont();
Stringtopic="处理反馈表";
Paragraphp=newParagraph(topic,newFont(Font.NORMAL,18,Font.BOLDITALIC,newColor(0,0,0)));伏悄裂
p.setAlignment(1);
document.add(p);
//设置中文字体
BaseFontbfFont=BaseFont.createFont("STSongStd-Light","UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);
//创建有三列的表格
Tabletable=newTable(3);
table.setBorderWidth(1);
table.setBorderColor(Color.BLACK);
table.setPadding(0);
table.setSpacing(0);
//添加表头的元素
Cellcell=newCell(title);//单元格
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setHeader(运乱true);
cell.setColspan(3);//设置表格为三列
cell.setRowspan(2);//设置表格为2行
table.addCell(cell);
table.endHeaders();//表头结束
cell=newCell("时间:"缺闭);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(cell);
cell=newCell(newParagraph((vl.getLetrDate())。toString()));
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setColspan(2);
table.addCell(cell);
cell=newCell("重要程度:");
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(cell);
cell=newCell(newParagraph((vl.getImptLevel())。toString()));
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setColspan(2);
table.addCell(cell);
//测试1
cell=newCell("测试1:");
cell.setRowspan(5);//当前单元格占两行,纵向跨度
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(cell);
table.addCell("姓名:");
table.addCell(vl.getPernName());
table.addCell("性别:");
table.addCell(vl.getPernSex());
table.addCell("公司:");
table.addCell(vl.getPernUnit());
table.addCell("职务:");
table.addCell(vl.getPernPost());
table.addCell("地址:");
table.addCell(vl.getPernAddress());
//测试2
cell=newCell("测试2:");
cell.setRowspan(4);//当前单元格占两行,纵向跨度
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(cell);
table.addCell("姓名:");
table.addCell(vl.getWrirName());
table.addCell("单位:");
table.addCell(vl.getWrirOrganization());
table.addCell("性别:");
table.addCell(vl.getWrirSex());
table.addCell("电话:");
table.addCell(vl.getWrirTnur());
//简要内容
cell=newCell("简要内容:");
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(cell);
cell=newCell(newParagraph(vl.getLetrNote()));
cell.setColspan(2);
table.addCell(cell);
//测试3
cell=newCell("测试3:");
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(cell);
cell=newCell(newParagraph(vl.getDeptVerifyOpinion()));
cell.setColspan(2);
table.addCell(cell);
//测试4
cell=newCell("测试4:");
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(cell);
cell=newCell(newParagraph(vl.getChargeVerifyOpinion()));
cell.setColspan(2);
table.addCell(cell);
//测试5
cell=newCell("测试5:");
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(cell);
cell=newCell(newParagraph(vl.getHandleContent()));
cell.setColspan(2);
table.addCell(cell);
document.add(table);
document.add(newParagraph(""));
document.close();
}catch(FileNotFoundExceptione){
e.printStackTrace();
}catch(DocumentExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}
在word中可以按照你所要求的格式,利用itext的table、cell、图片等“画”出想要的文档格式,然后再将数据往其中填充;如果想要将报表导出成pdf格式的,用itext也可以很轻松的实现。
J. 使用itext对pdf操作后,为什么生成pdf文件变大了
检查下有没有document.newPage()使得把数据放到下一页了。
如果没有,那就需要分析代码。但是换种思路也能解决你问题:
把数据作为附件一,附件二等形式生成在pdf的最后,那样就没人关注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);