Skip to main content Skip to footer

How to Load & View PDF Files in an Angular Application

Quick Start Guide
What You Will Need

Document Solutions PDF Viewer

NPM

VisualStudio Code

Controls Referenced Document Solutions PDF Viewer
Tutorial Concept Angular PDF Viewer - Add the ability to view PDF files in Angular applications. The Documents Solutions PDF Viewer makes it possible to add this functionality and other document management options to web applications.

The Document Solutions PDF Viewer is an Angular PDF Viewer that allows you to view and edit PDFs on the web, including PDF forms. It works on all modern browsers and helps users save the modified PDF file on the client. In this article, we’ll discuss how you can integrate the Document Solutions Angular PDF Viewer (DsPdfViewer) control into an Angular application, allowing your users to view and modify PDF content in the browser window. 

In this article, we’ll be covering the following topics:

Integrate the Angular PDF Viewer Control into the Angular Project

The steps below will walk you through creating an Angular application and configuring the Angular PDF Viewer within the application.

Work on PDFs in Angular on your own by downloading a FREE trial of Document Solutions for PDF!

Step 1: Set Up the Environment

Before we can start, we must ensure that we have the proper software set up to create an Angular application. To do so, we’ll need the following:

  • Node.js: Download the latest version of Node.js according to your system configuration from here and run the installer to install it.
  • Angular CLI: To install the Angular CLI, open a terminal window and run the following command:
npm install -g @angular/cli

For detailed steps on setting up an Angular project, refer to the following guide here.

Step 2: Create an Angular Application

  • Open a terminal and navigate to the directory where you want to create your application.
  • Run the following CLI command, passing the project name to create a new Angular project named “pdf-viewer-app”:
ng new pdf-viewer-app

Note: The project has been configured based on the following settings, chosen when prompted while creating the Angular application:

Angular PDF Viewer_Configuration

The project folder with all of the expected folders and files gets created at the specified location as shown below:

Angular PDF Viewer_Project Folders

Refer to this link for detailed steps on creating an Angular application.

Step 3: Configure the Application to Integrate Document Solutions PDF Viewer

To install the Document Solutions Angular PDF Viewer NPM package, we need to navigate to the application’s project folder by running the following command:

cd pdf-viewer-app

Then, install the Document Solutions PDF Viewer NPM package by running the following command:

npm install @mescius/gcpdfviewer

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

Angular PDF Viewer_Required Files

Now, navigate to the project’s app.component.html file and replace the contents with the following markup:

<div id="viewer"></div>

Next, we will import the Document Solutions Angular PDF Viewer component into the Angular application from the NPM package we’ve installed. In addition, we’re going to initialize the PDF Viewer in the ngAfterViewInit method inside of the app.component.ts file:

import { Component, AfterViewInit } from "@angular/core";
import { GcPdfViewer } from "@grapecity/gcpdfviewer";

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  stylesUrls: ['./app.component.less']
})

export class AppComponent implements AfterViewInit {
  title: 'pdf-viewer-app';
  
  ngAfterViewInit() {
    const viewer = new GcPdfViewer("#viewer", {
      workerSrc: "//node_modules/@grapecity/gcpdfviewer/gcpdfviewer.worker.js",
      restoreViewStateOnLoad: false
    });
    viewer.addDefaultPanels();
  }
}

The code above sets the workerSrc viewer option to enhance PDF loading and rendering performance. In addition, it sets the restoreViewStateOnLoad option and invokes the addDefaultPanels method to add default panels to the viewer.

Next, we need to update the project configuration. Open the angular.json file, find the budgets keyword, and increase the maximumWarning and maximumError budgets as follows:

"budgets": [
  {
    "type": "initial",
    "maximumWarning": "8mb",
    "maximumError": "10mb"
  }
]

In the angular.json file, look for the "build" object and add the allowedCommonJsDependencies option:

"build": {
  "builder": "@angular-devkit/build-angular:browser",
  "options": {
    "allowedCommonJsDependencies": [
      "grapecity/gcpdfviewer"
    ],
  }
}

Finally, run the application by executing the following command:

ng serve --open

After the application compiles, the Document Solutions Angular PDF Viewer control will display within the browser. The image below depicts the empty DsPdfViewer loaded into the browser window:

Angular PDF Viewer_Empty Viewer

Load or Open a Default PDF Template

With the application configured and the DsPdfViewer loaded into the browser window, we will now load and render a PDF in the DsPdfViewer. This section describes loading a local file existing in the application folder pdf-viewer-app → src → assets → pdf → <PDF File>.

The open method of the DsPdfViewer is invoked by passing in the filename as a parameter in order to load the PDF into the viewer. The code below loads the PDF newsletter.pdf into the DsPdfViewer:

import { Component, AfterViewInit } from "@angular/core";
import { GcPdfViewer } from "@grapecity/gcpdfviewer";

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  stylesUrls: ['./app.component.less']
})

export class AppComponent implements AfterViewInit {
  title: 'pdf-viewer-app';
  
  ngAfterViewInit() {
    const viewer = new GcPdfViewer("#viewer", {
      workerSrc: "//node_modules/@grapecity/gcpdfviewer/gcpdfviewer.worker.js",
      restoreViewStateOnLoad: false
    });
    viewer.addDefaultPanels();
    viewer.open("assets/pdf/newsletter.pdf");
  }
}

When we run the application, we can see the PDF being rendered by the Angular PDF Viewer:

Angular PDF Viewer

The DsPdfViewer also provides the 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

Next, we move on to the scenario of loading a PDF from a URL. The PDF URL can either be available within the same domain where the application has been hosted or be a URL in another domain. 

To load a PDF from a URL (from the same domain as the hosted application), we will again use the open() method of the DsPdfViewer and pass the URL as a parameter to the method. You can see the implementation below:

import { Component, AfterViewInit } from "@angular/core";
import { GcPdfViewer } from "@grapecity/gcpdfviewer";

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  stylesUrls: ['./app.component.less']
})

export class AppComponent implements AfterViewInit {
  title: 'pdf-viewer-app';
  
  ngAfterViewInit() {
    const viewer = new GcPdfViewer("#viewer", {
      workerSrc: "//node_modules/@grapecity/gcpdfviewer/gcpdfviewer.worker.js",
      restoreViewStateOnLoad: false
    });
    viewer.addDefaultPanels();
    viewer.open("/documents-api-pdf/docs/offlinehelp.pdf");
  }
}

You can see the output of the DsPdfViewer below:

Angular PDF Viewer_Output

You can test the above code in this demo.

Load or Open a PDF from Another Domain URL

Finally, we come to the scenario of loading a PDF from a remote URL, which may result in a CORS error based on the same origin policy. To overcome this error, the DsPdfViewer API provides the corsProxy() method in SupportApi to load a PDF from a remote URL without triggering a CORS error.

SupportAPI is a server-side ASP.NET Core library that ships as C# source code with DsPdf and allows you to easily set up a server that uses DsPdf to provide PDF modification features to the PDF Viewer. We’ll host this library as a service in the Angular application to consume the library on the client side.

To accomplish this, place the WebAPI project and the following two script files, run and supportapi, in the project folder.

Next, we need to update the AppComponent class to include a reference to the SupportApi service, along with passing the remote URL to the DsPdfViewer open() method, as shown below:

import { Component, AfterViewInit } from "@angular/core";
import { GcPdfViewer } from "@grapecity/gcpdfviewer";

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  stylesUrls: ['./app.component.less']
})

export class AppComponent implements AfterViewInit {
  title: 'pdf-viewer-app';
  
  ngAfterViewInit() {
    const viewer = new GcPdfViewer("#viewer", {
      workerSrc: "//node_modules/@grapecity/gcpdfviewer/gcpdfviewer.worker.js",
      restoreViewStateOnLoad: false,
      supportApi: {
        apiUrl: "http://localhost:5004/api/pdf-viewer",
        token: "support-api-demo-net-core-token-2021",
        webSocketUrl: false
      }
    });
    viewer.addDefaultPanels();
    viewer.open("http://localhost:5004/api/pdf-viewer/CorsProxy?url=https://www.africau.edu/images/default/sample.pdf");
  }
}

After making the required changes, running the application will show the following output in the browser:

Angular PDF Viewer_PDF File

Conclusion

This completes the basics of configuring the Document Solutions Angular PDF Viewer in an Angular application. Download the 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 demo to observe the sample in action and go through the implementation details.

Work on PDFs in Angular on your own by downloading a FREE trial of Document Solutions for PDF.

Explore other powerful and helpful features of the Document Solutions PDF Viewer through demos and documentation.

Tags:

comments powered by Disqus