我试图添加一个标志的pdf文件,这是由pdfMake生成的。这是我的代码:
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, productName) {
// productEvalDate: Date
// getDocumentDefinition(id: number, productName: string, companyName) {
return {
content: [
'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
{
image: './assets/images/GPBC-logo-2019.jpg',
width: 150
,
fontSize: 20
},
{
}]
};
}
}
我收到如下错误消息:无效映像:虚拟文件系统中找不到文件映像字典应包含dataURL条目(或node.js中的本地文件路径)。我认为我需要将图像转换为base64,但我并没有真正看到如何做到这一点的明确说明。任何帮助都将不胜感激
发布于 2021-06-17 05:14:05
这将帮助您从本地资源文件中获取图像。添加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, 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"
)
}
https://stackoverflow.com/questions/63584894
复制相似问题