phantomjs技巧之将html页面转换为pdf文件

    xiaoxiao2026-01-27  8

    需求

    很多时候我们需要将一些网页转换为pdf,比如开发人员需要为每个客户提供一份运维周报,周报一般是html的页面,但是为了能够永久记录存储,需要将周报转换为pdf格式的文件,pdf一方面便于阅览,另一方面也便于打印出来。所以本文研究如何通过phantomjs将一个html的页面转换为pdf文件。

    编写pdfconvert.js代码

    1. 先确定pdf输出格式

    页面格式(format):A3/A4/A5/letter页眉/页脚(header/footer):true or false页面方向(orientation):portrait/landscape页边距(margin)-浏览器窗口大小(viewportSize)

    2. 参数输入输出

    输入:url地址输出:文件名

    3. 具体代码(以A4纸输出为例)

    var page = require( 'webpage' ).create(); var oss_url, out_pdf; var system = require('system') oss_url = system.args[1]; //输入,系统参数 out_pdf = system.args[2]; //输出, 系统参数 page.viewportSize = { width: 1024, height: 800 }; //viewport size page.paperSize = { format: 'A4', orientation: 'portrait', margin: '1cm', //页边距 header: { //如果不需要,可以不用添加 height: '1cm', contents: phantom.callback(function(pageNum, numPages) { //返回页眉的代码逻辑 } }) }, footer: { //如果不需要,可以不用添加 height: '1cm', contents: phantom.callback(function(pageNum, numPages) { //返回页脚的代码逻辑 } }) } }; page.open( oss_url, function( status ) { window.setTimeout(function() { if ( status === "success" ) { page.render(out_pdf); } phantom.exit(); }, 300); //超时设置 });

    后端代码

    url := os.Args[1] out_pdf := os.Args[2] cmd := exec.Command("./phantomjs", "pdfconvertor.js", url, out_pdf) cmd.Stdout = os.Stdout cmd.Run() 相关资源:利用phantomjs将web页面转Pdf
    最新回复(0)