Merge pull request #150 from omenmn/pdftopng

feat: pdf to png
This commit is contained in:
Ibrahima G. Coulibaly
2025-07-07 02:31:45 +01:00
committed by GitHub
8 changed files with 506 additions and 185 deletions

View File

@@ -1,3 +1,4 @@
import { tool as pdfPdfToPng } from './pdf-to-png/meta';
import { tool as pdfRotatePdf } from './rotate-pdf/meta';
import { meta as splitPdfMeta } from './split-pdf/meta';
import { meta as mergePdf } from './merge-pdf/meta';
@@ -12,5 +13,6 @@ export const pdfTools: DefinedTool[] = [
compressPdfTool,
protectPdfTool,
mergePdf,
pdfToEpub
pdfToEpub,
pdfPdfToPng
];

View File

@@ -0,0 +1,70 @@
import { useState } from 'react';
import ToolContent from '@components/ToolContent';
import ToolPdfInput from '@components/input/ToolPdfInput';
import { ToolComponentProps } from '@tools/defineTool';
import { convertPdfToPngImages } from './service';
import ToolMultiFileResult from '@components/result/ToolMultiFileResult';
type ImagePreview = {
blob: Blob;
url: string;
filename: string;
};
export default function PdfToPng({ title }: ToolComponentProps) {
const [input, setInput] = useState<File | null>(null);
const [images, setImages] = useState<ImagePreview[]>([]);
const [zipBlob, setZipBlob] = useState<File | null>(null);
const [loading, setLoading] = useState(false);
const compute = async (_: {}, file: File | null) => {
if (!file) return;
setLoading(true);
setImages([]);
setZipBlob(null);
try {
const { images, zipFile } = await convertPdfToPngImages(file);
setImages(images);
setZipBlob(zipFile);
} catch (err) {
console.error('Conversion failed:', err);
} finally {
setLoading(false);
}
};
return (
<ToolContent
title={title}
input={input}
setInput={setInput}
initialValues={{}}
compute={compute}
inputComponent={
<ToolPdfInput
value={input}
onChange={setInput}
accept={['application/pdf']}
title="Upload a PDF"
/>
}
resultComponent={
<ToolMultiFileResult
title="Converted PNG Pages"
value={images.map((img) => {
return new File([img.blob], img.filename, { type: 'image/png' });
})}
zipFile={zipBlob}
loading={loading}
loadingText="Converting PDF pages"
/>
}
getGroups={null}
toolInfo={{
title: 'Convert PDF pages into PNG images',
description:
'Upload your PDF and get each page rendered as a high-quality PNG. You can preview, download individually, or get all images in a ZIP.'
}}
/>
);
}

View File

@@ -0,0 +1,14 @@
import { defineTool } from '@tools/defineTool';
import { lazy } from 'react';
export const tool = defineTool('pdf', {
name: 'PDF to PNG',
path: 'pdf-to-png',
icon: 'mdi:image-multiple', // Iconify icon ID
description: 'Transform PDF documents into PNG panels.',
shortDescription: 'Convert PDF into PNG images',
keywords: ['pdf', 'png', 'convert', 'image', 'extract', 'pages'],
longDescription:
'Upload a PDF and convert each page into a high-quality PNG image directly in your browser. This tool is ideal for extracting visual content or sharing individual pages. No data is uploaded — everything runs locally.',
component: lazy(() => import('./index'))
});

View File

@@ -0,0 +1,51 @@
import * as pdfjsLib from 'pdfjs-dist';
import pdfjsWorker from 'pdfjs-dist/build/pdf.worker.min?url';
import JSZip from 'jszip';
pdfjsLib.GlobalWorkerOptions.workerSrc = pdfjsWorker;
type ImagePreview = {
blob: Blob;
url: string;
filename: string;
};
export async function convertPdfToPngImages(pdfFile: File): Promise<{
images: ImagePreview[];
zipFile: File;
}> {
const arrayBuffer = await pdfFile.arrayBuffer();
const pdf = await pdfjsLib.getDocument({ data: arrayBuffer }).promise;
const zip = new JSZip();
const images: ImagePreview[] = [];
for (let i = 1; i <= pdf.numPages; i++) {
const page = await pdf.getPage(i);
const viewport = page.getViewport({ scale: 2 });
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d')!;
canvas.width = viewport.width;
canvas.height = viewport.height;
await page.render({ canvasContext: context, viewport }).promise;
const blob = await new Promise<Blob>((resolve) =>
canvas.toBlob((b) => b && resolve(b), 'image/png')
);
const filename = `page-${i}.png`;
const url = URL.createObjectURL(blob);
images.push({ blob, url, filename });
zip.file(filename, blob);
}
const zipBuffer = await zip.generateAsync({ type: 'arraybuffer' });
const zipFile = new File(
[zipBuffer],
pdfFile.name.replace(/\.pdf$/i, '-pages.zip'),
{ type: 'application/zip' }
);
return { images, zipFile };
}