將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();
            }
        }
    }
}

 (4)在網上看到了這個比較,很清晰  原文:https://blog.csdn.net/huyuyang6688/article/details/79710704?utm_source=blogxgwz0

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM