phantomjs(PDFConvert)

本文介绍如何使用PhantomJS将HTML页面转换为PDF文件,包括安装PhantomJS、配置命令行参数及使用示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

官方网站:http://phantomjs.org(主要参考官方网站)

Phantom JS是一个服务器端的 JavaScript API 的 WebKit。其支持各种Web标准: DOM 处理, CSS 选择器, JSON, Canvas, 和 SVG,其功能很强大,这里主要是讲一个html转换pdf的demo,也只是Phantom JS的冰山一角。

1.下载Phantom JS安装程序(支持windows,mac os x,linux),目前版本是2.0


2.Phantom JS是通过命令行来执行所有相关的操作,如下代码是将一个网站转化成pdf文件输出


Runtime runtime=Runtime.getRuntime();

String phant_path=PropKit.use("url.properties").get("PHANTOMJS_PATH");//phantomjs的安装路径
//程序执行命令,分为四部分(1.执行程序路径,2.相关功能的js文件(这里是pdf的convert),
//                                            3.html文件的源文件,4.转换后的pdf文件)
String command=phant_path+"/bin/phantomjs.exe " +
                             phant_path+"/examples/rasterize.js "+" "
                             +"http://www.oicqzone.com"+" "+"e://test.pdf";
Process process=runtime.exec(command);

try {
    process.waitFor();
} catch (InterruptedException e) {
    e.printStackTrace();
}

rasterize.js

var page = require('webpage').create(),

        system = require('system'),

        address, output, size;

 

    if (system.args.length < 3 || system.args.length > 5) {

        console.log('Usage: rasterize.js URL filename [paperwidth*paperheight|paperformat] [zoom]');

        console.log('  paper (pdf output) examples: "5in*7.5in", "10cm*20cm", "A4", "Letter"');

        phantom.exit(1);

    } else {

        address = system.args[1];

        output = system.args[2];

        page.viewportSize = { width: 600, height: 600 };

        if (system.args.length > 3 && system.args[2].substr(-4) === ".pdf") {

            size = system.args[3].split('*');

            page.paperSize = size.length === 2 ? { width: size[0], height: size[1], margin: '0px' }

                : { format: system.args[3], orientation: 'portrait', margin: '1cm' };

        }

        if (system.args.length > 4) {

            page.zoomFactor = system.args[4];

        }

        page.open(address, function (status) {

            if (status !== 'success') {

                console.log('Unable to load the address!');

                phantom.exit();

            } else {

                window.setTimeout(function () {

                    page.render(output);

                    phantom.exit();

                });

            }

        });

    }

这是转换PDF的一个例子而已,如果要实行web端导出功能还需html模板,freemarker工具进行html的生成才能进行转换。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值