html转pdf/图片(免配置-可转在线页面或本地资源)

说明:本程序支持windows32 和64 支持UNIX系统 MAC系统

1、首先安装wkhtmltopdf

下载地址:

官网地址: wkhtmltopdf

github地址 https://github.com/wkhtmltopdf/wkhtmltopdf

2、编写程序,并配置安装的wkhtmltopdf路径

package com.example.demo.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
 
/**
 * 当java调用wkhtmltopdf时,用于获取wkhtmltopdf返回的内容
 */
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); //输出内容
			}
		}catch (IOException e){
			e.printStackTrace();
		}
	}
}
package com.example.demo.utils;

import java.io.File;

public class HtmlToPdf2 {
    //wkhtmltopdf在系统中的路径
    private static final String toPdfTool = "E:\\javasoftware\\htmlToPdf\\wkhtmltopdf\\bin\\wkhtmltopdf.exe";//转图片为wkhtmltopimage.exe

    /**
     * html转pdf
     * @param srcPath html路径,可以是硬盘上的路径,也可以是网络路径
     * @param destPath pdf保存路径
     * @return 转换成功返回true
     */
    public static boolean convert(String srcPath, String destPath){
        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(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();
            System.out.println("生成的pdf路径为:"+destPath);
        }catch(Exception e){
            result = false;
            e.printStackTrace();
        }

        return result;
    }

    public static void main(String[] args) {
        convert("http://news.ynet.com/2021/10/11/3371592t2518.html","f:\\test.pdf");
    }
}

3、调用方法或直接启动测试

注:程序安装包在我的资源中也能找到

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

再写一行代码就下班

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值