将html文档转成pdf

(1)使用场景:在项目中使用到了合同,只有在合同的头部,是不相同的。在合同的主体部分都是相同的,因此就把他放到了模板(html文件)里面。

  在用户线上签约完成之后,可以将pdf版的合同下载。

(2)需求:忧伤可以看出,首先需要把html文件转成pdf。其次需要将pdf下载。

(3)code:

  1)在上午就顺利的找了一段合适的代码,成功的跑起来了,在参数里面需要传递一个html文件,因为我测试的是一个类似于hello word的简单的html,所以就侥幸成功了。可能是找的过程太顺利了!!!结果将html换成项目中的文件后死后调不出来,百度才知道,这种方式只能将标准格式的html转成pdf。这里所谓的标准,,标准到表态。。此方法,弃~【但是怎么也是费劲调出来的,就也贴出来吧】、

原文地址:https://blog.csdn.net/m15732622413/article/details/78456961?utm_source=blogxgwz1

package com.jeeplus.common.utils;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import com.jeeplus.core.web.BaseController;
import com.lowagie.text.DocumentException;
import com.lowagie.text.pdf.BaseFont;
import com.mitchellbosecke.pebble.PebbleEngine;
import com.mitchellbosecke.pebble.template.PebbleTemplate;

/**
 * 下载PDF文件
 * 
 * @author xiao
 *
 */
@Controller

public class PDFUtil extends BaseController {
    private static final String FONTPATH = "C:/WINDOWS/Fonts/simsun.ttc";// 支持中文字体(放哪里都行)

    public static String exportPdf(String htmlpath, HttpServletResponse response, HttpServletRequest request)
            throws Exception {
        String html = htmlpath;
        String pdf = html2Pdf(html, "D:/测试2.pdf");
        // 如果在控制类有response对象可以直接转换后的pdf文件,在控制类方法需要return null
        downloadFile(pdf, "我的PDF文件.pdf", response, request);
        // return null;
        System.out.println("create html success! 文件存放路径:" + pdf);
        return "导出成功!";
    }

    /**
     * html转换pdf文件 注:支持中文,目前iText只支持上面FONTPATH定义的这种字体,所以html文件中也需要用样式设置字体为:SimSun
     * htmlPath 需要转换的html源文件 pdfPath 转换后pdf文件存放地址
     */
    public static String html2Pdf(String htmlPath, String pdfPath) {
        try {
            String url = new File(htmlPath).toURI().toURL().toString();
            OutputStream output = new FileOutputStream(pdfPath);
            ITextRenderer renderer = new ITextRenderer();
            renderer.setDocument(url);

            // 解决中文支持问题(html的中文必须用SimSun字体,Java只能支持这1种字体)
            ITextFontResolver fontResolver = renderer.getFontResolver();
            fontResolver.addFont(FONTPATH, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            renderer.layout();
            renderer.createPDF(output);
            output.close();
            
            return pdfPath;
        } catch (MalformedURLException e) {
            e.printStackTrace();
            return null;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        } catch (DocumentException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 文件下载-支持中文名称
     * 
     * @param          sourcePath下载文件全路径(F:/test.pdf)
     * @param          fileName需要生成的下载文件名(HTML转PDF测试.pdf)
     * @param response
     * @throws Exception
     */
    public static void downloadFile(String sourcePath, String fileName, HttpServletResponse response,
            HttpServletRequest request) throws Exception {
        // 读到流中
        InputStream inStream = null;
        try {
            inStream = new FileInputStream(sourcePath);// 文件的存放路径
            // 设置输出的格式
            response.reset();
            String name = new String((fileName));
            response.addHeader("Content-Disposition",
                    "attachment; filename=" + new String(name.getBytes(), "iso-8859-1"));
            // 循环取出流中的数据
            byte[] b = new byte[100];
            int len;
            while ((len = inStream.read(b)) > 0) {
                response.getOutputStream().write(b, 0, len);
            }
            response.getOutputStream().flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                inStream.close();
                response.getOutputStream().close();
                // 删除源文件
                /*
                 * File sourceFile = new File(sourcePath); if(sourceFile.exists()){
                 * sourceFile.delete(); }
                 */
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/excellencesy/p/9813725.html