Cookbook
Cloudflare Worker R2 Upload

Uploading printed files to Cloudflare R2

This example shows how to upload a file to Cloudflare R2 using the Cloudflare Workers API.

Uploading printed files results will allow you to render the pdf only once and then serve the uploaded files for later requests.

If you want to set-up a cloudflare worker project, you can follow their quick start guide (opens in a new tab).

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
		}
	]
};
 
export default {
	async fetch(request, env, ctx): Promise<Response> {
		const searchParams = new URL(request.url).searchParams;
 
		const invoiceId = searchParams.get("invoiceNumber");
		if (!invoiceId) {
			return new Response("Missing invoiceId query parameter", { status: 400 });
		}
 
		const r2BucketKey = `invoices/${invoiceId}.pdf`;
 
		const existingInvoicePDF = await env.MY_BUCKET.get(r2BucketKey);
		if (existingInvoicePDF) {
			return new Response(existingInvoicePDF.body, { status: 200, headers: { "Content-Type": "application/pdf" } });
		}
 
		const invoiceTemplateId = "6ba567a4-e6ab-46de-be05-2b674b65aaa5";
 
		const printerzResponse = await fetch(`https://api.printerz.dev/templates/${invoiceTemplateId}/render`, {
			method: 'POST',
			headers: { "x-api-key": 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.blob();
 
		await env.MY_BUCKET.put(r2BucketKey, printerzResponseBody);
 
 
		return new Response(printerzResponseBody, { status: 200, headers: { "Content-Type": "application/pdf" } });
	},
} satisfies ExportedHandler<Env>;