Skip to Content

Turn a PDF into an image using MuPDF

This example will show you how to turn a PDF into an image using MuPDF and Trigger.dev.

Overview

This example demonstrates how to use Trigger.dev to turn a PDF into a series of images using MuPDF and upload them to Cloudflare R2.

Update your build configuration

To use this example, add these build settings below to your trigger.config.ts file. They ensure that the mutool and curl packages are installed when you deploy your task. You can learn more about this and see more build settings here.

trigger.config.ts
export default ({
  : "<project ref>",
  // Your other config settings...
  build: {
    : [aptGet({ packages: ["mupdf-tools", "curl"] })],
  },
});

Task code

trigger/pdfToImage.ts
import { ,  } from "@trigger.dev/sdk";
import { ,  } from "@aws-sdk/client-s3";
import {  } from "child_process";
import  from "fs";
import  from "path";

// Initialize S3 client
const s3Client = new ({
  region: "auto",
  endpoint: process..S3_ENDPOINT,
  credentials: {
    accessKeyId: process..R2_ACCESS_KEY_ID ?? "",
    secretAccessKey: process..R2_SECRET_ACCESS_KEY ?? "",
  },
});

export const pdfToImage = ({
  : "pdf-to-image",
  : async (payload: { pdfUrl: string; documentId: string }) => {
    .log("Converting PDF to images", payload);

    const pdfPath = `/tmp/${payload.documentId}.pdf`;
    const outputDir = `/tmp/${payload.documentId}`;

    // Download PDF and convert to images using MuPDF
    (`curl -s -o ${pdfPath} ${payload.pdfUrl}`);
    .(outputDir, { : true });
    (`mutool convert -o ${outputDir}/page-%d.png ${pdfPath}`);

    // Upload images to R2
    const uploadedUrls = [];
    for (const file of .(outputDir)) {
      const s3Key = `images/${payload.documentId}/${file}`;
      const uploadParams = {
        Bucket: process..S3_BUCKET,
        Key: s3Key,
        Body: .(.(outputDir, file)),
        ContentType: "image/png",
      };

      .log("Uploading to R2", uploadParams);

      await s3Client.send(new (uploadParams));
      const s3Url = `https://${process..S3_BUCKET}.r2.cloudflarestorage.com/${s3Key}`;
      uploadedUrls.(s3Url);
      .log("Image uploaded to R2", { url: s3Url });
    }

    // Clean up
    .(outputDir, { : true, : true });
    .(pdfPath);

    .log("All images uploaded to R2", { urls: uploadedUrls });

    return {
      imageUrls: uploadedUrls,
    };
  },
});

Testing your task

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

{
  "pdfUrl": "https://pdfobject.com/pdf/sample.pdf",
  "documentId": "unique-document-id"
}

Local development

To test this example task locally, be sure to install any packages from the build extensions you added to your trigger.config.ts file to your local machine. In this case, you need to install mupdf-tools from MuPDF.

Was this page helpful?

Last updated

Edit on GitHub

On this page