Next.js upload and preview
A client page that uploads a PDF, a route handler that converts it, and a grid that shows every page.
Config first
Add serverExternalPackages: ["pdf-raster"] to next.config.ts. See
Installation.
The flow has three steps:
The client page posts the PDF as
FormData.The route handler converts every page and returns them as data URLs.
The client renders each page with
next/image.page.tsx
route.ts
Route handler
import { convert, PdfToImagesError } from "pdf-raster";
export const runtime = "nodejs";
function errorResponse(code: string, message: string, status: number) {
return Response.json({ code, message }, { status });
}
export async function POST(request: Request) {
const formData = await request.formData();
const upload = formData.get("file");
if (!(upload instanceof File)) {
return errorResponse("INVALID_INPUT", "Missing PDF upload.", 400);
}
const isPdf =
upload.type === "application/pdf" ||
upload.name.toLowerCase().endsWith(".pdf");
if (!isPdf) {
return errorResponse("INVALID_INPUT", "Only PDF uploads are supported.", 400);
}
try {
const pages = await convert(await upload.arrayBuffer(), {
dpi: 150,
outputFormat: "webp",
maxPixels: 50_000_000,
});
return Response.json({
pages: pages.map((page) => ({
pageIndex: page.pageIndex,
width: page.width,
height: page.height,
dpi: page.dpi,
src: `data:${page.mimeType};base64,${page.data.toString("base64")}`,
})),
});
} catch (error) {
if (error instanceof PdfToImagesError) {
return errorResponse(error.code, error.message, 400);
}
console.error(error);
return errorResponse("RENDER_ERROR", "Conversion failed.", 500);
}
}Client page
"use client";
import Image from "next/image";
import { useState } from "react";
type RenderedPage = {
pageIndex: number;
width: number;
height: number;
dpi: number;
src: string;
};
export default function Page() {
const [pages, setPages] = useState<RenderedPage[]>([]);
const [error, setError] = useState<string | null>(null);
const [isLoading, setIsLoading] = useState(false);
async function handleSubmit(event: React.FormEvent<HTMLFormElement>) {
event.preventDefault();
setError(null);
setPages([]);
setIsLoading(true);
try {
const response = await fetch("/api/convert", {
method: "POST",
body: new FormData(event.currentTarget),
});
const payload = await response.json();
if (!response.ok) {
setError(payload.message ?? "Conversion failed.");
return;
}
setPages(payload.pages);
} catch {
setError("Could not reach the server.");
} finally {
setIsLoading(false);
}
}
return (
<main>
<form onSubmit={handleSubmit}>
<input type="file" name="file" accept="application/pdf,.pdf" required />
<button type="submit" disabled={isLoading}>
{isLoading ? "Converting…" : "Convert PDF"}
</button>
</form>
{error ? <p role="alert">{error}</p> : null}
<section>
{pages.map((page) => (
<figure key={page.pageIndex}>
<Image
src={page.src}
alt={`Page ${page.pageIndex + 1}`}
width={page.width}
height={page.height}
unoptimized
/>
<figcaption>
Page {page.pageIndex + 1}, {page.width} × {page.height} px at{" "}
{page.dpi} DPI
</figcaption>
</figure>
))}
</section>
</main>
);
}Why it is split this way
Only the route handler imports pdf-raster, so the native code stays on the server. The client page sends a form and renders the images it gets back.
For larger documents
Data URLs keep this example short. For PDFs with more than a few pages, store
the rendered images and return their URLs, or stream pages one request at a
time with the pages option.
For the route on its own, see Next.js route handler.