簡體   English   中英

如何使用 node.js 和 express 生成並下載 PDF 文件?

[英]How do I generate and download a PDF file using node.js and express?

我正在 node.js 和 angular 中構建一個 web 應用程序,我希望生成一個將由客戶端下載的 PDF。 我目前正在使用 phantomjs 下載一個 PDF 文件。 我如何使用 node.js 快速應用程序實現此目的?

fs.readFile('/temp/example.pdf',function(error,data){
    if(error){
       res.json({'status':'error',msg:err});
    }else{
       res.writeHead(200, {"Content-Type": "application/pdf"});
       res.write(data);
       res.end();       
    }
});

要么

res.download('/temp/example.pdf');

使用 NodeJS 生成 PDF 的最簡單方法是使用pdf-master package。您可以使用 HTML 調用一次 function 生成 static 和動態 PDF。

安裝

npm install pdf-master

例子

第 1 步- 添加所需的包並生成 PDF

const express = require("express");
const pdfMaster = require("pdf-master");
const app = express();

app.get("", async (req, res) => {

  var PDF = await pdfMaster.generatePdf("template.hbs");

  res.contentType("application/pdf");
  res.status(200).send(PDF);
});

generatePdf()語法和參數

generatePdf(
  templatePath, //<string>
  data, //<object>   Pass data to template(optional)
  options //<object>   PDF format options(optional)
);

Step 2 - 創建您的 HTML 模板(使用 .hbs 擴展名而不是 .html 保存模板)

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
  </head>
  <body>
    <h1>Hello World</h1>
  </body>
</html>

在模板和 PDF 格式選項中呈現動態數據

const express = require("express");
const pdfMaster = require("pdf-master");

const app = express();

app.get("", async (req, res) => {

  var students = {
      {
          id: 1,
          name: "Sam",
          age: 21
      },
      {
          id: 2,
          name: "Jhon",
          age: 20
      },
      {
          id: 3,
          name: "Jim",
          age: 24
      }
  }

  let options = {
    displayHeaderFooter: true,
    format: "A4",
    headerTemplate: `<h3> Header </h3>`,
    footerTemplate: `<h3> Copyright 2023 </h3>`,
    margin: { top: "80px", bottom: "100px" },
  };

  let PDF = await pdfMaster.generatePdf("template.hbs", students, options);
  res.contentType("application/pdf");
  res.status(200).send(PDF);
});

上述示例的模板(將模板保存為.hbs 擴展名)

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
  </head>
  <body>
    <h1>Student List</h1>
    <ul>
      {{#each students}}
      <li>Name: {{this.name}}</li>
      <li>Age: {{this.age}}</li>
      <br />
      {{/each}}
    </ul>
  </body>
</html>

要了解有關 pdf-master 的更多信息,請訪問

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM