Skip to Content

Generate a PDF using react-pdf and save it to R2

This example will show you how to generate a PDF using Trigger.dev.

Overview

This example demonstrates how to use Trigger.dev to generate a PDF using react-pdf and save it to Cloudflare R2.

Task code

This example must be a .tsx file to use React components.
trigger/generateResumePDF.tsx
import { ,  } from "@trigger.dev/sdk";
import { , , , ,  } from "@react-pdf/renderer";
import { ,  } from "@aws-sdk/client-s3";

// Initialize R2 client
const r2Client = new ({
  // How to authenticate to R2: https://developers.cloudflare.com/r2/api/s3/tokens/
  region: "auto",
  endpoint: process..R2_ENDPOINT,
  credentials: {
    accessKeyId: process..R2_ACCESS_KEY_ID ?? "",
    secretAccessKey: process..R2_SECRET_ACCESS_KEY ?? "",
  },
});

export const generateResumePDF = ({
  : "generate-resume-pdf",
  : async (payload: { text: string }) => {
    // Log the payload
    .log("Generating PDF resume", payload);

    // Render the ResumeDocument component to a PDF buffer
    const pdfBuffer = await (
      <>
        < size="A4">
          <>
            <>{payload.text}</Text>
          </View>
        </Page>
      </Document>
    );

    // Generate a unique filename based on the text and current timestamp
    const filename = `${payload.text.(/\s+/g, "-").()}-${.()}.pdf`;

    // Set the R2 key for the PDF file
    const r2Key = `resumes/${filename}`;

    // Set the upload parameters for R2
    const uploadParams = {
      Bucket: process..R2_BUCKET,
      Key: r2Key,
      Body: pdfBuffer,
      ContentType: "application/pdf",
    };

    // Log the upload parameters
    .log("Uploading to R2 with params", uploadParams);

    // Upload the PDF to R2
    await r2Client.send(new (uploadParams));

    // Return the Bucket and R2 key for the uploaded PDF
    return {
      Bucket: process..R2_BUCKET,
      Key: r2Key,
    };
  },
});

Testing your task

To test this task in the dashboard, you can use the following payload:

{
  "text": "Hello, world!"
}

Was this page helpful?

Last updated

Edit on GitHub

On this page