v8.51.4

Editing PDF pages

We can use the preprocessImageFile property on the createDefaultImageReader function to load a PDFs page for editing.

Using a third-party library called PDF.js we can add PDF loading support to the editor.

We need to import pdfjsLib and the PDF.js worker script.

<!-- This defines the pdfjsLib global -->
<script src="/pdfjs-2/build/pdf.js"></script>
<script>
    // here we tell pdfjsLib where to find the worker source
    pdfjsLib.GlobalWorkerOptions.workerSrc = '/pdfjs-2/build/pdf.worker.js';
</script>

Let's move on to setting up our preprocessImageFile function.

<!DOCTYPE html>

<link rel="stylesheet" href="./pintura.css" />

<img src="" alt="" />

<style>
    .pintura-editor {
        height: 600px;
    }
</style>

<div id="editor"></div>

<script type="module">
    import {
        appendDefaultEditor,
        processImage,
        blobToFile,
    } from './pintura.js';

    const editor = appendDefaultEditor('#editor', {
        src: 'image.jpeg',
        imageReader: {
            preprocessImageFile: async (file, options, onprogress) => {
                // If is not a pdf we return the origina lfile
                if (!/pdf$/.test(file.type)) return file;

                // let's convert the pdf to a png
                const pdf = await pdfjsLib.getDocument(
                    URL.createObjectURL(file)
                ).promise;

                // get first page
                const page = await pdf.getPage(1);

                // get a scaled viewport for the pdf
                const viewport = page.getViewport({ scale: 1 });

                // create the target canvas to draw on
                const canvas = document.createElement('canvas');
                canvas.width = viewport.width;
                canvas.height = viewport.height;

                // ask pdfjs to draw to the canvas
                await page.render({
                    canvasContext: canvas.getContext('2d'),
                    transform: null,
                    viewport: viewport,
                }).promise;

                // we turn the canvas into a blob
                const blob = await new Promise((resolve) =>
                    canvas.toBlob(resolve)
                );

                // Pintura Image Editor expects a File
                return blobToFile(blob, file.name);
            },
        },
    });

    editor.on('process', (imageState) => {
        document.querySelector('img').src = URL.createObjectURL(
            imageState.dest
        );
    });
</script>