Categories
JavaScript Answers

How to print PDF directly from JavaScript?

Spread the love

Sometimes, we want to print PDF directly from JavaScript.

In this article, we’ll look at how to print PDF directly from JavaScript.

How to print PDF directly from JavaScript?

To print PDF directly from JavaScript, we can call the print method.

For instance, we write

<embed
  type="application/pdf"
  src="path_to_pdf_document.pdf"
  id="pdfDocument"
  width="100%"
  height="100%"
/>

to embed the PDF with an embed element.

Then we write

const printDocument = (documentId) => {
  const doc = document.getElementById(documentId);

  if (typeof doc.print === "undefined") {
    setTimeout(() => {
      printDocument(documentId);
    }, 1000);
  } else {
    doc.print();
  }
};

to define the printDocument function.

In it, we get the embed element with getElementById.

Then we run printDocument repeatedly until the doc.print method is defined.

Once it’s defined, we call doc.print to open the print dialog.

Conclusion

To print PDF directly from JavaScript, we can call the print method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *