java生成pdf方案很多,常用的如下:
1. 利用jacob生成pdf:这种方法调用office的本地方法实现对pdf API的操作,只能在windows平台使用
2. 利用openoffice生成pdf:openoffice是开源软件且能在windows和linux平台下运行
3. itext + flying saucer生成pdf:itext和flying saucer都是免费开源的,且与平台无关,结合css和velocity技术,可以很好的实现。
我们重点介绍第三种方案。它实现的步骤是非常简单的:
1.新建一个ITextRenderer类
2.添加字体
3.设置ITextRenderer的源文档
4.调用layout()方法
5.调用createPdf()方法
6.关闭输出流
代码如下:
1. 利用jacob生成pdf:这种方法调用office的本地方法实现对pdf API的操作,只能在windows平台使用
2. 利用openoffice生成pdf:openoffice是开源软件且能在windows和linux平台下运行
3. itext + flying saucer生成pdf:itext和flying saucer都是免费开源的,且与平台无关,结合css和velocity技术,可以很好的实现。
我们重点介绍第三种方案。它实现的步骤是非常简单的:
1.新建一个ITextRenderer类
2.添加字体
3.设置ITextRenderer的源文档
4.调用layout()方法
5.调用createPdf()方法
6.关闭输出流
代码如下:
- packagecom.hank.pdfhtml;
- /**
- *@authorHank
- *2009-12-30
- */
- importjava.io.File;
- importjava.io.FileNotFoundException;
- importjava.io.FileOutputStream;
- importjava.io.IOException;
- importjava.io.OutputStream;
- importjava.net.MalformedURLException;
- importjava.net.URL;
- importorg.xhtmlrenderer.pdf.ITextFontResolver;
- importorg.xhtmlrenderer.pdf.ITextRenderer;
- importcom.lowagie.text.DocumentException;
- importcom.lowagie.text.pdf.BaseFont;
- publicclassHtml2Pdf{
- privatestaticvoidaddFonts()throwsDocumentException,IOException{
- if(null==renderer){
- return;
- }
- //添加所需的字体
- ITextFontResolverfontResolver=renderer.getFontResolver();
- URLfontsUrl=Html2Pdf.class.getResource("/com/hank/fonts/");//该文件夹下放所需字体文件
- Filefonts=newFile(fontsUrl.getPath());
- File[]fileList=fonts.listFiles();
- for(inti=0;i<fileList.length;i++){
- fontResolver.addFont(fileList[i].getAbsolutePath(),BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);
- }
- }
- publicstaticStringprint2Pdf(StringinputFile){
- Stringurl=null;
- try{
- url=newFile(inputFile).toURI().toURL().toString();
- }catch(MalformedURLExceptione){
- returnnull;
- }
- StringoutputFile=inputFile.substring(0,inputFile.lastIndexOf("."))+".pdf";
- OutputStreamos=null;
- try{
- os=newFileOutputStream(outputFile);
- }catch(FileNotFoundExceptione){
- returnnull;
- }
- ITextRendererrenderer=null;
- try{
- renderer=newITextRenderer();
- }catch(Exceptione){
- returnnull;
- }
- renderer.setDocument(url);
- //解决图片的相对路径问题
- renderer.getSharedContext().setBaseURL("file:/D:/working/HtmlTemp/image/");
- renderer.layout();
- try{
- renderer.createPDF(os);
- }catch(DocumentExceptione){
- returnnull;
- }
- try{
- os.close();
- }catch(IOExceptione){
- returnnull;
- }
- returnoutputFile;
- }
- publicstaticvoidmain(Stringargs[]){
- StringinputFile="D:/working/HtmlTemp/test.html";//必须符合W3C标准
- Html2Pdf.print2Pdf(inputFile);
- }
- }