Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upload pdf generated to AWS S3 using nodejs aws sdk

I am using pdfkit to generate a pdf with some custom content and then sending it to an AWS S3 bucket.

While if I generate the file as a whole and upload it works perfectly, however, if I want to stream the generated file probably as an octet stream I am not able to find any relevant pointers.

I am looking for a nodejs solution (or suggestion).

like image 660
Shivendra Soni Avatar asked Dec 13 '15 22:12

Shivendra Soni


People also ask

How do I put a PDF on my AWS S3?

In the Amazon S3 console, choose the bucket where you want to upload an object, choose Upload, and then choose Add Files. In the file selection dialog box, find the file that you want to upload, choose it, choose Open, and then choose Start Upload. You can watch the progress of the upload in the Transfer pane.

How do I access an S3 bucket from AWS SDK?

S3 service object. Call the listBuckets method of the Amazon S3 service object to retrieve a list of your buckets. The data parameter of the callback function has a Buckets property containing an array of maps to represent the buckets. Display the bucket list by logging it to the console.


1 Answers

Tried this and worked. I created a readFileSync and then uploaded that to S3. I also used a "writeStream.on('finish' " so that pdf file is completely created before it is uploaded, otherwise it uploads partial file.

const PDFDocument = require('pdfkit');
const fs = require('fs');
const AWS = require('aws-sdk');
const path = require('path')

async function createPDF() {


const doc = new PDFDocument({size: 'A4'});
let writeStream = fs.createWriteStream('./output.pdf')
doc.pipe(writeStream);


// Finalize PDF file
doc.end();

writeStream.on('finish', function () {
    var appDir = path.dirname(require.main.filename);
    const fileContent = fs.readFileSync(appDir + '/output.pdf');
    var params = {
        Key : 'filName',
        Body : fileContent,
        Bucket : process.env.AWS_BUCKET,
        ContentType : 'application/pdf',
        ACL: "public-read"
      }
      
    const s3 = new AWS.S3({
        accessKeyId: process.env.AWS_ACCESS_KEY,
        secretAccessKey: process.env.AWS_SECRET_KEY
    });
      //notice use of the upload function, not the putObject function
    s3.upload(params, function(err, response) {
        
    });
});

}

like image 200
Tanish Panjwani Avatar answered Oct 05 '22 11:10

Tanish Panjwani