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
Solution 1:
I'll try to be precise here. I will not be covering usage of pdfKit's nodejs sdk in much detail.
IF you want your generated pdf as a file.
varPDFDocument = require('pdfkit');
// Create a document
doc = newPDFDocument();
// Pipe it's output somewhere, like to a file or HTTP response
doc.pipe(fs.createWriteStream('output.pdf'));
doc.text('Whatever content goes here');
doc.end();
var params = {
key : fileName,
body : './output.pdf',
bucket : 'bucketName',
contentType : 'application/pdf'
}
s3.putObject(params, function(err, response) {
});
However if you want to stream it ( to say S3 bucket in the context of question), then it is worth remembering that every pdfkit instance is a readable stream.
And S3 expects a file, a buffer or a readable stream. So,
var doc = new PDFDocument();
// Pipe it's output somewhere, like to a file or HTTP response
doc.text("Text for your PDF");
doc.end();
var params = {
key : fileName,
body : doc,
bucket : 'bucketName',
contentType : 'application/pdf'
}
//notice use of the upload function, not the putObject function
s3.upload(params, function(err, response) {
});
Solution 2:
If you are using html-pdf package and aws-sdk than it's very easy...
var pdf = require('html-pdf');
import aws from'aws-sdk';
const s3 = new aws.S3();
pdf.create(html).toStream(function(err, stream){
stream.pipe(fs.createWriteStream('foo.pdf'));
const params = {
Key: 'foo.pdf',
Body: stream,
Bucket: 'Bucket Name',
ContentType: 'application/pdf',
};
s3.upload(params, (err, res) => {
if (err) {
console.log(err, 'err');
}
console.log(res, 'res');
});
});
Solution 3:
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.
constPDFDocument = require('pdfkit');
const fs = require('fs');
constAWS = require('aws-sdk');
const path = require('path')
asyncfunctioncreatePDF() {
const doc = newPDFDocument({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 = newAWS.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) {
});
});
}
Post a Comment for "Upload Pdf Generated To Aws S3 Using Nodejs Aws Sdk"