基于Chrome实现将url转为pdf

67 阅读1分钟

基于Chrome实现将url转为pdf

安装chrome浏览器

在网上找了很多文章尝试下来效果都是不怎么样,后面想到谷歌浏览器的打印网页的功能,于是想着使用谷歌浏览器实现这个效果。最终的效果,,,不错。

指令

chrome.exe  --virtual-time-budget=5000 --disable-gpu --no-sandbox --print-to-pdf=D:\aaa\1\1\qqq.pdf --javascriptEnabled=true --no-pdf-header-footer http://47.92.153.124/

--virtual-time-budget=5000

这个参数比较重要,这其实就是让网页加载一下,防止打印的时候网页数据还没有完全加载好,导致数据不全,这个参数具体的值可以根据情况调整

--print-to-pdf

这个参数是目标pdf文件存储的位置

javascriptEnabled=true

设置允许执行js代码

--no-pdf-header-footer 禁用掉pdf的页头和页脚否则pdf上会显示网页的url

127.0.0.1

最后一项就是需要转的url

代码

/**
 * html转pdf工具类
 */
public class HtmlToPdfUtils {
​
    /**
     * html转pdf
     *
     * @param chromePath    chrome路径
     * @param targetPdfPath pdf保存路径
     * @param url           html路径
     * @return 转换结果
     */
    public static String convertHtml2Pdf(String chromePath, String targetPdfPath, String url) {
        String[] command = {
                chromePath,
                "--headless",
                "--virtual-time-budget=5000",
                "--disable-gpu",
                "--no-sandbox",
                "--no-pdf-header-footer",
                "--print-to-pdf=" + targetPdfPath,
                "--javascriptEnabled=true",
                url
        };
​
        try {
            Process process = Runtime.getRuntime().exec(command);
            process.waitFor();
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        }
        return "success";
    }
}