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>XFA PDF Editor</title>
    <style>
        body {
            font-family: Arial, sans-serif;
        }
        textarea {
            width: 100%;
            height: 300px;
        }
    </style>
</head>
<body>
    <h1>XFA PDF Editor</h1>
    <input type="file" id="pdfInput" accept=".pdf" />
    <textarea id="xfaDisplay" placeholder="XFA data will appear here..." readonly></textarea>
    <button id="modifyBtn" disabled>Modify XFA</button>
    <button id="downloadBtn" disabled>Download Modified PDF</button>

    <script>
        document.getElementById('pdfInput').addEventListener('change', handleFileUpload);
        document.getElementById('modifyBtn').addEventListener('click', modifyXFAFields);
        document.getElementById('downloadBtn').addEventListener('click', downloadPDF);

        let originalPdfBuffer;
        let modifiedPdfBlob;

        async function handleFileUpload(event) {
            const file = event.target.files[0];
            if (!file) return;

            const arrayBuffer = await file.arrayBuffer();
            originalPdfBuffer = new Uint8Array(arrayBuffer);

            const xfaXml = extractXfaXml(originalPdfBuffer);
            if (xfaXml) {
                document.getElementById('xfaDisplay').value = xfaXml;
                document.getElementById('modifyBtn').disabled = false;
            } else {
                alert('No XFA data found in the PDF.');
            }
        }

        function extractXfaXml(pdfBuffer) {
            const pdfText = new TextDecoder().decode(pdfBuffer);

            // Locate the XFA XML in the PDF
            const xfaStart = pdfText.indexOf('<xfa:datasets');
            const xfaEnd = pdfText.indexOf('</xfa:datasets>') + '</xfa:datasets>'.length;

            if (xfaStart === -1 || xfaEnd === -1) {
                return null;
            }

    ...