Build a PDF from PNG/JPG images
Adds each image as a page sized to the image itself and returns the PDF bytes.
typescript
import { PDFDocument } from "pdf-lib";
// Each image (PNG or JPG) is added as a page sized to the image.
export async function imagesToPdf(files: File[]): Promise<Uint8Array> {
const pdf = await PDFDocument.create();
for (const file of files) {
const bytes = new Uint8Array(await file.arrayBuffer());
const isPng = file.type === "image/png" || file.name.toLowerCase().endsWith(".png");
const image = isPng ? await pdf.embedPng(bytes) : await pdf.embedJpg(bytes);
const page = pdf.addPage([image.width, image.height]);
page.drawImage(image, { x: 0, y: 0, width: image.width, height: image.height });
}
return pdf.save();
}Dependencias
pdf-libNotas de uso
- Get the File objects from a file input with an image accept attribute.
- The array order is the page order.
Limitaciones
- Only PNG and JPG. WebP can't be embedded directly in pdf-lib — convert it to PNG first via canvas.
- Each page is sized to the image's pixel dimensions; for a fixed A4, compute scale and centering yourself.
- A corrupt image or unsupported format will make embedPng/embedJpg throw.