Articles in this section
Category / Section

How to Implement a Login Page to Give Access to an Angular PDF Viewer?

2 mins read

This article explains how to implement a login page to control access to a PDF Viewer in an Angular PDF Viewer application using the Syncfusion® PDF Viewer component.

After following this guide, users will be able to display a secure login form, authenticate users, and only display the PDF Viewer if the login is successful. This is useful for protecting sensitive documents or restricting access based on user credentials.

Solution:

To control access with a login page, build a login form in your Angular application. Only render or show the PDF Viewer component after a successful authentication. User credentials can be validated within the component or using a backend API in production scenarios.

Prerequisites:

Before diving into the implementation, ensure that the following steps are completed:

  1. Syncfusion PDF Viewer Setup: Make sure the Syncfusion PDF Viewer is installed and set up in your Angular project. Follow the Getting Started with Syncfusion PDF Viewer for Angular guide if you haven’t already.

  2. Basic Knowledge of Angular: Familiarity with Angular components and the basic setup of Angular projects will help you follow along with the implementation.

Code Snippets
Install and Configure Syncfusion PDF Viewer

First, install the necessary Syncfusion PDF Viewer modules and services in your Angular project and import them as needed.

import { Component, ViewEncapsulation, OnInit, ViewChild } from '@angular/core';
import { PdfViewerComponent, LinkAnnotationService, BookmarkViewService, MagnificationService, ThumbnailViewService, ToolbarService, NavigationService, TextSearchService, TextSelectionService, PrintService, AnnotationService, FormFieldsService, FormDesignerService, PageOrganizerService } from '@syncfusion/ej2-angular-pdfviewer';
import { DialogComponent } from '@syncfusion/ej2-angular-popups';
import { AnimationSettingsModel } from '@syncfusion/ej2-splitbuttons;
Create the Login and Dialog UI

To protect access to your PDF documents, you’ll first create a login interface. The code below provides a streamlined login form with feedback messages. Upon successful authentication, authorized users can open and interact with the PDF Viewer inside a modal dialog. This separation ensures that your PDFs remain secure and only accessible after proper validation.

<div class="content-wrapper">
  <!-- Login Form Container -->
  <div class="login-container" *ngIf="!isAuthenticated">
    <div class="login-form">
      <h2>Login to Access PDF Viewer</h2>
      
      <div class="form-group">
        <label for="username">Username</label>
        <input type="text" id="username" [(ngModel)]="userName" placeholder="Enter username" />
      </div>
      
      <div class="form-group">
        <label for="password">Password</label>
        <input type="password" id="password" [(ngModel)]="password" placeholder="Enter password" />
      </div>
      
      <div class="error-message" *ngIf="authError">{{ authError }}</div>
      
      <div class="button-container">
        <button (click)="authenticate()">Login</button>
      </div>
      
      <div class="credentials-info">
        <p><strong>Demo Credentials:</strong></p>
        <p>Username: UserA, Password: admin123</p>
        <p>Username: UserB, Password: user123</p>
      </div>
    </div>
  </div>
  
  <!-- PDF Viewer Control Area (When Authenticated) -->
  <div class="viewer-controls" *ngIf="isAuthenticated">
    <div class="user-info">
      <span>Logged in as: <strong>{{ userName }}</strong></span>
      <button class="logout-btn" (click)="logout()">Logout</button>
    </div>
    <button class="open-pdf-btn" (click)="openPDFViewer()">Open PDF Viewer</button>
  </div>
  
  <!-- PDF Dialog -->
  <ejs-dialog #Dialog [visible]="false" [header]="header" [animationSettings]="animationSettings"
    [showCloseIcon]="showCloseIcon" [target]="target" [width]="width" [height]="height" 
    (open)="dialogOpen()" (close)="dialogClose()">
    <ng-template #content>
      <ejs-pdfviewer #pdfviewer id="pdfViewer" [documentPath]="document" [resourceUrl]="resourceUrl"
        style="height:100%;display:block"></ejs-pdfviewer>
    </ng-template>
  </ejs-dialog>
</div>
User Authentication and PDF Viewer Management Logic

This component handles user authentication and the display of the PDF viewer. It includes logic for validating user credentials, managing authentication state, opening and closing a modal PDF viewer, and persisting PDF state between sessions. The authenticate(), logout(), and openPDFViewer() methods are key to controlling access and user experience when viewing documents.

import { Component, ViewEncapsulation, OnInit, ViewChild } from '@angular/core';
import { PdfViewerComponent, LinkAnnotationService, BookmarkViewService, MagnificationService, ThumbnailViewService, ToolbarService, NavigationService, TextSearchService, TextSelectionService, PrintService, AnnotationService, FormFieldsService, FormDesignerService, PageOrganizerService } from '@syncfusion/ej2-angular-pdfviewer';
import { DialogComponent } from '@syncfusion/ej2-angular-popups';
import { AnimationSettingsModel } from '@syncfusion/ej2-splitbuttons';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  encapsulation: ViewEncapsulation.None,
  providers: [
    LinkAnnotationService,
    BookmarkViewService,
    MagnificationService,
    ThumbnailViewService,
    ToolbarService,
    NavigationService,
    TextSearchService,
    TextSelectionService,
    PrintService,
    AnnotationService,
    FormFieldsService,
    FormDesignerService,
    PageOrganizerService
  ],
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  public title: string = 'PDF Viewer Application';

  @ViewChild('pdfviewer')
  public pdfviewerControl!: PdfViewerComponent;
  
  @ViewChild('Dialog')
  public Dialog!: DialogComponent;
  
  public userName: string = '';
  public password: string = '';
  public isAuthenticated: boolean = false;
  public authError: string = '';
  public base64Strings: any;
  public document: string = 'https://cdn.syncfusion.com/content/pdf/pdf-succinctly.pdf';
  public resourceUrl: string = "https://cdn.syncfusion.com/ej2/30.1.37/dist/ej2-pdfviewer-lib";
  
  // Mock user credentials - in a real app, these would be stored securely
  private validUsers = [
    { username: 'UserA', password: 'admin123' },
    { username: 'UserB', password: 'user123' }
  ];

  ngOnInit(): void {
    // Check if user was previously authenticated in this session
    const savedAuth = sessionStorage.getItem('pdfViewerAuthenticated');
    if (savedAuth === 'true') {
      this.isAuthenticated = true;
      const savedUser = sessionStorage.getItem('pdfViewerUser');
      if (savedUser) {
        this.userName = savedUser;
      }
    }
  }

  // Validates user credentials and opens PDF viewer if successful
  authenticate() {
    // Reset error message
    this.authError = '';
    
    // Check if username and password are provided
    if (!this.userName || !this.password) {
      this.authError = 'Please enter both username and password';
      return;
    }
    
    // Find matching user
    const user = this.validUsers.find(
      u => u.username === this.userName && u.password === this.password
    );
    
    if (user) {
      this.isAuthenticated = true;
      // Store authentication state in session
      sessionStorage.setItem('pdfViewerAuthenticated', 'true');
      sessionStorage.setItem('pdfViewerUser', this.userName);
      
      // Open PDF Viewer with the authenticated user
      this.openPDFViewer();
    } else {
      this.authError = 'Invalid username or password';
      this.isAuthenticated = false;
    }
  }

  // Clears user session and hides PDF viewer
  logout() {
    this.isAuthenticated = false;
    this.userName = '';
    this.password = '';
    sessionStorage.removeItem('pdfViewerAuthenticated');
    sessionStorage.removeItem('pdfViewerUser');
    
    // Close dialog if open
    if (this.Dialog && this.Dialog.visible) {
      this.Dialog.hide();
    }
  }

  // Shows PDF viewer dialog and loads document after authentication check
  openPDFViewer() {
    if (!this.isAuthenticated) {
      this.authError = 'Authentication required!';
      return;
    }
    
    // Set the current user as the author for annotations
    if (this.pdfviewerControl) {
      this.pdfviewerControl.annotationSettings.author = this.userName;
    }
    this.Dialog.show();
    if(this.base64Strings!=undefined)
      this.pdfviewerControl.load(this.base64Strings, '');
    else
      this.pdfviewerControl.load(this.document, '');
  }

  // Dialog configuration properties
  public header: string = 'PDF Viewer';
  public showCloseIcon: Boolean = true;
  public width: string = '100%';
  public height: string = '90%';
  public animationSettings: AnimationSettingsModel = { effect: 'None' };
  public target: string = '.content-wrapper';
  
  // Saves PDF state as base64 on dialog close
  public dialogClose = (): void => {
    if (this.pdfviewerControl) {
      this.pdfviewerControl.saveAsBlob().then((value) => {
        const data = value;
        const reader = new FileReader();
        reader.readAsDataURL(data);
        reader.onload = () => {
          this.base64Strings = reader.result;
        };
      }).catch(error => {
        console.error('Error saving PDF:', error);
      });
    }
  }
  
  // Loads saved PDF data when dialog opens
  public dialogOpen = (): void => {
    if (this.base64Strings && this.pdfviewerControl) {
      this.pdfviewerControl.load(this.base64Strings, '');
    }
  }

}
Key Features Used in the Code:
  1. User Authentication: Secure login that validates username and password before allowing access.
  2. Conditional PDF Viewer Access: The PDF viewer is displayed only to authenticated users, ensuring protected document access.
  3. Session Persistence: Maintains the user authentication state and PDF session data using browser storage for a seamless experience during the session.
Sample Link:

You can find the full sample in our GitHub repository.

Conclusion:

I hope you enjoyed learning How can I implement a login page to control access to an Angular PDF Viewer. By following these steps, you can protect the Syncfusion Angular PDF Viewer using a login mechanism. This approach is suitable for demos and prototypes; for production use, connect the login to your secure, backend authentication.

You can refer to Angular PDF Viewer feature tour page to know about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our Angular PDF Viewer Example to understand how to create and manipulate data.

For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls.

If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, BoldDesk Support, or feedback portal. We are always happy to assist you!

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please  to leave a comment
Access denied
Access denied