Solved - pdf-lib.js Uncaught (in promise) Error: Failed to parse PDF document (line:0 col:0 offset=0): No PDF header found

526 Views Asked by At

im using pdf-lib.js lib but im having troubles, this code was working but some day give me that error Note: the pdf is in the same route

when i press the button the pdf get downloaded but without any text just the same pdf as the original

<!DOCTYPE html>
<html>
<head>
    <title>PDF-lib.js Prueba</title>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/pdf-lib.min.js"></script>
</head>
<body>
<input type="text" name="" id="">
<button id="agregarTexto">Agregar Texto</button>

<script src="pdf.js"></script>

</body>
</html>

document.getElementById('agregarTexto').addEventListener('click', async () => {
    const existingPdfBytes = await fetch('Prueba.pdf').then(res => res.arrayBuffer());
    const pdfDoc = await PDFLib.PDFDocument.load(existingPdfBytes);
    const pages = pdfDoc.getPages();
    const firstPage = pages[0];

    const arialFont = await pdfDoc.embedFont(PDFLib.StandardFonts.Helvetica);
    firstPage.drawText('Hola', {
        x: 105,
        y: 698,
        font: arialFont,
        size: 11,
        color: PDFLib.rgb(0, 0, 0),
    });

    const pdfBytes = await pdfDoc.save();
    const blob = new Blob([pdfBytes], { type: 'application/pdf' });
    const url = URL.createObjectURL(blob);
    

    const a = document.createElement('a');
    a.href = url;
    a.download = 'pruebapdf_modificado.pdf';
    a.textContent = 'Descargar PDF Modificado';
    a.style.display = 'none';
    document.body.appendChild(a);
    a.click();
});
1

There are 1 best solutions below

1
TaquitoLoverDev On

Ok i found the error was the integration of Internet Download Manager before the PDF was edited IDM catch the PDF and it did not allow the PDF to reach the Js file