html2pdf.js icon indicating copy to clipboard operation
html2pdf.js copied to clipboard

ReferenceError: Self is not defined - NextJS & Typescript

Open devrolle opened this issue 2 years ago • 4 comments

I'm getting an error when trying to call the html2pdf() function. The full error message is ReferenceError: self is not defined. I'm not sure what might be causing this error so I thought I would bring it here to see if anyone might have experienced this before and found a fix. I've included a codesandbox link with a copy of my code that re-creates the error.

Code Sandbox Link

Project Stack

  • NextJS v13.3.1
  • Typescript v5.0.4

Component Code

import { useEffect, useRef } from "react";
import * as html2pdf from "html2pdf.js";

export default function Home() {
  const ref = useRef(null);

  useEffect(() => {
    const element = ref.current;
    const worker = html2pdf().from(element);
    console.log("Worker: ", worker);
  }, []);

  return (
    <main>
      <section ref={ref} id="container">
        <h1>This is the pdf text.</h1>
        <p>
          Alright so this should be turned into a pdf. Once thats done, the user
          should be able to download me.
        </p>
      </section>
    </main>
  );
}

devrolle avatar Apr 25 '23 16:04 devrolle

I had the same problem. It's a problem with the library trying to use browser-specific features, when they are not available yet.

One fix that worked for me is importing the library after-render on client-side. i.e.:

// @ts-ignore
import('html2pdf.js').then((html2pdf) => {
  html2pdf.default().from(document.getElementById('print-target')).outputPdf('datauristring').then((data: string) => {
    // print the base64 string, call save instead of outputPdf if you just want to save it.    
  });
});

@devrolle hope that helps

JonasDoesThings avatar May 03 '23 13:05 JonasDoesThings

@JonasDoesThings thank you for the solution. It also helped me.

vitorleonel avatar Jul 27 '23 13:07 vitorleonel

I have the same error on Nuxt 3

clcoco avatar Aug 29 '23 14:08 clcoco

Thanks for the solution, this worked for me.

I had the same problem with VueJS 3 + Vite 3 No problems in development mode (vite), but the error appeared in production (vite build ...).

azertypow avatar Sep 20 '23 12:09 azertypow