Uploading printed files to S3
This example shows how to upload a file to S3 using the AWS SDK.
Uploading printed files results will allow you to render the pdf only once and then serve the uploaded files for later requests.
import {
GetObjectCommand,
PutObjectCommand,
S3Client
} from "@aws-sdk/client-s3";
import { writeFile } from 'node:fs/promises';
const invoiceData = {
"invoiceNumber": "INV-1001",
"invoiceDate": "2024-08-15",
"customer": {
"name": "John Doe",
"address": "123 Maple Street, Springfield, IL, 62704"
},
"invoiceItems": [
{
"name": "Widget A",
"quantity": 10,
"unitPrice": 1999
},
{
"name": "Gadget B",
"quantity": 5,
"unitPrice": 4995
},
{
"name": "Thingamajig C",
"quantity": 2,
"unitPrice": 14950
}
]
};
(async () => {
const invoiceId = "INV-1001";
const S3 = new S3Client({
region: process.env.S3_REGION,
endpoint: process.env.S3_URL,
credentials: {
accessKeyId: process.env.ACCESS_KEY_ID,
secretAccessKey: process.env.SECRET_ACCESS_KEY,
},
});
const r2BucketKey = `${invoiceId}.pdf`;
try {
const invoicePDFGetObjectResponse = await S3.send(new GetObjectCommand({
Bucket: process.env.BUCKET_NAME,
Key: r2BucketKey,
}));
console.log("File exists");
const arrayBuffer = await invoicePDFGetObjectResponse.Body?.transformToByteArray();
if (arrayBuffer) {
await writeFile(`./invoices/${invoiceId}.pdf`, Buffer.from(arrayBuffer));
return;
}
} catch (error) {
console.log("Could not find invoice PDF in S3");
}
const invoiceTemplateId = "6ba567a4-e6ab-46de-be05-2b674b65aaa5";
const printerzResponse = await fetch(`https://api.printerz.dev/templates/${invoiceTemplateId}/render`, {
method: 'POST',
headers: { "x-api-key": process.env.PRINTERZ_API_KEY, "Content-Type": "application/json" },
body: JSON.stringify({ variables: invoiceData, options: { "format": "A4" } })
});
if (!printerzResponse.ok) {
return new Response("Error while generating your invoice, please try again later", { status: 500 });
}
const printerzResponseBody = await printerzResponse.arrayBuffer();
await S3.send(new PutObjectCommand({
Bucket: process.env.BUCKET_NAME,
Key: r2BucketKey,
Body: Buffer.from(printerzResponseBody)
}));
await writeFile(`./invoices/${invoiceId}.pdf`, Buffer.from(printerzResponseBody));
})()