本文介绍了pdfMake-无法打开文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Nodejs上使用了此模块: https://github.com/bpampuch/pdfmake

I used this module on Nodejs : https://github.com/bpampuch/pdfmake

这是我创建它的代码:

    const fonts = {
    Roboto: {
        normal: './fonts/Roboto-Regular.ttf',
        bold: './fonts/Roboto-Medium.ttf',
        italics: './fonts/Roboto-Italic.ttf',
        bolditalics: './fonts/Roboto-Italic.ttf'
    }
};

let PdfPrinter = require('pdfmake/src/printer');
let printer = new PdfPrinter(fonts);
let fs = require('fs');


module.exports.generateFile = function (data,callback) {

    let fileName = "Logins_" + data[0]["userLogin"] + ".pdf";
    let filePath = __dirname + "/files/" + fileName;

    let logins = [ ['userLogin', 'softwarePassword', 'softwareName'] ];
    for (let obj of data) {
        let arr = [];
        for(let x in obj){
            arr.push(obj[x]);
        }
        logins.push(arr);
    }

    let docDefinition = {
        content: [
            {
                table: {
                    // headers are automatically repeated if the table spans over multiple pages
                    // you can declare how many rows should be treated as headers
                    headerRows: 1,
                    widths: [ '*', 'auto', 100, '*' ],

                    body: logins
                }
            }
        ]
    };

    try {

        let chunks = [];
        let result;

        let doc = printer.createPdfKitDocument(docDefinition);
        doc.pipe(fs.createWriteStream(filePath));
        doc.end();
        callback(null,fileName,filePath)
    } catch (err){
        callback(err);
    }
    };

我得到了这个屏幕:

有什么主意吗?在回调中,我将res.download与文件名和文件路径一起使用.我尝试了一切

Any ideas guys ?In the callback, I use res.download with the filename and the filepath.I tried everything

推荐答案

在本地和节点服务器上经过测试的工作解决方案

为什么pdfmake无法打开文件是因为文件流fs仍在写入内存块,这使其无法读取,并且下载的PDF会损坏,大小为0KB.

Why pdfmake cannot open file is because the file stream fs is still writing to the memory block, which makes it unreadable and the downloaded PDF would be corrupted with size of 0KB.

解决方案:将事件侦听器添加到fs.createWriteSteam,然后等待fs完成写入,然后发送文件.

Solution: Add an event listener to the fs.createWriteSteam and wait for fs to finish writing then send file.

var temp123;
pdfDoc.pipe(temp123 = fs.createWriteStream('./PDF/' + name), { encoding:'utf16' });

pdfDoc.end();

temp123.on('finish', async function () {
  // do send PDF file
  res.download('name.pdf');
});

这篇关于pdfMake-无法打开文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-27 08:30