利用html创建pdf文件

来源:互联网 发布:java 函数缺省参数 编辑:程序博客网 时间:2024/05/19 23:02

创建步骤

先要创建模板文件,将要生成的pdf文件的大体内容定下来,然后根据模板文件填充数据并存储为html文件,最后将html文件转换为pdf文件。
## 生成.html文件 ##
思路:首先要要创建模板文件,就是先要定个大体的框架出来就像盖房子一样先把地基打好,然后调用方法将你要动态添加的数据填充到文件中去。 示例模板如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">          <html xmlns="http://www.w3.org/1999/xhtml">          <head>        <title>askforout.html</title>        <meta http-equiv="content-type" content="text/html; charset=UTF-8"></meta>        <style type="text/css">            body {        font-family: SimSun;        }        table {        word-break:break-all;        border-collapse: collapse;        table-layout: fixed;        font-size: 18px;        width:100%;        text-align: center;        margin-top: 10px;        }        td {        word-break:break-all;        word-wrap : break-word;        padding:20px;        width:100%;        height:80px;        }        </style>        </head>        <body>        <table>        <tr>        <td align="left">        <span style="font-size:18.0pt; font-family:SimSun;float:left;">        关于同意${adept}单位在华召开${actionname}会议的批复函<br/>        </span>        </td>        </tr>        <tr>        <td align="left">        <span style="font-size:18.0pt; font-family:SimSun;float:left;">         ${adept}:<br/>         </span>        </td>        </tr>        <tr>        <td align="left">        <span style="font-size:18.0pt; font-family:SimSun;float:left;">        &nbsp;&nbsp;&nbsp;&nbsp;        你所(中心)        关于        《${actionname}的请示》        收悉。<br/>        </span>        </td>        </tr>        <tr>        <td align="left">        <span style="font-size:18.0pt; font-family:SimSun;float:left;">        经研究,原则同意你所(中心)于${strtime}至<br/>        ${stoptime}在${address}举办${actionname}会议。<br/>        </span>        </td>        </tr>        <tr>        <td align="left">        <span style="font-size:18.0pt; font-family:SimSun;float:left;">        请你单位根据相关外事管理规定和财务管理规定办理有关事宜        认真组织会议和交流活动,并将会后有关情况及时上报我司。<br/>        </span>        </td>        </tr>        <tr>        <td align="left">        <span style="font-size:18.0pt; font-family:SimSun;float:left;">        此复。        </span>        </td>        </tr>        <tr>        <td align="right">        <span style="font-size:18.0pt; font-family:SimSun;">        <br/>        ${approvetime}&nbsp;&nbsp;&nbsp;&nbsp;         </span>        </td>        </tr>        </table>                                  </body>    </html>    &nbsp;&nbsp;&nbsp;&nbsp;        </span>    </td>    </tr>    </table>                              </body></html>

注意:
模板文件要保存为.ftl格式
模版文件必须包含这两句:

!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">     <html xmlns="http://www.w3.org/1999/xhtml">

因为生成pdf文件必须是标准的html文件。
如果有中文则必须定义相对应的字体类型,如下:
font-family:SimSun;不然中文无法显示。

接下来根据模板文件填充动态数据并将模板文件存储为标准的html文件,最后将html文件转换为pdf
文件

kage com.aj.general.util;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.OutputStream;import java.io.Writer;import java.util.Map;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import org.xhtmlrenderer.pdf.ITextFontResolver;import org.xhtmlrenderer.pdf.ITextRenderer;import com.lowagie.text.pdf.BaseFont;import freemarker.template.Configuration;import freemarker.template.DefaultObjectWrapper;import freemarker.template.Template;import freemarker.template.TemplateException;public  class DocUtils {    private  Configuration configuration = null;          Log logger = LogFactory.getLog(DocUtils.class);          //取得根目录路径            String classPath = DocUtils.class.getClassLoader().getResource("/").getPath();           String rootPath=classPath.substring(1,classPath.indexOf("/WEB-INF/classes"))+"/public/font/simsun.ttc"; //这个文件是专门处理中文的          //实例化        private static DocUtils instances=new DocUtils();        public static DocUtils getInstances() {            return instances;        }        public DocUtils() {             configuration = new Configuration();             configuration.setDefaultEncoding("UTF-8");         }        private Template getTemplate(String templateName) throws IOException {                     configuration.setClassForTemplateLoading(this.getClass(), "/com/template");                     Template t = null;                     t = configuration.getTemplate(templateName);                     t.setEncoding("UTF-8");                     return t;                 }        /**         * 为创建pdf文件产生html静态页面         * ***/        public  Boolean CreateHtml(String htmlname, Map dataMap, Writer outhtmls,String srcpath) throws Exception{              try {                  Template t = getTemplate(htmlname);                configuration.setObjectWrapper(new DefaultObjectWrapper());                 //判断html是否已经存在                 String lastname=".html";                 deleteFiles(srcpath,lastname);                 t.process(dataMap, outhtmls);             } catch (IOException e) {                 logger.error(e);                 throw new Exception(e);             } catch (TemplateException e) {                 logger.error(e);                 throw new Exception(e);             } finally {                 try {                     outhtmls.close();                 } catch (IOException e) {                    logger.error(e);                    throw new Exception(e);                }            }            return true;             }          /**           *利用IText将已经生成的静态页面转化为pdf格式         * realpath 项目根目录         * frompath 静态页面路径         * topath 产生pdf批复函的路径         * srcpath 产生word路径           * **/             public Boolean ToPdf(String realpath,String frompath,String topath,String srcpath)throws Exception{                 OutputStream os = new FileOutputStream(topath);                 //判断html是否已经存在                 String lastname=".pdf";                 deleteFiles(srcpath,lastname);                 ITextRenderer renderer = new ITextRenderer();                        String url = new File(frompath).toURI().toURL().toString();                    renderer.setDocument(url);                  // 解决中文支持问题                // System.out.println("-------rootPath:-------"+rootPath+"-------------");                 ITextFontResolver fontResolver = renderer.getFontResolver();                 fontResolver.addFont(realpath, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);                 renderer.layout();                       renderer.createPDF(os);                     os.flush();                   os.close();                   return true;              }}
0 0
原创粉丝点击