使用Node.js将HTML转换为PDF

Mic*_*ael 73 pdf-generation node.js express

我正在寻找创建pdf我的网站网页的可打印版本.像express.render()只渲染页面的东西pdf

有谁知道这样做的节点模块?

如果没有,您将如何实施?我已经看到一些方法谈论使用无头浏览器phantom.js,但不确定流量是什么.

Joz*_*art 88

扩展Mustafa的答案.

A)然后安装http://phantomjs.org/

B)安装幻像节点模块https://github.com/amir20/phantomjs-node

在此输入图像描述

C)这是渲染pdf的示例

var phantom = require('phantom');   

phantom.create().then(function(ph) {
    ph.createPage().then(function(page) {
        page.open("http://www.google.com").then(function(status) {
            page.render('google.pdf').then(function() {
                console.log('Page Rendered');
                ph.exit();
            });
        });
    });
});
Run Code Online (Sandbox Code Playgroud)

PDF的输出:

在此输入图像描述

编辑: PDF的无声打印

java -jar pdfbox-app-2.0.2.jar PrintPDF -silentPrint C:\print_mypdf.pdf

  • 这也加载了CSS吗?当我渲染页面时,会显示文本,但没有CSS. (22认同)
  • PhantomJS 不再是一个活跃的项目 (4认同)
  • 此解决方案的一个问题是,您将无法获得网页上的可点击链接.这与拍摄屏幕截图并将图像嵌入PDF格式相同.如果这适用于你,那么这是一个很好的解决方案. (3认同)

Mus*_*afa 22

Phantom.js是一个无头webkit服务器,它将加载任何网页并将其呈现在内存中,虽然您可能无法看到它,但有一个屏幕捕获功能,您可以在其中将当前视图导出为PNG,PDF ,JPEG和GIF.从phantom.js文档中查看此示例


Mus*_*afa 14

如果要将HTML导出为PDF.你有很多选择.没有节点甚至

选项1:在html页面上有一个调用window.print()函数的按钮.使用浏览器原生html到pdf.使用媒体查询使您的HTML页面在pdf上看起来很好.并且您还可以在事件之前和之后进行打印,以便在打印之前对页面进行更改.

选项2. htmltocanvasrasterizeHTML.将html转换为canvas,然后在canvas对象上调用toDataURL()以获取图像.并使用像jsPDF这样的JavaScript库将该图像添加到PDF文件中.这种方法的缺点是pdf不可编辑.如果您想要从PDF中提取数据,可以采用不同的方法.

选项3. @Jozzhard回答


The*_*ech 10

我找到的最佳解决方案是html-pdf.它很简单,可以使用大HTML.

https://www.npmjs.com/package/html-pdf

就这么简单:

    pdf.create(htm, options).toFile('./pdfname.pdf', function(err, res) {
        if (err) {
          console.log(err);
        }
    });
Run Code Online (Sandbox Code Playgroud)

  • 它考虑到了CSS?课程? (2认同)
  • 仅供参考 - 该软件包自 2017 年以来尚未更新,并且存在严重漏洞 https://www.npmjs.com/advisories/1095 可能最好选择另一个选项:) (2认同)

Ale*_*der 7

包裹

我使用了html-pdf

易于使用,不仅允许将 pdf 保存为文件,还允许将 pdf 内容通过管道传输到 WriteStream(因此我可以将其直接流式传输到 Google Storage 以保存我的报告)。

使用 css + 图片

它考虑了css。我面临的唯一问题 - 它忽略了我的图像。我找到的解决方案是src用base64替换属性值中的url ,例如

<img src="data:image/png;base64,iVBOR...kSuQmCC">

您可以使用您的代码或使用在线转换器之一来完成,例如https://www.base64-image.de/

从 html 片段 + css 编译有效的 html 代码

  1. 我必须得到我的html文档的一个片段(我只是在 jQuery 选择器上应用了 .html() 方法)。
  2. 然后我阅读了相关css文件的内容。

使用这两个值(存储在变量中htmlcss相应地)我已经使用模板字符串编译了一个有效的 html 代码

var htmlContent = `
<!DOCTYPE html>
<html>
  <head>
    <style>
      ${css}
    </style>
  </head>
  <body id=direct-sellers-bill>
    ${html}
  </body>
</html>`
Run Code Online (Sandbox Code Playgroud)

并将其传递给html-pdf 的create方法。


Tet*_*Dev 6

从外部URL创建PDF

以下是对先前答案的改编,它使用了html-pdf,但也将它与之结合使用,requestify因此它适用于外部URL:

安装依赖项

npm i -S html-pdf requestify
Run Code Online (Sandbox Code Playgroud)

然后,创建脚本:

//MakePDF.js

var pdf = require('html-pdf');
var requestify = require('requestify');
var externalURL= 'http://www.google.com';

requestify.get(externalURL).then(function (response) {
   // Get the raw HTML response body
   var html = response.body; 
   var config = {format: 'A4'}; // or format: 'letter' - see https://github.com/marcbachmann/node-html-pdf#options

// Create the PDF
   pdf.create(html, config).toFile('pathtooutput/generated.pdf', function (err, res) {
      if (err) return console.log(err);
      console.log(res); // { filename: '/pathtooutput/generated.pdf' }
   });
});
Run Code Online (Sandbox Code Playgroud)

然后你只需从命令行运行:

node MakePDF.js
Run Code Online (Sandbox Code Playgroud)

观看美化像素完美PDF为您创建(免费!)


Chu*_*ran 6

尝试使用Puppeteer从HTML创建PDF

此处的示例https://github.com/chuongtrh/html_to_pdf

https://github.com/GoogleChrome/puppeteer

  • 现在,木偶比幻影更有意义,因为后者已被弃用,而前者具有更好,更稳定的api。 (2认同)

Cyr*_* N. 5

对于那些不想在他们的服务器上安装 PhantomJS 和 Chrome/Firefox 实例的人 - 或者因为PhantomJS 项目当前被暂停,这里有一个替代方案。

您可以将转换外部化为 API 来完成这项工作。许多存在且各不相同,但您将获得具有最新功能的可靠服务(我认为 CSS3、Web 字体、SVG、Canvas 兼容)。

例如,使用PDFShift(免责声明,我是创始人),您只需使用以下request包即可完成此操作:

const request = require('request')
request.post(
    'https://api.pdfshift.io/v2/convert/',
    {
        'auth': {'user': 'your_api_key'},
        'json': {'source': 'https://www.google.com'},
        'encoding': null
    },
    (error, response, body) => {
        if (response === undefined) {
            return reject({'message': 'Invalid response from the server.', 'code': 0, 'response': response})
        }
        if (response.statusCode == 200) {
            // Do what you want with `body`, that contains the binary PDF
            // Like returning it to the client - or saving it as a file locally or on AWS S3
            return True
        }

        // Handle any errors that might have occured
    }
);
Run Code Online (Sandbox Code Playgroud)