create a pdf using react-pdf in javascript

To create a PDF document in React using react-pdf, you first need to install the package using npm or yarn. Open your terminal and run:

index.tsx
npm install react-pdf
22 chars
2 lines

or

index.tsx
yarn add react-pdf
19 chars
2 lines

Once the package is installed, you can import it at the top of your React component file:

index.tsx
import React from 'react';
import { PDFDownloadLink, PDFViewer, Document, Page, Text } from '@react-pdf/renderer';
115 chars
3 lines

Then, you can create a new component and include the <PDFViewer> component to render the PDF document in your application's UI.

index.tsx
const MyPDF = () => (
  <PDFViewer>
    <MyDocument />
  </PDFViewer>
);
73 chars
6 lines

To create a PDF, you'll need to define the MyDocument component, which should return a <Document> component that will contain one or more <Page> components. The <Page> components can contain any content, including text, images, and other React components.

index.tsx
const MyDocument = () => (
  <Document>
    <Page>
      <Text>Hello World!</Text>
    </Page>
  </Document>
);
112 chars
8 lines

Finally, you can add a button or link to download the PDF using the <PDFDownloadLink> component, passing in the MyDocument component as a prop.

index.tsx
const DownloadButton = () => (
  <PDFDownloadLink document={<MyDocument />} fileName="myDocument.pdf">
    {({ blob, url, loading, error }) =>
      loading ? 'Loading document...' : 'Download now!'
    }
  </PDFDownloadLink>
);
229 chars
8 lines

With this setup, users can click the DownloadButton component to generate and download the PDF file. This process can be optimised by using a server-side rendering framework like Node.js, which can generate and serve the PDF document to the client.

gistlibby LogSnag