Invalid PDF Structure error message with Nodejs &

2019-08-19 01:57发布

问题:

I am trying to generate a pdf using nodejs & pdfkit. This will be a GET webservice which will be hosted in AWS api gateway. I am trying to run it locally first and getting Invalid PDF structure everytime.

Here is my code for it. The pdf file is getting generated properly if I place a local path of my system , but always turns up to be a invalid one if I call from browser or postman. Any help would be highly appreciated

'use strict';

const Actions = require('libs-api').Actions;
const config = require('../libs/config').config();
const PDFDocument = require('pdfkit');
const fs = require("fs");
const blobStream = require('blob-stream');
module.exports = async (event, context, callback) => {

    try {
        let actions = new Actions(event, context, config);


        console.log("resultId::" + event.pathParameters.resultId);

        const params = {
            TableName: config.tableName,
            Key: { resultId: event.pathParameters.resultId }
        };

        console.log("params ::" + JSON.stringify(params));

        let data = await actions.readDynamoDB(params);
        // console.log("data::" + JSON.stringify(data));
        let doc = await generatePDF(data);

        let response = {
            statusCode: 200,
            headers: {
                'Access-Control-Allow-Origin': process.env.CORS_URL,
                'Content-Type': 'application/pdf',
                'Content-Disposition': 'attachment; filename=test.pdf'
            },
            body: doc.toString('base64'),
            isBase64Encoded: true
        }
        return response;
    } catch (error) {
        console.log(JSON.stringify(error.stack));
        return Actions.processError();
    }
};

const generatePDF = (data) => {
    console.log("data in generatePDF");

    let doc = new PDFDocument({ margin: 50 });

    doc.text(`Qualification id: ${data.qualificationId}`, 50, 200)
        .text(`Assesment Method: ${data.methodOfAssessment.method}`, 50, 215)
        .text(`Unit Local Code: ${data.unitLocalCode}`, 50, 130)
        .moveDown();

    doc.end();

    return doc;

}