sumatraPDF + wkhtmltopdf 实现标签的远程打印

557 阅读2分钟

说明

要实现将标签数据打印到远程的一台打印机上,并且打印机会有多个客户端人员进行使用,在这种情况下,单独使用一台windows服务器,奖所有的打印机进行链接,开发对应的程序在服务器上调用选择的打印机进行标签打印。

使用技术

使用 wkhtmltopdf 将项目生成的标签html 转化成pdf 文件,使用 sumatraPDF 程序将生成的pdf 文件自动调用选择的打印机进行打印。

详细说明

wkhtmltopdf 使用

下载 wkhtmltopdf 程序 wkhtmltopdf.org/downloads.h…

在java 中使用 Runtime.getRuntime().exec(microsoft_print_to_pdf); 进行调用windows 服务器中可执行程序。

具体程序如下

public void generatePdf(String url, String tmpFile) {
    String printStr = "%s %s %s";
    String microsoft_print_to_pdf = String.format(printStr, wkhtmltopdfPath, url, tmpFile);
    log.info("打印执行的参数 => {}", microsoft_print_to_pdf);
    Process exec = Runtime.getRuntime().exec(microsoft_print_to_pdf);

    new Thread(() -> {
        String read = IoUtil.read(exec.getInputStream(), Charset.forName("GBK"));
        log.info("log success -> {}",read);
    }).start();
    new Thread(() -> {
        String read = IoUtil.read(exec.getErrorStream(), Charset.forName("GBK"));
        log.info("log error -> {}",read);
    }).start();
    exec.waitFor();
}

程序对应的输入参数为 网页的url 和 生成pdf 文件的临时地址
wkhtmltopdfPath 参数为 windows系统中 wkhtmltopdf 的路径

sumatraPDF 使用

sumatraPDF 的作用可以将 pdf 进行静默调用windows 上的打印机程序,从而自动打印

同样 sumatraPDF 程序下载地址 www.sumatrapdfreader.org/download-fr…

同上次功能一样,java 程序中调用对应的脚本从而自动调用打印机系统

@SneakyThrows
public void pdfPrint(String deviceName,Integer num,String dir) {

    /**
     * 打印机名称
     * 设置
     * 路径
     */
    String printStr = ""%s" -print-to "%s" -print-settings %dx "%s"";
    String microsoft_print_to_pdf = String.format(printStr, SumatraPdfPath, deviceName, num, dir);
    log.info("打印执行的参数 => {}", microsoft_print_to_pdf);
    Process exec = Runtime.getRuntime().exec(microsoft_print_to_pdf);
    new Thread(() -> {
        String read = IoUtil.read(exec.getInputStream(), Charset.forName("GBK"));
        log.info("log -> {}",read);
    }).start();
    new Thread(() -> {
        String read = IoUtil.read(exec.getErrorStream(), Charset.forName("GBK"));
        log.info("log -> {}",read);
    }).start();
    exec.waitFor();
}

其中方法对应的参数为打印机系统的名称,打印份数,pdf文件的临时路径 SumatraPdfPath 同样对应 在系统中 SumatraPdf 的路径

丰富系统

系统增加对应的打印机管理功能,将服务器上所有的打印机在系统中进行管理,开发对应的接口供其他系统调用。

实例项目

gitee.com/financial-m…