首页 > 其他分享 >使用Wkhtmltopdf导出PDF

使用Wkhtmltopdf导出PDF

时间:2024-01-18 11:45:54浏览次数:19  
标签:WkhtmltopdfDemo String filePath Wkhtmltopdf 导出 add command new PDF

Wkhtmltopdf是什么?引用官网的一句话

wkhtmltopdf and wkhtmltoimage are open source (LGPLv3) command line tools to render HTML into PDF and various image formats using the Qt WebKit rendering engine. These run entirely "headless" and do not require a display or display service.

为什么要用这个工具?

项目需要每个月自动在后台生成PDF报告存储到文件服务器,不能使用前端生成PDF的方法,所以找到了这个工具。

下载安装:https://wkhtmltopdf.org/downloads.html

​ Windows安装直接下一步到最后就可以。安装之后要配置环境变量,在path中加入C:\Program Files\wkhtmltopdf\bin根据自己的安装目录。然后就可以在运行命令,打开cmd:

C:\Users\Administrator>wkhtmltopdf https://www.baidu.com C:\Users\Administrator\Desktop\demo.pdf
Loading pages (1/6)
Counting pages (2/6)
Resolving links (4/6)
Loading headers and footers (5/6)
Printing pages (6/6)
Done

此时桌面就会生成一个百度首页的PDF文件。

命令格式

wkhtmltopdf [GLOBAL OPTION]... [OBJECT]... <output file>

常用的参数选项

  • --cookie 设置访问网页时的cookie,value 需要进行url编码(可重复使用此参数指定多个cookie)
  • --javascript-delay 延迟一定的毫秒,等待javascript执行完成(默认值是200)
  • --debug-javascript Show javascript debugging output(默认是不开启的)

更多参数选项参考官方文档

问题

​ 有的web页面导出的PDF文件内容不全,可以延长JavaScript执行等待时间。但是有的web页面怎么延长都还是内容缺失,甚至生成空白页,目前没搞明白什么原因导致的。

最后给一段参考demo代码

package com.company.project.demo;

import javax.servlet.http.Cookie;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;

public class WkhtmltopdfDemo implements Runnable {

    private int consId = 1;

    // wkhtmltopdf工作目录
    public static final String WKHTMLTOPDF_WORKDIR = "C:\\Program Files\\wkhtmltopdf\\bin";
    // wkhtmltopdf启动程序
    public static final String WKHTMLTOPDF_PROGRAM = "C:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltopdf.exe";
    // 生成pdf存储路径
    public static final String FILE_PATH = "C:\\Users\\Administrator\\Desktop\\test";

    public boolean processTool(ArrayList<String> command) {
        ProcessBuilder processBuilder = new ProcessBuilder(command);
        processBuilder.directory(new File(WkhtmltopdfDemo.WKHTMLTOPDF_WORKDIR));
        processBuilder.redirectErrorStream(true);
        try {
            Process process = processBuilder.start();
            assert process.getInputStream().read() == -1;
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                System.out.println("cmd" + line);
            }
            bufferedReader.close();
            process.waitFor();
            if (process.exitValue() != 0) {
                System.out.println("非正常结束");
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public static String createFileDirectory(String filePath) {
        File file = new File(filePath);
        File parentFile = file.getParentFile();
        if (!parentFile.exists()) {
            parentFile.mkdirs();
        }
        return filePath;
    }

    public boolean wkhtmltopdfTool(String htmlURL, String filePath, Cookie[] cookies) {
        ArrayList<String> command = new ArrayList<>();
        command.add(WkhtmltopdfDemo.WKHTMLTOPDF_PROGRAM);
        for (Cookie cookie : cookies) {
            String value = cookie.getValue();
            command.add("--cookie");
            command.add(cookie.getName());
            command.add((value == null || "".equals(value.trim()) ? "null" : value));
        }
//        command.add("--javascript-delay");
//        command.add("5000");
//        command.add("--debug-javascript");
        command.add(htmlURL);
        command.add(filePath);
        boolean result = new WkhtmltopdfDemo().processTool(command);
        return result;
    }

    public boolean wkhtmltopdfTool(String htmlURL, String filePath) {
        ArrayList<String> command = new ArrayList<>();
        command.add(WkhtmltopdfDemo.WKHTMLTOPDF_PROGRAM);
//        command.add("--javascript-delay");
//        command.add("5000");
//        command.add("--debug-javascript");
        command.add(htmlURL);
        command.add(filePath);
        boolean result = new WkhtmltopdfDemo().processTool(command);
        return result;
    }

    public byte[] htmltopdfByte(String htmlURL, String fileName) {
        String filePath = WkhtmltopdfDemo.FILE_PATH + "\\" + fileName;
        byte[] bytes = null;
        WkhtmltopdfDemo wkhtmltopdfDemo = new WkhtmltopdfDemo();
        boolean result = wkhtmltopdfDemo.wkhtmltopdfTool(htmlURL, WkhtmltopdfDemo.createFileDirectory(filePath));
        if (result) {
            File file = new File(filePath);
            try {
                FileInputStream inputStream = new FileInputStream(file);
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                byte[] b = new byte[1024];
                int n;
                while ((n = inputStream.read(b)) != -1) {
                    outputStream.write(b, 0, n);
                }
                if (inputStream != null) {
                    inputStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
                bytes = outputStream.toByteArray();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                file.delete();
            }
        }
        return bytes;
    }

    public File htmltopdfFile(String htmlURL, String fileName) {
        String filePath = WkhtmltopdfDemo.FILE_PATH + "\\" + fileName;
        File file = null;
        boolean result = new WkhtmltopdfDemo().wkhtmltopdfTool(htmlURL, WkhtmltopdfDemo.createFileDirectory(filePath));
        if (result) {
            file = new File(filePath);
        }
        return file;
    }

    @Override
    public void run() {
        WkhtmltopdfDemo wkhtmltopdfDemo = new WkhtmltopdfDemo();
        String htmlURL = "\"https://www.baidu.com\"";
        while (consId > 0) {
            String fileName = "test" + consId + ".pdf";
            String filePath = WkhtmltopdfDemo.FILE_PATH + "\\" + fileName;
            wkhtmltopdfDemo.wkhtmltopdfTool(htmlURL, WkhtmltopdfDemo.createFileDirectory(filePath));
            consId--;
        }
    }

    public static void main(String[] args) {
        WkhtmltopdfDemo wkhtmltopdfDemo = new WkhtmltopdfDemo();
        String htmlURL = "\"https://www.baidu.com\"";
        String fileName = "test.pdf";
        String filePath = WkhtmltopdfDemo.FILE_PATH + "\\" + fileName;
        wkhtmltopdfDemo.wkhtmltopdfTool(htmlURL, WkhtmltopdfDemo.createFileDirectory(filePath));
    }
}

标签:WkhtmltopdfDemo,String,filePath,Wkhtmltopdf,导出,add,command,new,PDF
From: https://www.cnblogs.com/sealrui/p/17972167

相关文章

  • 用ArcGIS模型构建器生成、导出Python转换空间坐标系的代码
      本文介绍在ArcMap软件中,通过创建模型构建器(ModelBuilder),导出地理坐标系与投影坐标系之间相互转换的Python代码的方法。  在GIS领域中,矢量、栅格图层的投影转换是一个经常遇见的问题;而由于地理坐标系与投影坐标系各自都分别具有很多不同的种类,且二者之间相互转换涉及到很多......
  • Stirling-PDF docker安装
    有时候pdf文件需要处理,有个开源工具。https://github.com/Stirling-Tools/Stirling-PDF docker安装1、下载dockerpullfrooodle/s-pdf:latest2、安装dockerrun-d\-p8380:8080\-v/Users/xxxx/Documents/Stirling-PDF/data/:/usr/share/tesseract-ocr/4.......
  • 记录--为什么 export 导出一个字面量会报错,而使用 export default 就不会报错?
    这里给大家分享我在网上总结出来的一些知识,希望对大家有所帮助核心其实总的来说就是export导出的是变量的句柄(或者说符号绑定、近似于C语言里面的指针,C++里面的变量别名),而exportdefault导出的是变量的值。需要注意的是:模块里面的内容只能在模块内部修改,模块外部只能使......
  • 「云渲染科普」blender如何导出序列帧与序列帧动画
    blender是不少人都在使用的动画建模软件,工具免费使用,且支持多种渲染器插件,能够为用户制作出完整得动画人物、场景建模,那么blender中去如何导出序列帧与序列帧动画呢?下面一起来看看吧。一、blender怎么导出序列帧1、先设置输出格式为:PNG,在点击ctrlF12渲染动画,等待序列帧图像......
  • PDF转图片-itextpdf-java源码
    提供PDF文件转图片的工具类。电子签章过程中存在着在网页上对签署文件进行预览、指定签署位置、文件签署等操作,由于图片在浏览器上的兼容性和友好性优于PDF文件,所以一般在网页上进行电子签章时,会先将PDF文件转换成图片,展示给用户。用户在页面上确定好签署位置,并进行签署时,后端服......
  • PDF转图片-itextpdf-java源码
    提供PDF文件转图片的工具类。电子签章过程中存在着在网页上对签署文件进行预览、指定签署位置、文件签署等操作,由于图片在浏览器上的兼容性和友好性优于PDF文件,所以一般在网页上进行电子签章时,会先将PDF文件转换成图片,展示给用户。用户在页面上确定好签署位置,并进行签署时,后......
  • 【专题】2023中国电商营销趋势及增长策略研究报告PDF合集分享(附原数据表)
    全球电商市场在疫情后持续发展,其中,中国市场占据了半壁江山,对全球电商格局产生了重大影响。在中国,三至五线城市的城镇人口众多,约占总城镇人口的65%。随着移动互联网的普及,这些城市构成了纵深市场,其用户规模正在稳步增长。据数据显示,近7.2亿的目标用户占据了整个市场的52%,成为移动互......
  • 【专题】2023年B2B医疗企业营销转型白皮书报告PDF合集分享(附原数据表)
    随着医药企业营销数字化转型的深入,将面临更多的内外数据和数据源。这些问题导致数据断层,难以有效利用,使企业忙于处理数据问题,无暇关注深层业务需求。因此,尽管高呼“数据驱动”,却难以提供切实有效的解决方案和洞察。医疗企业数字化营销的挑战医疗企业在数字化营销过程中面临多方面的......
  • 【专题】2023双碳背景下新型电力系统的应用创新-电网洞察白皮书报告PDF合集分享(附原数
    为实现碳达峰、碳中和目标,构建清洁低碳、安全高效的能源体系成为首要任务。清洁电力作为能源转型的关键,对于保障中国能源安全具有重要意义。为适应新能源的大规模接入,新型电力系统应运而生,以确保电力系统的安全可靠运行。为确保电力系统的稳定运行,提升其灵活性至关重要,这需要各环......
  • 【专题】全球医疗器械报告 2023报告PDF合集分享(附原数据表)
    在全球范围内,医疗器械行业的检验中心和诊断解决方案、牙科、医疗辅助设备等细分领域的企业表现尤为出色。这些企业在新冠疫情期间或是受益于有利的市场环境,或是凭借创新主导的高增长市场策略取得了显著的优势。相反,手术器械细分市场在疫情期间受到了一定的冲击,由于手术量减少,医疗......