Skip to main content Skip to footer

How to Load & View PDF Files in an Angular Application

Document Solutions PDF Viewer is a JavaScript PDF Viewer that lets you view and edit PDF files on the web, including PDF forms. It works on all modern browsers and helps the user save the modified PDF file on the client. In this blog, we will understand how we can integrate GrapeCity Documents PDF Viewer (GcPdfViewer) control into an Angular application to create a modern JavaScript application to work with PDF content in the browser window.

The blog sections will help you understand how to create an Angular application and integrate the GcPdfViewer control: 

Integrate the PDF Viewer Control into the Angular Project 

The steps below will guide you in creating an Angular application and configuring the PDF Viewer into the application.

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

Step 1: Setup the Environment

Before we start, the following prerequisites must be set up to create an Angular application:

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

For detailed steps, you may refer to the following guide.

Step 2: Create an Angular Application

  1. Open the command prompt and switch to the destination directory where you want to create the application.
  2. Run the following CLI command passing the project name to create a new Angular project named "viewer-app":
ng new viewer-app

Command Prompt

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

Angular App

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

src

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

Step 3: Configure the Application to Integrate GrapeCity Documents PDF Viewer

To install GrapeCity Documents PDF Viewer NuGet package, we should switch to the Angular application project folder by executing the following command:

cd viewer-app

Command Line

Install GrapeCity Documents PDF Viewer NuGet package using the following command:

npm install @grapecity/gcpdfviewer

After installing the GrapeCity Documents PDF Viewer NuGet package, all the required files are installed in the node_modules → @grapecity → gcpdfviewer folder as depicted below:

docs

Replace the content of the template file (src → app → app.component.html) with the below-defined markup of adding a DIV element to render the GrapeCity Documents PDF Viewer component:

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

Import the GrapeCity Documents PDF Viewer component into an Angular application from the package @grapecity/gcpdfviewer and define the ngAfterViewInitmethod in AppComponent class (src → app → app.component.ts) to initialize the GcPdfViewer control, as depicted in the code below:

import { Component } from '@angular/core';
import { GcPdfViewer } from '@grapecity/gcpdfviewer';
 
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.less']
})
export class AppComponent {
  title = '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 also sets the restoreViewStateOnLoad option, along with invoking the addDefaultPanels method to add default panels to the viewer.

Update project configuration. Open angular.jsonfile, find budgets keyword, and increase 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 allowedCommonJsDependencies option:

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

Now, execute the application using the following command:

ng serve --open

After the successful compilation of the application, the GcPdfViewer control displays on application execution.

The image below depicts the empty GcPdfViewer loaded in the browser window:

ViewerApp

Load or Open a Default PDF Template

The application is now configured, and the GcPdfViewer is loaded in the browser window; let's move on to understand how to load and render a PDF file in GcPdfViewer. This section describes loading a local file existing in the application folder viewer-app → src → assets → pdf → <PDF file>. 

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

import { Component } from '@angular/core';
import { GcPdfViewer } from '@grapecity/gcpdfviewer';
 
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.less']
})
export class AppComponent {
  title = '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");
  }
}

The image below depicts the PDF file loaded in GcPdfViewer:

ViewerApp

GcPdfViewer even provides the openLocalFile to enable the user to choose the PDF file they want to load in GcPdfViewer using the file open dialog.

Load or Open a PDF File from a URL 

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

Here, we discuss the prior scenario, so to load a PDF file from a URL (in the same domain as hosted application), we again use the open method of GcPdfViewer and pass in the URL as a parameter to the open method as depicted in the code below:

import { Component } from '@angular/core';
import { GcPdfViewer } from '@grapecity/gcpdfviewer';
 
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.less']
})
export class AppComponent {
  title = 'viewer-app';
 
  ngAfterViewInit() {
    const viewer = new GcPdfViewer("#viewer", {
      workerSrc: "/documents-api-pdfviewer/demos/product-bundles/build/gcpdfviewer.worker.js",
      restoreViewStateOnLoad: false
    });
    viewer.addDefaultPanels();
    viewer.open("/documents-api-pdf/docs/offlinehelp.pdf");
  }
}

The screenshot below depicts a PDF file loaded from a URL:

URL

You can test the above code in the following demo: /documents-api-pdfviewer/demos/reference-samples/Angular/angular-example/angular.

Load or Open a PDF File from Another Domain URL

Lastly comes the scenario of loading the PDF file from a remote URL, which might result in CORS error based on the same origin policy. To overcome this error, GcPdfViewer API provides the corsProxy method in SupportApi to load a PDF file from a remote URL without any error.

Support API is a server-side ASP.​NET Core library ships as C# source code with GcPdf and allows to easily set up a server that uses GcPdf to provide PDF modification features to GcPdfViewer. Hence, we will host this library as a service in the Angular application project to consume the library on the client side.

To accomplish the same, place the WebApi project and the following two script files: run and supportapi, in the angular application project folder.

Next, we need to update the AppComponent class (src → app → app.component.ts) code to include reference to the SupportApi service along with passing the remote URL to the GcPdfViewer open method, as depicted in the code below:

import { Component } from '@angular/core';
import { GcPdfViewer } from '@grapecity/gcpdfviewer';
 
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.less']
})
export class AppComponent {
  title = 'sample-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 all the suggested changes, execute the run script file from the angular application project folder, and after successful compilation of the project, navigate to http://localhost:4200/ to observe the following output:

Simple PDF File

This completes the basics of configuring GcPdfViewer in an Angular application; you can download the sample implementing the above-defined scenarios from here. Make sure to install the GcPdfViewer package to get the sample working.

You can even refer to the following demo to observe the sample in action and dig into 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 Document Solutions PDF Viewer through demos and documentation.

 

comments powered by Disqus