html2pdf.js
html2pdf.js copied to clipboard
I cannot import from cdn on svelte
I installed svelte as shown in the official page's guide
npx degit [sveltejs/template](https://github.com/sveltejs/template) my-svelte-project
cd my-svelte-project
npm install
npm run dev
And I add "cdn import" like this(App.svelte):
<script>
import { onMount } from 'svelte'
let html2pdf
onMount(async () => {
html2pdf = (await import('https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js')).default
})
async function pdfmake() {
var element = document.getElementById('root');
console.log(element, html2pdf)
html2pdf().from(element).set({
margin: 0,
filename: 'test.pdf',
html2canvas: { scale: 1 },
jsPDF: {orientation: 'portrait', unit: 'mm', format: 'a4', compressPDF: true}
}).save();
}
</script>
<button on:click={pdfmake} >Generate PDF</button>
<main>
<h1 id="root">test</h1>
</main>
But nothing happend, Is there anyway I can use this plugin in my app?
import html2pdf from 'html2pdf.js';
const pdfTest = async () => {
let element = document.getElementById('html');
console.log(element, html2pdf)
html2pdf().from(element).set({
margin: 0,
filename: 'test.pdf',
html2canvas: { scale: 1 },
jsPDF: {orientation: 'portrait', unit: 'mm', format: 'a4', compressPDF: true}
}).save();
}
it is working!
@Neptunium1129 did you run into a ReferenceError: self is not defined
error? I get then in my svelte app when I import it like that
@Neptunium1129 did you run into a
ReferenceError: self is not defined
error? I get then in my svelte app when I import it like that
any solution?
@Neptunium1129 did you run into a
ReferenceError: self is not defined
error? I get then in my svelte app when I import it like thatany solution?
The html2pdf.js library uses self to refer to the global scope, which is not defined in a server-side rendering (SSR) environment like SvelteKit.
To fix this issue, you can dynamically import html2pdf.js on the client-side only. You can use the onMount function from Svelte to ensure the code runs only in the browser after the component has been mounted.
let html2pdf;
onMount(async () => {
const module = await import('html2pdf.js');
html2pdf = module.default;
});