1. 程式人生 > 實用技巧 >文章內容過長,將此內容轉為pdf的方式(使用node)

文章內容過長,將此內容轉為pdf的方式(使用node)

第一步:先下載 html-pdf,命令為 npm i html-pdf -D

varpdf=require('html-pdf');

第二部:建立一個pdf模板

varhtml1=fs.readFileSync('./routes/1.html','utf8')//模板1

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
</head>
<style>
    em {
        font-style: normal;
    }
    .details
-box { padding: 15px; } .details-telit h2 { font-size: 20px; text-align: center; } .details-source { text-align: center; font-size: 14px; margin-top: 30px; } .details-source span { padding: 0 15px; color: #666; }
/* 標題 */ .details-title { font-size: 18px; padding: 0; border-bottom: 1px solid #ccc; position: relative; padding-left: 20px; padding-bottom: 8px; } /* 內容 */ .details-matters { padding: 30px 0; text-align: justify; font-size: 12px; line
-height: 28px; color: #666; } .details-title::after { content: ''; width: 5px; background: #121937; position: absolute; top: 3px; bottom: 11px; left: 0; } .tedt-hhs { color: #666666; } </style> <body>   <div class="details-box"> <div class="details-telit">   <h2> __title__   </h2> </div> <div class="details-matter">   <div class='details-title'> 內容 </div> <div class="details-matters"> __content__ </div> </div>   </div> </body> </html>
varhtml=fs.readFileSync('./routes/2.html','utf8')//模板2 第三步:對模板轉為pdf檔案的方法進行封裝:
// 生成pdf
function createPDFProtocolFile(template, options, reg, filename) {
    /**
      template: html 模板
      options: 配置
      reg: 正則匹配規則
      filename: 輸出pdf檔案路徑及檔名
    */
      // 將所有匹配規則在html模板中匹配一遍
      if (reg && Array.isArray(reg)) {
        reg.forEach(item => {
          template = template.replace(item.relus, item.match);
        });
      }
      pdf
      .create(template, options).toFile(filename, function(err, res) {
          if (err) {
            console.log(err);
              return err
          }
          console.log(res);
      })
}

第四步:使用程式碼生成pdf檔案

var options = {
    "format": 'A4',
    "header": {
    "height": "10mm",
    "contents": ''
}}; // 一些配置// 匹配規則
var reg = [
  {
     relus: /__title__/g,
     match: info[0].title
  },
   {
      relus: /__content__/g,
      match: selectConRs[0].content
   }
];
createPDFProtocolFile(html, options, reg, './public/pdf/'+id+'.pdf'); // 傳入引數 生成pdf

第五步:以上步驟操作完成,就可以實現將文章內容寫進html頁面,最終轉為pdf。