Generating pdf file and excel file in JS front end

Generate pdf file:

Using html2canvas and jspdf plug-ins
Details:
jspdf
html2canvas
Install or use CDN with the following instructions

npm install --save html2canvas jspdf

And then introduce

import html2canvas from 'html2canvas'
import JsPdf from 'jspdf'

First, generate canvas from the whole screenshot of DOM element through html2canvas, and then export the generated image of canvas to pdf format through jspdf

tableToPdf () {
      html2canvas(document.querySelector('#table')).then(canvas => {
        this.createPDFObject(canvas.toDataURL('image/jpeg'))
      })
 },
createPDFObject (imgData) {
      let doc = new JsPdf('', 'pt', 'a4')
      doc.addImage(imgData, 0, 0, 595, 841, 'img')  //	Parameters: picture content, left offset, up offset, width, height, width height of a4 size is 595.28841.89
      doc.save('form.pdf') // Parameters: naming export files
}
Generate excel file (. csv):

Reference resources: https://blog.csdn.net/hhzzcc_/article/details/80419396

 tableToExcel () {
    //  json data to export
    const jsonData = [
       {
         name: 'Passerby a',
         phone: '123456789',
         email: '000@123456.com'
       },
       {
         name: 'Cannon fodder',
         phone: '123456789',
         email: '000@123456.com'
       },
       {
         name: 'Bandit C',
         phone: '123456789',
         email: '000@123456.com'
       }
     ]
     //  Column headings, separated by commas, each comma is separated by a cell
     let str = `Full name,Telephone,mailbox\n`
     //  Add \ tto prevent tables from displaying scientific notation or other formats
     for (let i = 0; i < jsonData.length; i++) {
       for (let item in jsonData[i]) {
         str += `${jsonData[i][item] + '\t'},`
       }
       str += '\n'
     }
     //  Encodeuriccomponent solves Chinese code disorder
     let uri = 'data:text/csv;charset=utf-8,\ufeff' + encodeURIComponent(str)
     //  If the browser recognizes that the path of a label is a file, it will download the file automatically
     let link = document.createElement('a') 
     link.href = uri
     //  Name the downloaded file
     link.download = 'Data sheet.csv'
     document.body.appendChild(link)
     link.click()
     document.body.removeChild(link)
   }

First, join JSON data into string str and form excel format, and then transcode 'text/csv'. Because csv file stores table data (numbers and text) in plain text form, csv file will be generated according to str string

Keywords: JSON Excel npm

Added by tHud on Tue, 26 Nov 2019 20:57:38 +0200