html2pdf.js
html2pdf.js copied to clipboard
ReferenceError: Self is not defined - NextJS & Typescript
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.
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>
);
}
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 thank you for the solution. It also helped me.
I have the same error on Nuxt 3
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 ...).