Embedding PDF files directly in your SharePoint Framework (SPFx) web part is a valuable capability that enhances the user experience, eliminating the need to force downloads or open new tabs. In this article, we will show you how to render a PDF in your SPFx web part with support for.
- scrollable pages
- customizable dimensional sizing
- clean page rendering using the react-pdf library
Prerequisites
Before diving in, make sure you have.
- An SPFx React-based web part.
- React-pdf installed.
To install react-pdf and its dependencies.
npm install react-pdf
npm install pdfjs-dist
Then, configure your component to use it.
You can load a PDF and view the entire document using the <Document> and <Page> components from react-pdf. Here is the primary code snippet.
import { Document, Page, pdfjs } from "react-pdf";
import "react-pdf/dist/esm/Page/AnnotationLayer.css";
import "react-pdf/dist/esm/Page/TextLayer.css";
pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.min.js`;
const [numPages, setNumPages] = useState(0);
return (
<div style={{ overflowY: "auto", maxHeight: "600px" }}>
<Document
file={pdfUrl}
onLoadSuccess={({ numPages }) => setNumPages(numPages)}
>
{Array.from({ length: numPages }, (_, index) => (
<Page key={index} pageNumber={index + 1} width={700} />
))}
</Document>
</div>
);
Feature Overview Let's quickly summarize some of the great functionality that comes built-in with react-pdf.
- Scroll Support: The Document is contained within a wrapping element that has overflowY: auto and a maxHeight. This allows users to scroll through the entire document, even if it contains many pages.
- Page Rendering: Each Page is rendered with the Page component. We use:
{ Array.from({ length: numPages }, (_, index) => ( // your JSX or logic here )) } - This generates an array of pages dynamically after the PDF has been loaded.
- Responsive Width (Optional): You have two options for dynamically changing the width: either use useRef and ResizeObserver to make the PDF completely responsive to the size of its containing element, or use the following approach.
- Annotation and Text Layers: If you import.
import "react-pdf/dist/esm/Page/AnnotationLayer.css"; import "react-pdf/dist/esm/Page/TextLayer.css"; - This will also ensure that the functionality of text selection and annotations in a PDF will be functional as if it were a native viewer.
Conclusion
It is simple and useful to render PDFs inside your SPFx web part by using react-pdf. A few lines of code enable your users to view, scroll, and interact with PDFs directly within SharePoint, eliminating the need to download or open external viewers.

Join the conversation! Your thoughts help the community grow.