Make pdf download button

2023-03-04

If you want to download a PDF file from a website without using any external packages, you can use the following steps in your ReactJS component:

  • Create a function that will handle the PDF file download. In this example, the file download will be triggered by clicking a button.
import React from "react";

function handleDownloadPDF() {
  const pdfURL = "https://example.com/file.pdf";
  const link = document.createElement("a");
  link.href = pdfURL;
  link.setAttribute("download", "example.pdf");
  document.body.appendChild(link);
  link.click();
}

if you are using Nextjs you can save the pfd file in the public dir and adapt the pdfURL = "/example.pdf"

  • Create a button element in the component's render method that will call the handleDownloadPDF function on click.
function PDFDownloadButton() {
  return <button onClick={handleDownloadPDF}>Download PDF</button>;
}

The handleDownloadPDF function will create a new a element, set its href attribute to the PDF file URL, and its download attribute to the desired file name. It will then append the a element to the body of the document and simulate a click on the a element to initiate the download. That's it! You can customize the PDF URL and file name to suit your needs.