Shifs
Shifs

Reputation: 355

Integrate jsPDF in Nativescript

I researched that using jsPDF, json response cna be converted into PDF and then can be downloaded. Is there any way to integrate JsPDF in nativescript application?

Upvotes: 1

Views: 598

Answers (1)

jdnichollsc
jdnichollsc

Reputation: 1569

Check the following POC with jsPDF and NativeScript, you need to override some global variables required by jsPDF and install some packages from npm:

global['window'] = {
  'document': {
    'createElementNS': () => { return {} }
  }
};
global['document'] = {
  'createElement': (str) => { return {} }
};
global['navigator'] = {};

import * as base64 from 'base-64';
import * as utf8   from 'utf8';
import * as jsPDF  from 'jspdf';

global['btoa'] = (str) => {
  var bytes = utf8.encode(str);
  return base64.encode(bytes);
};

Example: https://play.nativescript.org/?template=play-ng&id=OGrw9s&v=8

By other hand, you can use a NativeScript shim for aotb / btoa functions, to avoid install more packages from npm (Only install jspdf and @types/jspdf): https://play.nativescript.org/?template=play-ng&id=OGrw9s&v=13

As you can see in the logic of the component, you need to import the file and modify some global variables:

require('../base64')

global['window'] = {
  'document': {
    'createElementNS': () => { return {} }
  },
  'atob': global['atob']
};
global['document'] = {
  'createElement': (str) => { return {} }
};
global['navigator'] = {};

It would be much better to create a fork of jsPDF with that solution.

And later you can create your PDF:

generatePDF() {
    var doc = new jsPDF('p', 'pt');
    doc.setFontSize(26);
    doc.text(40, 50, "My first PDF with NativeScript!");

    //Add image
    doc.addImage(imgData, 'JPEG', 20, 90, 300, 300)

    var base64 = doc.output('datauristring')

    dialogs.alert({
        title: "PDF - Base64",
        message: base64,
        okButtonText: "Copy text"
    }).then(() => {
        clipboard.setText(base64)
    });
}

Upvotes: 1

Related Questions