使用wkhtmltopdf将html页面转换为image或者pdf

维基html转pdf或者html转image图片是一款C++编写的软件,基于QT Webkit rendering engine生成图片和pdf。

可以参考 https://wkhtmltopdf.org 查看更多的文档和资料,使用它我们需要下载和安装该软件到本地。

使用java调用,可参考如下调用:

 /**
     * 1.wkhtmltoimage http://xxx/xxx/index.html C:\Users\xuchang\Desktop\imgae\test2.jpg
     * 
     * 2.wkhtmltopdf http://xxx/xxx/index.html C:\Users\xuchang\Desktop\imgae\test3.pdf
     * 
     * 3.C:\Program" "Files" ("x86")"\wkhtmltopdf\wkhtmltoimage.exe --width 1024 --height 768 http://www.google.com/
     * D:\example.jpg
     * 
     * 4.wkhtmltopdf --page-width 50 http://xxx/xxx/index.html C:\Users\xuchang\Desktop\imgae\test7.pdf
     */
    @Test
    public void testGenerateImage() {
        ExecutorService executor = Executors.newFixedThreadPool(2);
        try {
            Process process = Runtime
                .getRuntime()
                .exec(
                    "D:/wkhtmltopdf/bin/wkhtmltoimage.exe http://xxx/xxx/index.html C:/Users/xuchang/Desktop/imgae/test4.jpg");
            
            Future<List<String>> inputStreamToByteArray = executor.submit(streamToByteArrayTask(process
                .getInputStream()));
            Future<List<String>> outputStreamToByteArray = executor.submit(streamToByteArrayTask(process
                .getErrorStream()));
            
            process.waitFor();
            if (process.exitValue() != 0) {
                System.out.println("getErrorStream:" + getFuture(outputStreamToByteArray));
                System.out.println("getInputStream:" + getFuture(inputStreamToByteArray));
            }
            
            System.out.println("getErrorStream:" + getFuture(outputStreamToByteArray));
            System.out.println("getInputStream:" + getFuture(inputStreamToByteArray));
            
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            executor.shutdownNow();
        }
        
    }
    
    /**
     * @param input xx
     * @return xx
     */
    private Callable<List<String>> streamToByteArrayTask(final InputStream input) {
        return new Callable<List<String>>() {
            
            public List<String> call() throws Exception {
                return IOUtils.readLines(input, "utf-8");
            }
        };
    }
    
    /**
     * @param future xx
     * @return xx
     */
    private List<String> getFuture(Future<List<String>> future) {
        try {
            return future.get(10, TimeUnit.SECONDS);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值