JSFiddle - React, Tailwind, and code Playground

by booktu8

HTML

<button>
print
</button>

JavaScript

const printPdf = (data) => {
  const newBlob = new Blob([data], {
    type: 'text/html'
  });
  const fileLink = window.URL.createObjectURL(newBlob);
  const iframe = document.createElement('iframe');
  iframe.src = fileLink;
  iframe.id = 'print_pdf';
  iframe.name = 'print_pdf';
  // iframe.style.display = 'none'
  iframe.onload = () => {
    iframe.contentWindow.addEventListener('afterprint', (evt) => {
      console.log("printed");
      document.body.removeChild(iframe)
    });
    /* window.frames['print_pdf'].focus() */
    window.frames['print_pdf'].print()
  }
  document.body.appendChild(iframe)
};

document.querySelector("button").onclick = (evt) => printPdf('<h1>Hello</h1>');