java 中实现HTML 生成pdf

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/liiuijkiuu/article/details/54691889

JAVA 中生成pdf 的方法很多,iText是一个生成PDF文档的开源Java库。但是用iText生成pdf,有时候很难控制页面的样式。听说flying-saucer 可以对样式进行简单的支持。由于项目需要,用flying-saucer 体验 了一把,感觉还不错。生成pdf 的整体思路:1.利用freemaker 将模版和数据整合成html 2.利用flying-saucer将生成的html 转换pdf .不废话上代码
1.项目需要引入的包
这里写图片描述
2.书写利用freemarker 生成html 的html 生成器

package com.jscredit.zxypt.freemaker;

import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;

import com.jscredit.zxypt.utils.ResourceLoader;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;


//html 的生成器

public class HtmlGenerator {


    public static void main(String[] args) throws Exception { 

          // classpath 中模板路径
           String temp = "temple/overseaAssistance.html";
          // classpath 路径
           String outputFileClass = ResourceLoader.getPath("");
           System.out.println(outputFileClass);
           String ss = new File(outputFileClass).getParentFile().getParent();
           System.out.println(ss);

          /* String htmlStr = HtmlGenerator.generate(template, variables);
           System.out.println(htmlStr);*/

            // 生成pdf路径
            //outputFile = outputFile == null ? new File(outputFileClass).getParentFile().getParent()+ "/tmp/"+ System.currentTimeMillis() + ".pdf" : outputFile;



        // 生成pdf路径
          /* OutputStream out = new FileOutputStream(outputFile);
           PdfDocumentGenerator.pdfgenerate(htmlStr, out);*/
      } 
     /**    
     * 
     * 根据上面的main 方法抽出的通用方法
     * 传入模版路径 和数据生成html 返回html 的内容
     * template 模版的路径 variables数据
     */
      public static String generate(String template, Map<String,Object> variables) throws IOException, TemplateException{

            Configuration config = FreemarkerConfiguration.getConfiguation();
            //Template tp = configuration.getTemplate("overseaAssistance.html");
            Template tp = config.getTemplate(template);
            StringWriter stringWriter = new StringWriter();  
            BufferedWriter writer = new BufferedWriter(stringWriter);  
            tp.setEncoding("UTF-8");  
            tp.process(variables, writer);  
            String htmlStr = stringWriter.toString();
            writer.flush();  
            writer.close();
            return htmlStr;
      } 
}

3.书写生成pdf 的生成器

package com.jscredit.zxypt.freemaker;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.xhtmlrenderer.pdf.ITextRenderer;

import com.jscredit.zxypt.utils.ResourceLoader;
import com.lowagie.text.pdf.BaseFont;

import freemarker.template.TemplateException;



//pdf的生成器
public class PdfDocumentGenerator {

    private final static Logger logger = Logger.getLogger(PdfDocumentGenerator.class);

    private final static HtmlGenerator htmlGenerator;
    static {
        htmlGenerator = new HtmlGenerator();
    }


    /*
     * 
     * 根据html的内容生成pdf 
     * 
     */
    public static void pdfgenerate(String htmlContent, String outputFile)throws Exception{
            OutputStream out = null;

            DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            Document doc = builder.parse(new ByteArrayInputStream(htmlContent.getBytes("UTF-8")));
            ITextRenderer iTextRenderer = new ITextRenderer();
            // classpath 路径
            String outputFileClass = ResourceLoader.getPath("");
             //添加字体,以支持中文
            iTextRenderer.getFontResolver().addFont(outputFileClass+"fronts/arialuni.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            iTextRenderer.getFontResolver().addFont(outputFileClass+"fronts/SIMSUN.TTC", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            File f = new File(outputFile);
            if (f != null && !f.getParentFile().exists()) {
                f.getParentFile().mkdir();
            }
            out = new FileOutputStream(outputFile);
            iTextRenderer.setDocument(doc, null);
            iTextRenderer.layout();
            iTextRenderer.createPDF(out);
            out.close();
    }

    /*
     * 
     * 对上面的方法再进行封装
     * 
     */
    public boolean generate(String template, Map<String,Object> variables,String outputFile) throws IOException, TemplateException{

            String htmlContent = this.htmlGenerator.generate(template,variables);
            System.out.println("+++++++++"+htmlContent);//打印出html 的内容方便查看是否是html 的时候已经出现乱码
            try {
                this.pdfgenerate(htmlContent, outputFile);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return true;
    }
}

4.书写freemarker的基本配置

package com.jscredit.zxypt.freemaker;

import java.io.File;
import java.io.IOException;

import com.jscredit.zxypt.utils.ResourceLoader;

import freemarker.template.Configuration;



/*
 * freemaker 的配置
 */

public class FreemarkerConfiguration {


    private static Configuration config = null;

    /**
     * 获取 FreemarkerConfiguration
     * 
     * @Title: getConfiguation
     * @Description:
     * @return
     */
    public static synchronized Configuration getConfiguation() {
        if (config == null) {
            setConfiguation();
        }
        return config;
    }

    /**
     * 设置 配置
     * @Title: setConfiguation
     * @Description: 
     */
    private static void setConfiguation() {
        config = new Configuration();
        String path = ResourceLoader.getPath("");
        System.out.println(">>>>>>>>>>>>>>>>>>>"+path);
        try {
            config.setDirectoryForTemplateLoading(new File(path));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



}

5.书写获取资源的resources工具类

package com.jscredit.zxypt.utils;

import java.net.URL;

//获取项目资源的工具类

public class ResourceLoader {

    public static String CLASS_PATH_PREFIX ="classpath:";



     /**
       * classpath中获取资源
       * @Title: getResource
       * @Description: classpath中获取资源
       * @param resource
       * @return
       */

     public static URL getResource(String resource) {
            ClassLoader classLoader = null;
            classLoader = Thread.currentThread().getContextClassLoader();
            return classLoader.getResource(resource);
          } 


     /**
       *  classpath 中搜索路径
       * @Title: getPath
       * @Description: 
       * @param resource
       * @return
       */
     public static String getPath(String resource){
          if(resource!=null){
              if(resource.startsWith(CLASS_PATH_PREFIX)){
                  resource = getPath("")+resource.replaceAll(CLASS_PATH_PREFIX, "");
              }
          }
          URL url = getResource(resource);
          if(url==null)
              return null;
          return url.getPath().replaceAll("%20", " ");
      }


     /**
       * 
       * @Title: getPath
       * @Description: 
       * @param resource
       * @param clazz
       * @return
       */
      public static String getPath(String resource,Class clazz){
          URL url = getResource(resource, clazz);
          if(url==null)
              return null;
          return url.getPath().replaceAll("%20", " ");
      }

      /**
       * 指定class中获取资源
       * @Title: getResource
       * @Description: 指定class中获取资源
       * @param resource
       * @param clazz
       * @return
       */
      public static URL getResource(String resource,Class clazz){
          return clazz.getResource(resource);
      }




}

这样就可以轻松实现Java 的html转pdf 了。附上生成 的效果图:
这里写图片描述
另外需要jar 的可以再我博客里面去下载

猜你喜欢

转载自blog.csdn.net/liiuijkiuu/article/details/54691889
今日推荐