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.

  1. scrollable pages
  2. customizable dimensional sizing
  3. clean page rendering using the react-pdf library

Prerequisites

Before diving in, make sure you have.

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.

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.