jsPDF server side (node.js) usage using node-jspdf

前端 未结 5 522
眼角桃花
眼角桃花 2020-12-10 16:38

I am actually trying to include jspdf in server side and then use it for simple pdf generation(simply the text \"Hello world!\")(Go to the url- get the pdf localhost:8080).

相关标签:
5条回答
  • 2020-12-10 16:55

    You can actually use jspdf directly (npm install jspdf instead of npm install node-jspdf). Jspdf is currently (v1.3.2) not built with node support in mind, but you can mock the globals like below and get it to work that way. This is a basic example and all features of jspdf will not be available.

    global.window = {document: {createElementNS: () => {return {}} }};
    global.navigator = {};
    global.html2pdf = {};
    global.btoa = () => {};
    
    var fs = require('fs');
    var jsPDF = require('jspdf');
    
    var doc = new jsPDF();
    doc.text("Hello", 10, 10);
    var data = doc.output();
    
    fs.writeFileSync('./document.pdf', data, 'binary');
    
    delete global.window;
    delete global.html2pdf;
    delete global.navigator;
    delete global.btoa;
    
    0 讨论(0)
  • 2020-12-10 17:03

    In extension to the answer provided by Simon Bengtsson:

    I managed to handle even latin-1 characters by sending the output of jsPdf to encoding:

    global.window = {document: {createElementNS: () => {return {}} }};
    global.navigator = {};
    global.btoa = () => {};
    
    var fs = require('fs');
    var jsPDF = require('jspdf');
    var encoding = require('encoding')
    var doc = new jsPDF();
    doc.text("HelloäöüßÄÖÜ©µ®", 10, 10);
    var data = doc.output()
    var buffer = encoding.convert(data, "Latin_1") 
    
    fs.writeFileSync('./document.pdf', buffer);
    
    delete global.window;
    delete global.navigator;
    delete global.btoa;
    
    0 讨论(0)
  • 2020-12-10 17:07

    I am able to install node-jspdf in Windows.

    1. As suggested download jspdf-master.zip and extract it.
    2. Now use the command:

      npm install <location on jspdf-master extract>
      

    After that you can use npm list to see the installation success.

    0 讨论(0)
  • 2020-12-10 17:07

    Download your jspdf folder from parallax jspdf. After installing jspdf ( "npm install jspdf" ) you get the jspdf folder inside node-modules. Go inside it and replace the jspdf.min.js by the jspdf.amd.min.js present in the /dist folder inside the jspdf downloaded from parallax

    0 讨论(0)
  • 2020-12-10 17:09

    Node-jspdf mainly uses library jsPDF as the core library to render PDF file

    but node-jspdf can only be installed on *unix system therefore you can download and install jsPDF manually by following steps in this file

    I think you only need to install jsPDF to work with PDF file.

    0 讨论(0)
提交回复
热议问题