How to render a PDF in React.js?

Member

by beaulah , in category: JavaScript , a year ago

How to render a PDF in React.js?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by marcella.kautzer , a year ago

@beaulah 

Member

by marina , 7 months ago

@beaulah 

There are multiple libraries available to render PDF in React.js. One popular library is React-PDF.


You can start by installing the library using npm or yarn:

1
npm install react-pdf


Once the installation is complete, you can import the necessary components in your React component and render the PDF. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
import React from 'react';
import { Document, Page } from 'react-pdf';

const MyPDFViewer = () => {
  const pdfURL = 'https://example.com/my-file.pdf';

  return (
    <div className="pdf-container">
      <Document file={pdfURL}>
        <Page pageNumber={1} />
      </Document>
    </div>
  );
}

export default MyPDFViewer;


In the above example, we import the Document and Page components from react-pdf. We provide the file prop to the Document component that accepts the URL or file path of the PDF. Finally, we render the first page using the Page component.


You can customize the PDF viewer's appearance and behavior as per your requirements using various props provided by the library.


Note: Make sure to include the necessary CSS stylesheets for the library to render the PDF properly. The official documentation of React-PDF provides more detailed examples and guidance on how to render PDF in React.js.