0

我有以下功能,预计可以从链接运行并生成 PDF:

var fs = require('fs');
var pdf = require('html-pdf');
var html = fs.readFileSync('https://www.google.com/', 'utf8');
var options = { format: 'Letter' };

pdf.create(html, options).toFile('./businesscard.pdf', function (err, res) {
    if (err) return console.log(err);
    console.log(res); // { filename: '/app/businesscard.pdf' }
});

但是,当我运行它时,我从终端收到以下错误:

internal/fs/utils.js:454
    throw err;
    ^

Error: ENOENT: no such file or directory, open 'https://www.google.com/'
    at Object.openSync (fs.js:436:3)
    at Object.readFileSync (fs.js:336:35)
    at Object.<anonymous> (C:\Users\hdindi\Documents\NetBeansProjects\NodeJsApplication\main.js:9:15)
    at Module._compile (internal/modules/cjs/loader.js:759:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:770:10)
    at Module.load (internal/modules/cjs/loader.js:628:32)
    at Function.Module._load (internal/modules/cjs/loader.js:555:12)
    at Function.Module.runMain (internal/modules/cjs/loader.js:822:10)
    at internal/main/run_main_module.js:17:11

我该如何解决这个问题?

4

1 回答 1

0

您需要先向要导出为 pdf 的网页发送 http 请求,然后将读取的 html-content 传递给您的 pdf 生成库。像这样的东西(使用 request-promise 来抓取 html,请注意还没有错误处理):

const fs = require('fs');
const pdf = require('html-pdf');
const rq = require('request-promise');
const html = await rp('http://www.google.com');

const options = { format: 'Letter' };

pdf.create(html, options).toFile('./businesscard.pdf', function(err, res) {
  if (err) return console.log(err);
  console.log(res); // { filename: '/app/businesscard.pdf' }
});
于 2019-07-23T19:55:49.003 回答