使用pdfmake在angularjs中生成pdf时未显示图像

Image not showing when generating pdf in angularjs using pdfmake

本文关键字:显示 显示图 图像 pdf pdfmake angularjs 使用      更新时间:2024-03-23

我正在使用pdfmake,这是一个很好的javascript pdf打印库,可以在我的angularjs SPA中生成pdf。当我只使用文本时,一切都很好。pdf文件显示正确,所有文本都已就位。但当我试图展示图像时,它对我不起作用。没有错误,没有空的pdf,只是什么都没发生。也没有404。

这是我现在正在尝试的代码,

var dd = {
        content: [
            {
                image: 'picture13438908025659.jpg'
            },
            {
                text: 'Patient''s Detail', fontSize: 18, bold: true
            },
            {
                columns: [
                    {
                        text: 'Patient''s ID: ' + $scope.prescription.Patient[0].id, bold: false
                    },
                    {
                        text: 'Name: ' + $scope.prescription.Patient[0].name, bold: false
                    },
                    {
                        text: 'Age: ' + $scope.prescription.Patient[0].age, bold: false
                    },
                    {
                        text: 'Contact: ' + $scope.prescription.Patient[0].contact, bold: false
                    }
                ]
            },
            {
                text: 'Address: ' + $scope.prescription.Patient[0].address, bold: false
            }
        ]
    }

它很简单,

1) 在此处将您的图像转换为base64

2) 复制你的base64代码并替换到

image : 'base64', // use your base64 instead image.jpg

3) 完成。这种方法是,如果你的图像不是通过链接处理的,请使用base64代替

您可以轻松地将任何图像转换为base64格式,根据文档,这是首选格式。这是一个100%的工作代码:

function convertImgToBase64URL(url, callback, outputFormat){
    var canvas = document.createElement('CANVAS'),
    ctx = canvas.getContext('2d'),
    img = new Image;
    img.crossOrigin = 'Anonymous';
    img.onload = function(){
        var dataURL;
        canvas.height = img.height;
        canvas.width = img.width;
        ctx.drawImage(img, 0, 0);
        dataURL = canvas.toDataURL(outputFormat);
        callback(dataURL);
        canvas = null; 
    };
img.src = url;
}

在这之后,你只需在你的pdf创建代码中提及它

var docDefinition = {
  content: [
    {
      // you'll most often use dataURI images on the browser side
      // if no width/height/fit is provided, the original size will be used
      image: 'data:image/jpeg;base64,...encodedContent...'
    }]

您首先需要将图像转换为base64,然后可以在图像属性中使用它,就像这个

{
  image: 'data:image/jpeg;base64,...encodedContent...',
  width: 75,
  height: 75,
  alignment : 'left'
}

以下是参考资料-https://pdfmake.github.io/docs/0.1/document-definition-object/images/

您能在图像对象中添加width:your_required_width并检查是否有效吗?这也发生在我身上,我发现图像分辨率太大,PDFMake只是显示了原始尺寸的图像,无法容纳标准尺寸的纸张。为了将来使用PDFMake游乐场来创建文档定义对象,它非常方便。