JSFiddle - React, Tailwind, and code Playground

by dshilkret

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PDF Signer</title>
</head>
<body>
    <input type="file" id="fileInput" accept="application/pdf">
    <button id="signButton">Sign PDF</button>
    <div>
        <h3>Original PDF:</h3>
        <iframe id="pdfViewer" width="100%" height="500px"></iframe>
    </div>
    <div>
        <h3>Signed PDF:</h3>
        <iframe id="signedPdfViewer" width="100%" height="500px"></iframe>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/pdf-lib"></script>
    <script src="app.js"></script>
</body>
</html>

JavaScript

document.getElementById('fileInput').addEventListener('change', handleFileSelect, false);
document.getElementById('signButton').addEventListener('click', signSelectedPdf, false);

let selectedFile = null;

function handleFileSelect(event) {
    const file = event.target.files[0];
    if (file.type === 'application/pdf') {
        selectedFile = file;
        console.log('File selected:', file.name);

        const reader = new FileReader();
        reader.onload = function(e) {
            const arrayBuffer = e.target.result;
            const blob = new Blob([new Uint8Array(arrayBuffer)], { type: 'application/pdf' });
            const url = URL.createObjectURL(blob);
            document.getElementById('pdfViewer').src = url;
        };
        reader.readAsArrayBuffer(file);
    } else {
        alert('Please upload a PDF file.');
    }
}

async function signSelectedPdf() {
    if (!selectedFile) {
        alert('No PDF file selected.');
        return;
    }

    const reader = new FileReader();
    reader.onload = async function(e) {
        const arrayBuffer = e.target.result;
        const signedPdfBytes = await signPdf(new Uint8Array(arrayBuffer));

        const blob = new Blob([signedPdfBytes], { type: 'application/pdf' });
        const url = URL.createObjectURL(blob);
        document.getElementById('signedPdfViewer').src = url;
    };
    reader.readAsArrayBuffer(selectedFile);
}

async function signPdf(pdfBytes) {
    const { PDFDocument, rgb } = PDFLib;

    const pdfDoc = await PDFDocument.load(pdfBytes);

    // Perform signing (this is a placeholder for actual signing logic)
    const pages = pdfDoc.getPages();
    const firstPage = pages[0];
    firstPage.drawText('Signed by Me', {
        x: 50,
        y: 700,
        size: 30,
        color: rgb(0, 0, 0),
    });

    const signedPdfBytes = await pdfDoc.save();

    return signedPdfBytes;
}