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

I cannot import from cdn on svelte

Open unolife opened this issue 2 years ago • 4 comments

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?

unolife avatar Feb 12 '22 03:02 unolife

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 avatar May 25 '23 08:05 Neptunium1129

@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

bennettcolecohen avatar May 26 '23 15:05 bennettcolecohen

@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?

kevin4dhd avatar Oct 03 '23 19:10 kevin4dhd

@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?

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;
});

ethanfox avatar Feb 23 '24 15:02 ethanfox