把html页面转换为pdf

把html页面转换为pdf

这个玩意需要专门的软件去转,有点不喜欢。

1.下载安装软件

http://wkhtmltopdf.org/downloads.html
在这里插入图片描述
在windows测试选这个就行了。

2.写主类
public class WkhtmlTopdf {
    /**
     * wkhtmltopdf 在系统中的路径
     */
    private static final String toPdfTool = "C:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltopdf.exe";
    public static void main(String[] args) {
        Date date = new Date();
        System.out.println("开始执行………………");
        String fileName = String.valueOf(date.getTime()) + ".pdf";
        //要转换的HTML页面
        String srcPath = "https://blog.csdn.net/m0_37635053";
        //目的文件夹
        String destPath = "C:\\Users\\test\\Desktop\\workspace\\filetest";
        convert(srcPath,  destPath+ File.separator + fileName);
        System.out.println("执行完成……………………");
    }
    /**
     * html转pdf
     *
     * @param srcPath  html路径,可以是硬盘上的路径,也可以是网络路径
     * @param destPath pdf保存路径
     * @return 转换成功返回true
     */
    public static boolean convert(String srcPath, String destPath) {
        File file = new File(destPath);
        File parentFile = file.getParentFile();
        if (!parentFile.exists()) {
            parentFile.mkdirs();
        }
   
        StringBuilder sb = new StringBuilder();
        sb.append(toPdfTool);
        //设置页面上边距 (default 10mm)
        sb.append("  --margin-right 0  ");
        //设置页面上边距 (default 10mm)
        sb.append("  --margin-left 0  ");
        sb.append(" --javascript-delay 30000 ");
        sb.append(" --load-error-handling ignore ");
        sb.append(" --dpi 180 ");
        sb.append(" --page-size A4");
        sb.append(" --debug-javascript ");
        sb.append(srcPath);
        sb.append(" ");
        sb.append(destPath);
        boolean result = true;
        try {
            Process pro = Runtime.getRuntime().exec(sb.toString());
            HtmlToPdfInterceptor error = new HtmlToPdfInterceptor(pro.getErrorStream());
            HtmlToPdfInterceptor output = new HtmlToPdfInterceptor(pro.getInputStream());
            error.start();
            output.start();
            pro.waitFor();

        } catch (Exception e) {
            result = false;
            e.printStackTrace();
        }
        return result;
    }
}
3.写配置类
public class HtmlToPdfInterceptor extends Thread {
    private InputStream is;

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

    @Override
    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()=========="+line.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

这样就可以了

发布了67 篇原创文章 · 获赞 12 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/m0_37635053/article/details/104017089