在我的应用程序中,有一个用于生成PDF的屏幕。在Web浏览器上,正在下载PDF,显示内容,但是在移动设备上,它正在下载并以PDF格式保存,并且内容未写入PDF。
使用的插件:cordova pdfMake
这是参考代码
import { Component } from '@angular/core';
import { NavController, Platform, NavParams } from 'ionic-angular';
import pdfMake from 'pdfmake/build/pdfmake';
import pdfFonts from 'pdfmake/build/vfs_fonts';
pdfMake.vfs = pdfFonts.pdfMake.vfs;
import { File } from '@ionic-native/file';
import { FileOpener } from '@ionic-native/file-opener';
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
letterObj = {
to: '',
from: '',
text: ''
}
public signatureImage : any;
pdfObj = null;
constructor(public navCtrl: NavController,private plt: Platform,
private file: File, private fileOpener: FileOpener,public navParams:NavParams ) {
this.signatureImage = navParams.get('signatureImage');
}
createPdf() {
var docDefinition = {
content: [
{ text: 'REMINDER', style: 'header' },
{ text: new Date().toTimeString(), alignment: 'right' },
{ text: 'From', style: 'subheader' },
{ text: this.letterObj.from },
{ text: 'To', style: 'subheader' },
this.letterObj.to,
{ text: this.letterObj.text, style: 'story', margin: [0, 20, 0, 20] },
{
image: this.signatureImage , style: 'foo',
fit: [100, 100] ,alignment:'right'
},
// {
// ul: [
// 'Bacon',
// 'Rips',
// 'BBQ',
// ]
// }
],
styles: {
header: {
fontSize: 18,
bold: true,
},
subheader: {
fontSize: 14,
bold: true,
margin: [0, 15, 0, 0]
},
story: {
italic: true,
alignment: 'center',
width: '50%',
},
foo:{
position: 'absolute',
top: "100%",
right: '100%',
}
}
}
this.pdfObj = pdfMake.createPdf(docDefinition);
pdfMake.createPdf(docDefinition).getBuffer(function (buffer) {
let utf8 = new Uint8Array(buffer);
let binaryArray = utf8.buffer;
self.saveToDevice(binaryArray,"familydescription.pdf")
});
// this.documentViewer.viewDocument(this.pdfObj,'application/pdf',{});
this.fileOpener.open(this.pdfObj, 'application/pdf')
.then(() => console.log('File is opened'))
.catch(e => console.log('Error opening file', e));
}
downloadPdf() {
if (this.plt.is('cordova')) {
this.pdfObj.getBuffer((buffer) => {
var blob = new Blob([buffer], { type: 'application/pdf' });
// Save the PDF to the data Directory of our App
this.file.writeFile(this.file.dataDirectory, 'myletter.pdf', blob, { replace: true }).then(fileEntry => {
// Open the PDf with the correct OS tools
this.fileOpener.open(this.file.dataDirectory + 'myletter.pdf', 'application/pdf');
})
});
} else {
// On a browser simply use download!
this.pdfObj.download();
}
}
saveToDevice(data:any,savefile:any){
let self = this;
self.file.writeFile(self.file.externalDataDirectory, savefile, data, {replace:false});
// const toast = self.toastCtrl.create({
// message: 'File saved to your device',
// duration: 3000,
// position: 'top'
// });
//toast.present();
console.log('file saved')
}
}
我正在使用"pdfmake": "^0.1.54"
答案 0 :(得分:0)
最后,我修复了该错误。我的fileopener
插件版本不支持Ionic -3。我更改了插件版本
答案 1 :(得分:0)
我找到了适合我的解决方案。 希望它可以帮助Github