无法使用pdfmake在pdf文档中显示本地图像

问题描述

我正在尝试将徽标添加到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,但是我并没有真正看到有关如何执行此操作的明确说明。任何帮助将不胜感激

解决方法

这将帮助您从本地资产文件中获取图像。添加 asyncawait 进行转换很重要。

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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...