Search code examples
amazon-web-servicesamazon-s3pdfkitcorruptpdfmake

PDF uploading to AWS S3 corrupted


I managed to get my generated pdf uploaded to s3 from my node JS server. Pdf looks okay on my local folder but when I tried to access it from the AWS console, it indicates "Failed to load PDF document".

I have tried uploading it via the s3.upload and s3.putObject APIs, (for the putObject I also used an .on finish checker to ensure that the file has been fully loaded before sending the request). But the file in the S3 bucket is still the same (small) size, 26 bytes and cannot be loaded. Any help is greatly appreciated!!!

    var pdfDoc = printer.createPdfKitDocument(inspectionReport);
    var writeStream = fs.createWriteStream('pdfs/inspectionReport.pdf');
    pdfDoc.pipe(writeStream);
    pdfDoc.end();
    writeStream.on('finish', function(){
        const s3 = new aws.S3();
        aws.config.loadFromPath('./modules/awsconfig.json');

    var s3Params = {
        Bucket: S3_BUCKET,
        Key: 'insp_report_test.pdf',
        Body: '/pdf/inspectionReport.pdf',
        Expires: 60,
        ContentType: 'application/pdf'
    };
    s3.putObject(s3Params, function(err,res){
        if(err) 
            console.log(err);
        else
            console.log(res);
    })

Solution

  • I realised that pdfDoc.end() must come before piping starts. Have also used a callback to ensure that s3 upload is called after pdf write is finished. See code below, hope it helps!

    var pdfDoc = printer.createPdfKitDocument(inspectionReport);
    pdfDoc.end();    
    
    async.parallel([
    
            function(callback){
                var writeStream = fs.createWriteStream('pdfs/inspectionReport.pdf');
                pdfDoc.pipe(writeStream);
                console.log('pdf write finished!');
                callback();
            }
    
        ], function(err){
    
            const s3 = new aws.S3();
            var s3Params = {
                Bucket: S3_BUCKET,
                Key: 'insp_report_test.pdf',
                Body: pdfDoc,
                Expires: 60,
                ContentType: 'application/pdf'
            };
    
            s3.upload(s3Params, function(err,result){
                if(err) console.log(err);
                else console.log(result);
            });
        }
    );