Java利用wkhtmltopdf 实现Html转PDF,IMAGE【非常好用】

Java利用wkhtmltopdf 实现Html转PDF,IMAGE【非常好用】,第1张

Java利用wkhtmltopdf 实现Html转PDF,IMAGE【非常好用】

前言:java实现html转pdf 是非常困难的,网上很多种方式对比了下很多坑,,效果非常不理想

通过wkhtmltopdf 实现效果非常完美,可以html转pdf,也可以转图片。

wkhtmltopdf 工具

官网链接:wkhtmltopdf 

 

windos版本

        自行下载对应版本,解压后目录如下

C:tomssoftwkhtmltoxbin>wkhtmltopdf.exe  file:///C:/Users/jijun.tang/Desktop/b.html  C:Usersjijun.tangDesktopd1.pdf

通过exe 调用b.html文件转换成d1.pdf

 docker安装
FROM 自己的基础进行
#需要root不然安装会提示无权限
USER root
COPY test-SNAPSHOT.jar /data/webapps
#自行下载linux版本的放在工程中 wkhtmltox-0.12.6-1.centos7.x86_64.rpm
COPY target/classes/wkhtmltox-0.12.6-1.centos7.x86_64.rpm /data/wkhtmltox/
WORKDIR /data/wkhtmltox/
RUN yum -y install fontconfig libX11 libXext libXrender libjpeg openssl xorg-x11-fonts-75dpi xorg-x11-fonts-Type1
RUN rpm -ivh wkhtmltox-0.12.6-1.centos7.x86_64.rpm
#安装字体不然pdf会乱码
RUN yum groupinstall Fonts -y

 

import lombok.extern.slf4j.Slf4j;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;


@Slf4j
public class PdfUtils {

    //public static final String toPdfTool = "C:\toms\soft\wkhtmltox\bin\wkhtmltopdf.exe";
    public static final String toPdfTool = "wkhtmltopdf";
    
    public static boolean convert(String toPdfTool, String srcPath, String destPath) {
        StringBuilder cmd = new StringBuilder();
        cmd.append(toPdfTool);
        cmd.append(" ");
        cmd.append("  --header-line");//页眉下面的线
        cmd.append("  --header-center 这里是页眉这里是页眉这里是页眉这里是页眉 ");//页眉中间内容
        cmd.append(" --header-spacing 10 ");//    (设置页眉和内容的距离,默认0)
        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 InputStream getFile(String content, String srcPath, String destPath) {
        try {
            Files.write(Paths.get(srcPath), content.getBytes(BrainConstants.UTF8));
            File destPathFile = new File(destPath);
            File parent = destPathFile.getParentFile();
            //如果pdf保存路径不存在,则创建路径
            if (!parent.exists()) {
                parent.mkdirs();
            }
            PdfUtils.convert(PdfUtils.toPdfTool, srcPath, destPath);
            FileInputStream fileInputStream = new FileInputStream(destPath);
            if(destPathFile.exists()){
                destPathFile.delete();
            }
            return fileInputStream;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    
    public static void download(InputStream stream, String fileName, HttpServletResponse response) {
        try (BufferedInputStream bufin = new BufferedInputStream(stream);
             OutputStream outputStream = response.getOutputStream()) {
            response.setContentType("application/x-msdownload");
            response.setHeader("Content-Disposition", "attachment;filename="" + URLEncoder.encode(fileName, "utf-8") + """);
            byte[] temp = new byte[1024];
            int size = 0;
            while ((size = bufin.read(temp)) != -1) {
                outputStream.write(temp, 0, size);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

 

@GetMapping("/dowlodPdf")
@ApiOperation(value = "下载pdf", notes = "下载pdf")
public void dowlodPdf( HttpServletResponse response) {
        //把需要导出的pfd内容放入str
        StringBuffer str = new StringBuffer();
        InputStream stream = PdfUtils.getFile(str.toString(), srcPath, destPath);
        PdfUtils.download(stream,title.concat(".pdf"),response);
}

 希望该笔记对同学们有用,如果过程中有什么问题欢迎给我留言,记得多关注点赞哟

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5681368.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存