eKoopmans / html2pdf.js

Client-side HTML-to-PDF rendering using pure JS.
MIT License
4.01k stars 1.37k forks source link

ReferenceError: Self is not defined - NextJS & Typescript #644

Open devrolle opened 1 year ago

devrolle commented 1 year ago

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

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>
  );
}
JonasDoesThings commented 1 year ago

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

vitorleonel commented 1 year ago

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

clcoco commented 12 months ago

I have the same error on Nuxt 3

azertypow commented 11 months ago

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 ...).