问题描述
我正在尝试将徽标添加到pdfMake生成的pdf文档中。这是我的代码:
import {Injectable} from '@angular/core';
import pdfMake from 'pdfmake/build/pdfmake';
import pdfFonts from 'pdfmake/build/vfs_fonts';
pdfMake.vfs = pdfFonts.pdfMake.vfs;
@Injectable({
providedIn: 'root'
})
export class PdfService {
constructor() { }
getDocumentDefinition(id: number,companyName,productName) {
// productEvalDate: Date
// getDocumentDefinition(id: number,productName: string,companyName) {
return {
content: [{
image: '.assets/images/GPBC-logo-2019.jpg',width: 150,text: 'The product,listed below,produced for the company listed below,is PLANT-BASED certified ' +
'under XXX Certification.\n \n' +
'Name of Product: ' + productName +
'\n Name of Producer/Owner: ' + companyName +
'\n Product ID#: ' + id +
'\n \n \n Signed by: XXX '
// '\n \n \n This certificate is valid until: ' + productEvalDate,fontSize: 20
},{
}]
};
}
}
我得到的结果是一切都正确显示;文字和动态数据。但是没有图像显示,也没有错误。
由于进行了更多研究,我将代码更改如下:
import {Injectable} from '@angular/core';
import pdfMake from 'pdfmake/build/pdfmake';
import pdfFonts from 'pdfmake/build/vfs_fonts';
pdfMake.vfs = pdfFonts.pdfMake.vfs;
@Injectable({
providedIn: 'root'
})
export class PdfService {
constructor() { }
getDocumentDefinition(id: number,companyName) {
return {
content: [
'The product,is PLANT-BASED certified ' +
'under XXX Certification.\n \n' +
'Name of Product: ' + productName +
'\n Name of Producer/Owner: ' + companyName +
'\n Product ID#: ' + id +
'\n \n \n Signed by: XXX '
// '\n \n \n This certificate is valid until: ' + productEvalDate
{
image: './assets/images/GPBC-logo-2019.jpg',{
}]
};
}
}
我收到如下错误消息:无效的图像:在虚拟文件系统中找不到文件图像字典应包含dataURL条目(或node.js中的本地文件路径)。我相信我需要将图像转换为base64,但是我并没有真正看到有关如何执行此操作的明确说明。任何帮助将不胜感激
解决方法
这将帮助您从本地资产文件中获取图像。添加 async
和 await
进行转换很重要。
getBase64ImageFromURL(url) {
return new Promise((resolve,reject) => {
var img = new Image();
img.setAttribute("crossOrigin","anonymous");
img.onload = () => {
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img,0);
var dataURL = canvas.toDataURL("image/png");
resolve(dataURL);
};
img.onerror = error => {
reject(error);
};
img.src = url;
});}
async createPdf() {
var docDefinition = {
content: [
{
image: await this.getBase64ImageFromURL(
"../../assets/ribbonLogo1.png"
)
}
,
我认为必须先将图像转换为base64
才能使用,
source
将图像转换为base64