Introduction to the

Requirements: Fill in the form (lots of pictures) in the APP and send it to the back end to generate the PDF and save it in the mobile phone

Dependency of use

html-pdf

The code structure

Utils /index.js main method

const path = require('path')
const pdf = require('html-pdf'); // html-pdf
const optionDefault = {
  "format"'A4'."header": {
    "height""10mm"."contents"' '
  },
  // "phantomPath": "/usr/local/phantomjs-2.1.1-linux-x86_64/bin/phantomjs" // The phantomJS path is deployed online
};
module.exports = {
  /** * Export PDF *@param {String} Template template *@param {String} Name PDF name *@param {Object} The data data *@param {Function} Fn handler *@param {Object} Options html-pdf parameters */
  exportPdf(template, name, data, fn = null,  options = optionDefault) {
    return new Promise((resolve, reject) = > {
      letdataReplace = { ... data };if (fn) { dataReplace = fn(data) }
      const html = template.replace(/__([A-Za-z]+)__/g.function(a1, a2{
        return dataReplace[a2] || '    '
      });
      const exportPath = path.resolve(__dirname, '.. /.. /temporary')
      pdf.create(html, options).toFile(`${exportPath}/${name}.pdf`.(err, res) = > {
        if (err) {
          reject(err)
        } else {
          // resolve(res)
          resolve(`${name}.pdf`)}}); }})},Copy the code

Enum. Js For different templates, write different processing functions

const fs = require('fs');
const path = require('path')
const TABLE_TYPE = {
  proofing: {
    name'Proof sheet'.fn(data) {
      data.images = data.imgs.map((item) = > {
        return `<img src="${item.src}" alt="" />`
      }).join(' ')
      return data
    }
  },
  primary: {
    name'First Piece Inspection Record'.fn(data) {
      data.images = data.imgs.map((item) = > {
        return `<img src="${item.src}" alt="" />`
      }).join(' ')
      return data
    }
  },
}
module.exports = function(type{
  const templatePath = path.resolve(__dirname, `./template/${type}.html`)
  const template = fs.readFileSync(templatePath, 'utf8'); // Import HTML templates
  const { name, fn } = TABLE_TYPE[type]
  return { name, fn , template }
}
Copy the code

Index.js project startup file


const Koa = require('koa')
const Route = require('koa-router')
const koaBody = require('koa-body')
const koaStatic = require('koa-static');
const cors = require('@koa/cors');
const path = require('path')
const app = new Koa();
const router = new Route()
const { exportPdf } = require('./utils/exportPdf')
const EnumHtml = require('./enum')

// Use middleware
app.use(koaBody());
app.use(cors());
app.use(koaStatic(path.resolve(__dirname, '.. /temporary')));

// Export PDF interface
router.post('/'.async (ctx) => {
  const data = ctx.request.body
  const { template, name, fn = null } = EnumHtml(data.type)
  const exportPath = await exportPdf(template, name + data.createTime, data, fn)
  ctx.body = exportPath
  ctx.status = 200
})
app.use(router.routes())
app.listen(3001)
console.log('Service Running: http://localhost:3001')

Copy the code

Template/rivet. HTML Template file

<! DOCTYPEhtml>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
  <title>Document</title>
  <style>
    body {
      margin0;
      padding20px;
    }
    /* Customize PDF styles */
  </style>
</head>
<body>
  <table>
    <tr>
      <td class="key">The applicant</td>
      <td>__applicant__</td>
      <td class="key">Application date</td>
      <td>__date__</td>
      <td class="key">Apply for department</td>
      <td>__department__</td>
    </tr>
    <tr>
      <td>Responsible for the department</td>
      <td>panel</td>
      <td>The host</td>
      <td>packaging</td>
      <td>The quality of</td>
      <td>Workshop Director</td>
    </tr>
    <tr class="sign-block">
      <td class="key">Signature of principal</td>
      <td><img class="sign" src="__panel__" alt=""/></td>
      <td><img class="sign" src="__host__" alt=""/></td>
      <td><img class="sign" src="__packaging__" alt=""/></td>
      <td><img class="sign" src="__quality__" alt=""/></td>
      <td><img class="sign" src="__generationWorkshopDirector__" alt=""/></td>
    </tr>
  </table>
  <div class="image-block">
    <! -- Photo information -->
    __images__
  </div>
</body>
</html>
Copy the code

Problem solving

Install phantomjs

AssertionError [ERR_ASSERTION]: html-pdf: Failed to load PhantomJS module. You have to set the path to the PhantomJS binary using 'options.phantomPath'
...
Copy the code

Small partners may have the above problems in use

PhantomJs is a server-side JavaScript API WebKit that supports various Web standards: DOM handling, CSS selector, JSON, Canvas, SVG. To use HTML-PDF, install PhantomJS based on the server operating system

This parameter is not required for local development on Windows, but is automatically downloaded in HTML-PDF dependency. However, this parameter is required for MAC and Linux

  1. Download, follow the link above
  2. PhantomJs does not need to be installed. After unpacking and configuring environment variables, it can be used directly
  3. Configuration, vim/etc/profile = > export PATH = $PATH: / usr/local/phantomjs – 2.1.1 – Linux – x86_64 / bin execute commands, make its effect: the source/etc/profile
  4. Change the phantomjs path in utils/index.js

Install font library & Chinese font

You may encounter that the exported PDF cannot display Chinese, which is difficult to find in local development because both MAC and Windows development environments have font libraries and support Chinese. However, font libraries may not be installed when deployed on a server. To install the Chinese font library according to the operating system, you can search online directly:

Install font libraries for Linux CentOS/Ubuntu

I’m not going to expand it

The last

Hope to help you, the above code is very complete, any questions can be communicated with oh