JAVA中將html轉換成pdf


  前言

  本文是采用了wkhtmltopdf插件的方式進行將html轉換成pdf的,首先需要下載該插件,並進行安裝(注意區分系統),此處提供windows64的安裝包,本文中也是采用此安裝包來實現,其他系統的同學可以自行到官網去下載對應系統的安裝包,此處不贅述,順道給出大家下載地址。

windows下載地址:https://pan.baidu.com/s/1eD0NJQymnWgnmPIkBt4Rcg      提取碼:dcj7

官網下載地址:https://wkhtmltopdf.org/

  第一步:

下載成功后,安裝插件並記錄安裝的路徑

  第二步:

copy我的代碼

HtmlToPdf類:
import java.io.File;

public class HtmlToPdf {

    //    wkhtmltopdf在系統中的路徑
    private static final String toPdfTool = "D:\\soft\\wkhtmltopdf\\bin\\wkhtmltopdf.exe";

    /**
     * html轉pdf
     *
     * @param srcPath  html路徑,可以是硬盤上的路徑,也可以是網絡路徑
     * @param destPath pdf保存路徑
     * @return 轉換成功返回true
     */
    public static boolean convert(String srcPath, String destPath,String toPdfTool){
        File file = new File(destPath);
        File parent = file.getParentFile();
        //如果pdf保存路徑不存在,則創建路徑
        if(!parent.exists()){
            parent.mkdirs();
        }
        StringBuilder cmd = new StringBuilder();
        cmd.append(toPdfTool);
        cmd.append(" ");
        cmd.append(" --header-line");//頁眉下面的線
        cmd.append(" --margin-top 3cm ");//設置頁面上邊距 (default 10mm)
        // cmd.append(" --header-html file:///"+WebUtil.getServletContext().getRealPath("")+FileUtil.convertSystemFilePath("\\style\\pdf\\head.html"));// (添加一個HTML頁眉,后面是網址)
        cmd.append(" --header-spacing 5 ");// (設置頁眉和內容的距離,默認0)
        //cmd.append(" --footer-center (設置在中心位置的頁腳內容)");//設置在中心位置的頁腳內容
        //cmd.append(" --footer-html file:///"+WebUtil.getServletContext().getRealPath("")+FileUtil.convertSystemFilePath("\\style\\pdf\\foter.html"));// (添加一個HTML頁腳,后面是網址)
        cmd.append(" --footer-line");//* 顯示一條線在頁腳內容上)
        cmd.append(" --footer-spacing 5 ");// (設置頁腳和內容的距離)
        cmd.append(srcPath);
        cmd.append(" ");
        cmd.append(destPath);
        boolean result = true;
        try{
            Process proc = Runtime.getRuntime().exec(cmd.toString());
            HtmlToPdfInterceptor error = new HtmlToPdfInterceptor(proc.getErrorStream());
            HtmlToPdfInterceptor output = new HtmlToPdfInterceptor(proc.getInputStream());
            error.start();
            output.start();
            proc.waitFor();
        }catch(Exception e){
            result = false;
            e.printStackTrace();
        }

        return result;
    }
    public static void main(String[] args) {
        String sourcePath = "https://baike.baidu.com/item/%E5%BC%A0%E4%B8%B9%E5%B3%B0/3740983?fr=aladdin";
        HtmlToPdf.convert(sourcePath, "D:\\testpdf.pdf",toPdfTool);
        System.out.println("ojbk");
    }


}
HtmlToPdfInterceptor類:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class HtmlToPdfInterceptor extends Thread {
    private InputStream is;

    public HtmlToPdfInterceptor(InputStream is){
        this.is = is;
    }

    public void run(){
        try{
            InputStreamReader isr = new InputStreamReader(is, "utf-8");
            BufferedReader br = new BufferedReader(isr);
            String line = null;
            while ((line = br.readLine()) != null) {
                System.out.println(line.toString()); //輸出內容
            }
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}

 至此,大功告成,so easy!!!此插件可以生產本地頁面,在線頁面,以及頁面代碼哈。

 


免責聲明!

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



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