Skip to main content Skip to footer

How to Load & View PDF Files in a React Application

Quick Start Guide
Tutorial Concept

React PDF Viewer - Add the ability to view PDF files in React applications. The Documents Solutions PDF Viewer makes it possible to add this functionality and other document management options to web applications.

What You Will Need

NPM @mescius/dspdfviewer
Visual Studio Code
React 19 or Later

Controls Referenced

Document Solutions PDF Viewer - React PDF Viewer Control

Online Demo Explore | Documentation

The Document Solutions PDF Viewer (DsPdfViewer) is a React PDF Viewer, included with Document Solutions for PDF, that enables users to view and edit PDF files directly in the browser— including interactive PDF forms. Compatible with all modern browsers, it also allows users to save their modified PDFs on the client side. In this article, we’ll show you how to integrate the Document Solutions PDF Viewer into a React application, giving users a seamless way to interact with PDF content in-browser.

Load and View PDF Files in a React PDF Control | Developer Solution

Download a finished React sample app to follow along with the blog!

Steps for Loading & Viewing PDFs in React Apps: Viewer Integration and Loading Methods

Download a Trial of Document Solutions for PDF and the PDF Viewer Control Today!


Integrate the React PDF Viewer Control into the React Project

First, you will need to create a basic React app. In this example, we will be using Vite as our build tool.

npm create vite@latest dspdfviewer-react -- --template react

Note, you will be asked to select a framework and a variant. We will be using React as our framework, of course. You can select the variant that applies to you if, for example, you want to use TypeScript. For this sample, we will simply select JavaScript:

Vite project set up for the React Framework

Next, run the commands as shown above: 

cd dspdfviewer-react
npm install
npm run dev

Now we can install the Document Solutions PDF Viewer NPM package. Optionally, you can additionally install bootstrap for styling.

npm install @mescius/dspdfviewer
npm install bootstrap

After the installation is complete, all of the required files are installed in the node_modules → @mescius → dspdfviewer folder, as depicted below:

React Vite Project Folder | NPM install for a React PDF Viewer | Document Solutions DsPdfViewer

Update the index.html file by adding an “app” div to the template in order to create a host element for the React PDF Viewer.

<!--index.html-->
<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="/vite.svg" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>DsPdfViewer | Vite + React</title>
  </head>
  <body>
    <div id="root"></div>
    <div id="app" class="app-viewer"></div>
    <script type="module" src="/src/main.jsx"></script>
  </body>
</html>

In the main.jsx file, it is recommended that StrictMode is removed from the template. Leaving StrictMode enabled generally causes compatibility issues with the PDF Viewer and can lead to problems such as double-mounting or duplicate initialization. Additionally, you must import createRoot from react-dom. 

//main.jsx
import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App.jsx'

createRoot(document.getElementById('root')).render(
    <App />
)

Set the CSS styling for the React PDF Viewer’s host element in the index.css class by replacing the template contents with the following:

/*index.css*/
.app-viewer {
  width: 100%;
  height: calc(100vh - 10px);
}

Last but not least, replace the contents of the App.jsx file with the following code to initialize the React PDF Viewer and add the default set of sidebar panels.

//app.jsx
import * as React from 'react';
import * as ReactDOM from 'react-dom/client';
import './app.css';
import { DsPdfViewer } from '@mescius/dspdfviewer';

class App extends React.Component {
  // Store the viewer instance
  _viewer = null;
 
  // Create ref for the viewer DOM element
  viewerRef = React.createRef();

  componentDidMount() {
    // Get the DOM node via ref instead of findDOMNode
    const viewerContainer = this.viewerRef.current;
   
    if (!viewerContainer) {
      console.error('Viewer container element not found');
      return;
    }

    try {
      // Initialize the PDF viewer
      const viewer = new DsPdfViewer(viewerContainer);     
      viewer.addDefaultPanels();
      this._viewer = viewer;
    } catch (error) {
      console.error('Failed to initialize DsPdfViewer:', error);
    }
  }
 
  componentWillUnmount() {
    // Clean up the viewer instance
    if (this._viewer) {
      this._viewer.dispose();
      this._viewer = null;
    }
  }

  render() {
    // Attach the ref to the viewer container
    return <div id="viewer" ref={this.viewerRef}></div>;
  }
}
export default App;

// Root element where the app will be mounted
const appContainer = document.getElementById('app');

// Use modern createRoot API if available (React 18+),
// otherwise fall back to legacy render (React 17)
if (typeof ReactDOM.createRoot === 'function') {
  const root = ReactDOM.createRoot(appContainer);
  root.render(<App />);
} else {
  ReactDOM.render(<App />, appContainer);
}

Once completed, the React application will now show an empty PDF viewer control on load.

A React App  with an Empty PDF Viewer and Default Controls/Panels

Check out the online React PDF Viewer demo and documentation to learn more about this developer friendly PDF viewer control.


Load or Open a Default PDF Template

With the application configured and the Document Solutions PDF Viewer successfully rendered in the browser, we can now load and display a PDF file within the viewer. In this example, we'll load a local PDF file stored in the React project directory at public/pdfs/social_media_schedule.pdf.

To render the PDF, use the open method provided by DsPdfViewer, passing in the relative file path as an argument. 

viewer.open("./public/pdfs/social_media_schedule.pdf");

Notice, the specified PDF will now appear on load in the React PDF Viewer.

React App| Loading a PDF into a JS Viewer/Editor Control | Developer Solution

The PDF Viewer API also provides an openLocalFile method, which allows the user to choose the PDF that they want to load into the DsPdfViewer using the file open dialog.


Load or Open a PDF from a URL

In addition to loading local files, you can also open PDFs hosted on the same domain as your React application. To do this, use the open method and pass the URL of the PDF as an argument:

viewer.open("/document-solutions/javascript-pdf-viewer/demos/product-bundles/assets/pdf/helloworld.pdf");

This method works for any PDF file that is accessible within your app’s domain. Once called, the viewer will fetch and render the specified PDF directly in the browser.

Loading PDF from URL into React App using a JS PDF Viewer Control

Test the above code here in the online React PDF Viewer demo sample.


Load or Open a PDF from Another Domain URL using a CORS Proxy

To load a PDF from another domain, use the SupportApi configuration to avoid CORS issues. SupportApi is a lightweight ASP.NET Core service included with Document Solutions for PDF that acts as a proxy for loading and processing remote PDFs.

The supportApi object in the viewer config enables this, and you’ll also need to create a CorsProxyController on the server to download and stream remote files.

Start by adding the following controller to your SupportApi ASP.NET Core project:

[ApiController]
[Route("[controller]")]
public class CorsProxyController : ControllerBase
{
    private readonly IHttpClientFactory _httpClientFactory;
    public CorsProxyController(IHttpClientFactory httpClientFactory) => _httpClientFactory = httpClientFactory;

    [HttpGet]
    public async Task<IActionResult> Get(string url)
    {
        if (string.IsNullOrEmpty(url)) return BadRequest("Missing 'url' query parameter.");
        var client = _httpClientFactory.CreateClient();
        var response = await client.GetAsync(url);
        if (!response.IsSuccessStatusCode) return StatusCode((int)response.StatusCode);
        var stream = await response.Content.ReadAsStreamAsync();
        var contentType = response.Content.Headers.ContentType?.ToString() ?? "application/pdf";
        return File(stream, contentType);
    }
}

Make sure to register the HTTP client in Program.cs. Additionally, you may need to configure the CORS service and policy as needed:

//Add CORS
builder.Services.AddCors(options =>
{
    //Configure the CORS policy
    options.AddPolicy("AllowAll", policy =>
    {
        policy.AllowAnyOrigin()
              .AllowAnyMethod()
              .AllowAnyHeader();
    });
});
//Register HTTP client
builder.Services.AddHttpClient();
builder.Services.AddControllers();
GcPdfViewerHub.ConfigureServices(builder.Services);

//Server side signing implementation
var app = builder.Build();
//Use CORS with custom policy
app.UseCors("AllowAll");

In your React component, set up the viewer with the supportApi config pointing to your backend, and call the open method provided by DsPdfViewer, passing in the proxy endpoint:

  componentDidMount() {
    const viewerContainer = this.viewerRef.current;
   
    if (!viewerContainer) {
      console.error('Viewer container element not found');
      return;
    }

    try {
      const viewer = new DsPdfViewer(viewerContainer, {
        workerSrc: "https://cdn.mescius.com/ds-pdfviewer/latest/dspdfviewer.worker.js",
        restoreViewStateOnLoad: false,
        supportApi: {
          apiUrl: "https://localhost:7126",
          token: "support-api-demo-net-core-token-2021",
          webSocketUrl: false
        }
      });
      viewer.addDefaultPanels();
      viewer.open("https://localhost:7126/CorsProxy?url=https://cdn.mescius.io/sites/developer/legal/eula/ds/20250401-DOCUMENTS-EULA.pdf");
    } catch (error) {
      console.error('Failed to initialize DsPdfViewer:', error);
    }
  }

Once configured, the React app will be able to open PDFs from external domains without hitting CORS issues, using an ASP.NET Core app as a secure proxy.

Load or Open a PDF from Another Domain URL into a React app using a CORS Proxy

Conclusion

This completes the basics of configuring the Document Solutions PDF Viewer in an React application. Download the React sample that we built throughout the article to check it out. Make sure to install the DsPdfViewer NPM package to get the sample working.

You can also refer to this online demo to observe the sample in action and go through the implementation details.

Download a Trial of Document Solutions for PDF and the PDF Viewer Control Today!


React PDF Viewer Control

This article just scratches the surface of the full capabilities of the React PDF Viewer, Document Solutions PDF Viewer, included with Document Solutions for PDF. Check out the online demo explorer and documentation to learn more about this powerful control.

Tags:

comments powered by Disqus