Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save j-hernandez/47c72d30c6bc68935c8c15c372504d43 to your computer and use it in GitHub Desktop.
Save j-hernandez/47c72d30c6bc68935c8c15c372504d43 to your computer and use it in GitHub Desktop.
Using Stream PassThrough to pass same output buffer to multiple destination
const PDFMake = require("pdfmake");
const AWS = require("aws-sdk");
const nodemailer = require("nodemailer");
const { PassThrough } = require("stream");
//aws: update your AWS credentials
const accessKeyId = "{aws_accesskey}";
const secretAccessKey = "{aws_secret}";
const region = "us-east-1";
//pdfmake: make sure you have Roboto fonts in this path
const fonts = {
Roboto: {
normal: __dirname + "/resources/fonts/Roboto-Regular.ttf",
bold: __dirname + "/resources/fonts/Roboto-Medium.ttf",
italics: __dirname + "/resources/fonts/Roboto-Italic.ttf",
bolditalics: __dirname + "/resources/fonts/Roboto-MediumItalic.ttf"
}
};
//pdfmake: sample document definition to create a document
const documentDefinition = {
pageSize: "A4",
pageOrientation: "landscape",
pageMargins: [0, 0, 0, 0],
content: [
{
text: "Great PDF",
alignment: "center",
fontSize: 45,
absolutePosition: { x: 0, y: 255 }
},
{
text: `Thank you for creating this PDF`,
bold: true,
alignment: "center",
color: "#A91F24",
fontSize: 12,
absolutePosition: { x: 0, y: 340 }
}
]
};
const MakePDFUploadAndEmail = () => {
const printer = new PDFMake(fonts);
const pdfDoc = printer.createPdfKitDocument(documentDefinition);
//notice pdfDoc buffer is piped twice here
pdfDoc.pipe(awsUpload());
pdfDoc.pipe(sendEmail());
pdfDoc.end();
};
const awsUpload = data => {
console.log("---Processing AWS");
const s3 = new AWS.S3({ apiVersion: "2006-03-01", accessKeyId, secretAccessKey, region });
//captured the piped buffer here
const doc = new PassThrough();
var params = {
Bucket: "my-bucket",
Key: `test/test.pdf`,
ACL: "public-read",
ContentType: "application/pdf",
Body: doc
};
s3.upload(params, function(err, data) {
if (err) console.log(err);
console.log(data);
});
return doc;
};
const sendEmail = data => {
console.log("---Processing Email");
//captured the piped buffer here
const doc = new PassThrough();
var ses = new AWS.SES({ accessKeyId, secretAccessKey, region });
var transporter = nodemailer.createTransport({
SES: ses
});
var params = {
from: "mySESregistedEmail@gmail.com",
to: "passthroughtest@mailinator.com",
subject: "This is subject",
html: "Here is the attachment",
attachments: [
{
filename: "attachment.pdf",
content: doc
}
]
};
transporter.sendMail(params, function(err, data) {
if (err) console.log(err);
console.log(data);
});
return doc;
};
//run the code using "node ./passthrough-example.js"
MakePDFUploadAndEmail();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment