【问题标题】:phantomjs - render HTML to PDFphantomjs - 将 HTML 渲染为 PDF
【发布时间】:2018-02-16 18:50:27
【问题描述】:

我在将 HTML 文件呈现为 PDF 文件时遇到问题。我将两个参数传递给命令行。第一个是 HTML 输入文件,第二个是 PDF 输出

/var/bin/phantomjs-2.1.1-linux-x86_64/bin/phantomjs /var/www/nodejs/html_to_pdf.js /root/input.html /root/hello.pdf

代码

var page = require('webpage').create(),
    args = require('system').args,
    f = require('fs').open(args[1], 'r');

page.paperSize = {
    format : 'A4',
    orientation : 'portrait',
    margin : {
        top : '1cm',
        left : '1cm',
        bottom : '1cm',
        right : '1cm'
    }
};

page.content = f.read();
page.setContent(page.content, page);
page.render(args[2]);
phantom.exit();

没有返回错误,也没有输出PDF文件?

这是输入文件

http://www.filedropper.com/input_3

【问题讨论】:

    标签: node.js pdf phantomjs


    【解决方案1】:

    我建议将文件重写为page.open

    var page = require('webpage').create();
    var args = require('system').args;
    var fs = require('fs');
    
    function getFileUrl(str) {
      var pathName = fs.absolute(str).replace(/\\/g, '/');
      // Windows drive letter must be prefixed with a slash
      if (pathName[0] !== "/") {
        pathName = "/" + pathName;
      }
      return encodeURI("file://" + pathName);
    };
    
    page.paperSize = {
        format : 'A4',
        orientation : 'portrait',
        margin : {
            top : '1cm',
            left : '1cm',
            bottom : '1cm',
            right : '1cm'
        }
    };
    
    page.open(getFileUrl(args[1]), function(){
        page.render(args[2]);
        phantom.exit();
    });
    

    getFileUrl 来自this answer

    【讨论】:

      猜你喜欢
      • 2023-04-03
      • 1970-01-01
      • 1970-01-01
      • 2016-11-21
      • 1970-01-01
      • 2014-01-31
      • 2016-04-17
      • 1970-01-01
      • 2020-04-12
      相关资源
      最近更新 更多