Skip to content

Instantly share code, notes, and snippets.

@JacobFischer
Created October 1, 2020 01:00
Show Gist options
  • Save JacobFischer/aecbd871cb2aae46993236f65797da5c to your computer and use it in GitHub Desktop.
Save JacobFischer/aecbd871cb2aae46993236f65797da5c to your computer and use it in GitHub Desktop.
import React from 'react';
import {
pdf,
Document,
Page,
Text,
} from '@react-pdf/renderer';
import { saveAs } from 'file-saver';
const DocumentPdf = ({ someString }) => (
<Document>
<Page>
<Text>Hey look at this string: {someString}</Text>
</Page>
</Document>
);
const delay = (t) => new Promise((resolve) => setTimeout(resolve, t));
async function getProps() {
await delay(1_000);
return ({
someString: 'You waited 1 second for this',
});
}
export const LazyDownloadPDFButton = () => (
<button
onClick={async () => {
const props = await getProps();
const doc = <DocumentPdf {...props} />;
const asPdf = pdf({}); // {} is important, throws without an argument
asPdf.updateContainer(doc);
const blob = await asPdf.toBlob();
saveAs(blob, 'document.pdf');
}}
>
Download PDF
</button>
);
@BakriSusanto
Copy link

Thank you so much. It's work now. using
const asPdf = pdf([] as any);

@mhonjester
Copy link

Thank you so much. It's working.

@chaithanyasuraj7878
Copy link

Hi @JacobFischer
Im able to download PDF using your solution, but im not getting any data of images or text which i dynamically fetching to pdf it just shows empty
Any idea how to resolve this please

@gwvwl
Copy link

gwvwl commented Nov 29, 2022

Hello, please tell me what to transfer to asPdf.

@alirezakasirzare
Copy link

thanks a lot, thats work!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment