使用pdfmake在angularjs中生成pdf时,图片无法显示。

5
我将使用javascript中的一个不错的pdf打印库pdfmake来生成我的angularjs单页面
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
            }
        ]
    }

根据pdfmake的文档(https://github.com/bpampuch/pdfmake#images),建议使用dataURI图像。你已经尝试过了吗? - AardVark71
4个回答

6

很简单,

1)将您的图像转换为base64 这里

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

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

3) 完成。如果您的图像无法使用链接方式工作,则可以使用base64。


2
您可以轻松将任何图像转换为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...'
    }]

1
嗨,Markkillah,我使用了上面的代码,并且在较小的图像(大小<100 kb)上运行良好,但是当我使用大型图像(> 100 kb)时,pdfMake不会在PDF中显示图像,并且控制台中也没有错误。 - Ravindra Vairagi

1

0

你可以在图片对象中添加 width:你需要的宽度 并检查是否有效吗?我也遇到过这个问题,发现图片分辨率太大了,PDFMake 只显示原始大小的图像,无法适应标准纸张尺寸。为了以后使用,请使用 PDFMake playground 创建文档定义对象,非常方便。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接