Home > Mobile >  How to download a file stored as bytes in a React/JavaScript Variable
How to download a file stored as bytes in a React/JavaScript Variable

Time:08-12

So I'm creating a web application to get inputs like name, email, age etc from a user and fill these details onto a form11 PDF. So far, I have been able to get the inputs and fill these onto a Form11 PDF using PDF-lib library. Now I want to enable the users to download this filled PDF via download button, or even better, auto-download this filled file when the user presses the Submit button. The submit button fires a function fillForm() whose code is given below.

async function fillForm() {
    const formUrl = 'https://github.com/chandran-jr/Genie11/blob/main/PFForm11.pdf'
    const formPdfBytes = await fetch(formUrl).then(res => res.arrayBuffer())

    const pdfDoc = await PDFDocument.load(formPdfBytes)

    const form = pdfDoc.getForm()

    const nameField = form.getTextField('Name of the member')

    nameField.setText({name})

    const pdfBytes = await pdfDoc.save()

So the variable pdfBytes has the filled document saved, is what I assume. Now I want to enable the users to download this file or as mentioned, the auto-download. This function is written using the pdf-lib documentation, but it does not mention how to download it.

CodePudding user response:

Add the below code. This will auto download the file. You will be passing pdfBytes created in the code you shared below. It will create an anchor tag in DOM and simulate the click. If you want user to click download then remove the last line link.download() and instead use the value of window.URL.createObjectURL(blob) and open that URL in new tab with window.open()

var blob = new Blob([pdfBytes], {type: "application/pdf"});
var link = document.createElement("a");
link.href = window.URL.createObjectURL(blob);
link.download = "myFileName.pdf";
link.click();
  • Related