在Nativescript中集成jsPDF

在Nativescript中集成jsPDF,nativescript,angular2-nativescript,Nativescript,Angular2 Nativescript,我研究了使用jsPDF,将json响应cna转换为PDF,然后可以下载。有没有办法将JsPDF集成到nativescript应用程序中?使用JsPDF和nativescript检查以下POC,您需要覆盖JsPDF所需的一些全局变量,并从npm安装一些包: global['window'] = { 'document': { 'createElementNS': () => { return {} } } }; global['document'] = { 'create

我研究了使用jsPDF,将json响应cna转换为PDF,然后可以下载。有没有办法将JsPDF集成到nativescript应用程序中?

使用JsPDF和nativescript检查以下POC,您需要覆盖JsPDF所需的一些全局变量,并从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);
};
例如:

另一方面,您可以为aotb/btoa函数使用NativeScript垫片,以避免从npm安装更多软件包(仅安装jspdf和@types/jspdf):

正如您在组件逻辑中看到的,您需要导入文件并修改一些全局变量:

require('../base64')

global['window'] = {
  'document': {
    'createElementNS': () => { return {} }
  },
  'atob': global['atob']
};
global['document'] = {
  'createElement': (str) => { return {} }
};
global['navigator'] = {};
使用该解决方案创建一个jsPDF分支会更好

稍后,您可以创建您的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)
    });
}

如果以base64发送服务器响应,则无需插件即可将其转换为pdf