How to Load & View PDF Files in an Angular Application
Tags: webdev, devops, angular, tutorial
Published: 2022-08-19 20:30:50

---
canonical_url: https://developer.mescius.com/blogs/how-to-load-and-view-pdf-files-in-an-angular-application
description: Learn how to load & view PDF files in an Angular application. See more today.
---
**What You Will Need**
- Visual Studio
- Ds.Documents.Excel NuGet Package

**Controls Referenced**
- [Ds.Documents.Excel](https://developer.mescius.com/document-solutions/dot-net-excel-api/docs/online/overview.html)

**Tutorial Concept**

C# Excel Templates - Using a C# .NET Excel API, retail-style product labels can be created using Excel document templates.

---
The [Document Solutions PDF Viewer](https://developer.mescius.com/documents-api-pdf/javascript-pdf-viewer "https://developer.mescius.com/documents-api-pdf/javascript-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](#Integrate)
*   [Load or Open a Default PDF Template](#Default)
*   [Load or Open a PDF from a URL](#Open)
*   [Load or Open a PDF from Another Domain URL](#Another)

## <a id="Integrate"></a>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.

### 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](https://nodejs.org/en/ "https://nodejs.org/en/"): 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](https://angular.io/guide/setup-local "https://angular.io/guide/setup-local").

### 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](//cdn.mescius.io/umb/media/lfnnmbt3/s1-2.png)

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](//cdn.mescius.io/umb/media/eeohcbde/project_folder.png?rmode=max&width=727&height=354)

Refer to [this link](https://angular.io/tutorial/toh-pt0 "https://angular.io/tutorial/toh-pt0") 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](//cdn.mescius.io/umb/media/ve2jbova/required-files.png?rmode=max&width=722&height=268)

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](https://developer.mescius.com/documents-api-pdfviewer/api/classes/gcpdfviewer.html#adddefaultpanels "https://developer.mescius.com/documents-api-pdfviewer/api/classes/gcpdfviewer.html#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](//cdn.mescius.io/umb/media/cxpicozg/empty_viewer.png?rmode=max&width=685&height=497)

## <a id="Default"></a>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](https://developer.mescius.com/documents-api-pdfviewer/api/classes/gcpdfviewer.html#open "https://developer.mescius.com/documents-api-pdfviewer/api/classes/gcpdfviewer.html#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](//cdn.mescius.io/umb/media/db1njeon/06-image.png?rmode=max&width=736&height=621)

The DsPdfViewer also provides the [openLocalFile()](https://developer.mescius.com/document-solutions/javascript-pdf-viewer/api/classes/gcpdfviewer.html#openlocalfile "https://developer.mescius.com/document-solutions/javascript-pdf-viewer/api/classes/gcpdfviewer.html#openlocalfile") method, which allows the user to choose the PDF that they want to load into the DsPdfViewer using the file open dialog.

## <a></a><a></a><a id="Open"></a>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("https://developer.mescius.com/documents-api-pdf/docs/offlinehelp.pdf");
      }
    }
```

You can see the output of the DsPdfViewer below:

![Angular PDF Viewer_Output](//cdn.mescius.io/umb/media/ttybue5r/07-image.png?rmode=max&width=748&height=299)

You can test the above code in this [demo](https://developer.mescius.com/documents-api-pdfviewer/demos/reference-samples/Angular/angular-example/angular "https://developer.mescius.com/documents-api-pdfviewer/demos/reference-samples/Angular/angular-example/angular").

## <a id="Another"></a>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](https://developer.mescius.com/documents-api-pdf/docs/online/configure-pdf-editor.html?highlight=supportapi, "https://developer.mescius.com/documents-api-pdf/docs/online/configure-pdf-editor.html?highlight=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](https://gccontent.blob.core.windows.net/gccontent/blogs/gcdocuments/20230922-how-to-load-and-view-pdf-files-in-an-angular-application/WebApi.zip "https://gccontent.blob.core.windows.net/gccontent/blogs/gcdocuments/20230922-how-to-load-and-view-pdf-files-in-an-angular-application/WebApi.zip") and the following two script files, [run](https://cdn.mescius.io/umb/media/drodg11t/run.cmd) and [supportapi](https://cdn.mescius.io/umb/media/st2pixih/supportapi.cmd), 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](//cdn.mescius.io/umb/media/b20bmbrp/08-image.png?rmode=max&width=733&height=450)

## Conclusion

This completes the basics of configuring the Document Solutions Angular PDF Viewer in an Angular application. [Download the sample](https://cdn.mescius.io/umb/media/ryposf2r/viewer-app.zip) 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](https://developer.mescius.com/documents-api-pdfviewer/demos/reference-samples/Angular/angular-example/angular "https://developer.mescius.com/documents-api-pdfviewer/demos/reference-samples/Angular/angular-example/angular") to observe the sample in action and go through the implementation details.

Explore other powerful and helpful features of the Document Solutions PDF Viewer through [demos](https://developer.mescius.com/documents-api-pdfviewer/demos/ "https://developer.mescius.com/documents-api-pdfviewer/demos/") and [documentation](https://developer.mescius.com/documents-api-pdf/docs/online/grapecitydocumentspdfviewer.html "https://developer.mescius.com/documents-api-pdf/docs/online/grapecitydocumentspdfviewer.html").