Wisdom
  • Welcome
  • core
    • Flyway
    • Bean Validation
    • Lombok
    • Webclient
      • Generic Webclient Api
      • SSL Certificate
    • Application Event Publisher
    • REST API's Design
      • Http Methods and Status Codes
      • Resource Naming and URL Structure
      • Request / Response Design
      • Versioning Strategies
      • Filtering and Searching In API
    • Spring Boot Mail Integration
      • Sendgrid
    • Template Engines
      • Java Template Engine [JTE]
  • security
    • Complete Guide to URL Matchers in Spring Security: Types, Examples, Pros, Cons, and Best Use Cases
    • Passwordless Login With Spring Security 6
      • Spring Security OneTimeToken
        • One Time Token with default configuration
        • One Time Token with custom configuration
        • One Time Token With Jwt
  • others
    • How to Integrate WhatsApp for Sending Messages in Your Application
  • java
    • Interview Questions
      • Constructor
      • Serialization
      • Abstract Class
    • GSON
      • Type Token
      • Joda Datetime Custom Serializer and Deserializer
  • Nginx
    • Core Concepts and Basics
    • Deep Dive on NGINX Configuration Blocks
    • Deep Dive on NGINX Directives
    • Deep Dive into Nginx Variables
    • Nginx as a Reverse Proxy and Load Balancer
    • Security Hardening in NGINX
    • Performance Optimization & Tuning in NGINX
    • Dynamic DNS Resolution in Nginx
    • Advanced Configuration & Use Cases in NGINX
    • Streaming & Media Delivery in NGINX
    • Final Configuration
  • Angular
    • How to Open a PDF or an Image in Angular Without Dependencies
    • Displaying Colored Logs with Search Highlighting in Angular 6
    • Implementing Auto-Suggestion in Input Field in Angular Template-Driven Forms
    • Creating an Angular Project Using npx Without Installing It Globally
    • Skip SCSS and Test Files in Angular with ng generate
  • Javascript
    • When JavaScript's Set Falls Short for Ensuring Uniqueness in Arrays of Objects
    • Demonstrating a Function to Get the Last N Months in JavaScript
    • How to Convert Numbers to Words in the Indian Numbering System Using JavaScript
    • Sorting Based on Multiple Criteria
  • TYPESCRIPT
    • Using Omit in TypeScript
Powered by GitBook
On this page
  1. Angular

How to Open a PDF or an Image in Angular Without Dependencies

In this article, we'll walk through a simple way to display PDF documents or images in an Angular application without relying on any external libraries. By leveraging Angular's built-in functionality and browser features, you can create an efficient document viewer. Below, I will show you a code example of how to display a PDF or image in a modal view without any third-party dependencies.

Step-by-Step Guide

1. Setting Up the HTML Template

We will use a modal to display the PDF or image, and the object tag will be used for the PDF rendering. We will also use img for rendering image files. Here's the basic HTML structure:

<div *ngIf="fileUrl != null && (this.isPdf || this.isImage)" class="fixed inset-0 bg-gray-800 bg-opacity-50 flex z-[60] justify-center items-center backdrop-blur-md">
  <div class="bg-white w-[90%] h-[90%] rounded-lg flex flex-col">
    <div class="flex justify-between items-center p-4 border-b">
      <h2 class="text-lg font-semibold">Document Viewer</h2>
      <button class="text-gray-500 hover:text-gray-700" (click)="closePdf()">×</button>
    </div>
    
    <div *ngIf="isPdf; else imageTemplate">
      <!-- PDF Rendering -->
      <object [attr.data]="fileUrl" type="application/pdf" width="100%" height="800">
        <p>Your browser does not support PDFs. <a [href]="fileUrl" download="document.pdf">Download PDF</a></p>
      </object>
    </div>
    
    <!-- Image Rendering -->
    <ng-template #imageTemplate>
      <img *ngIf="isImage" [src]="fileUrl" alt="Preview" style="max-width: 100%; max-height: 800px;"/>
    </ng-template>
  </div>
</div>

2. Component Code

In the TypeScript component, we'll handle the logic to determine whether the file is a PDF or an image, and we'll convert the base64-encoded document data into a usable URL.

import { Component } from '@angular/core';
import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser';

@Component({
  selector: 'app-document-viewer',
  templateUrl: './document-viewer.component.html',
  styleUrls: ['./document-viewer.component.css']
})
export class DocumentViewerComponent {
  isPdf = false;
  isImage = false;
  fileUrl: SafeResourceUrl | null = null;
  private sanitizer: DomSanitizer;

  constructor(sanitizer: DomSanitizer) {
    this.sanitizer = sanitizer;
  }

  openDocumentModal(doc: any) {
    console.log(doc);
    this.selectedDocument = doc;
    
    // Decode base64 to binary data
    const binaryString = window.atob(doc.fileBase64);
    const len = binaryString.length;
    const bytes = new Uint8Array(len);
    for (let i = 0; i < len; i++) {
      bytes[i] = binaryString.charCodeAt(i);
    }

    // Create a Blob from the binary data
    const blob = new Blob([bytes], { type: doc.contentType });
    const blobUrl = URL.createObjectURL(blob);
    
    // Determine if the document is a PDF or an image
    this.isPdf = doc.contentType === 'application/pdf';
    this.isImage = doc.contentType.startsWith('image/');
    
    // Assign the URL for rendering, no need of html part and comment this, if you want to open in new tab
    this.fileUrl = this.sanitizer.bypassSecurityTrustResourceUrl(blobUrl);

    // Optionally, open the document in a new tab
    // window.open(blobUrl, '_blank');
  }

  closePdf() {
    // Revoke object URL and reset flags
    window.URL.revokeObjectURL(this.fileUrl as string);
    this.fileUrl = null;
    this.isPdf = false;
    this.isImage = false;
  }
}

3. How It Works

  • Base64 Decoding: The openDocumentModal function decodes the base64 data and converts it into a binary format using window.atob. This allows us to work with the actual file content.

  • Blob Creation: A Blob object is created from the decoded data, which is then used to create an object URL (blobUrl) using URL.createObjectURL. This URL represents the file, which can be opened and viewed.

  • Type Detection: We check the contentType of the document to determine whether it's a PDF or an image. Based on this, we display the file accordingly using the <object> tag for PDFs and an <img> tag for images.

  • Safe Resource URL: To ensure safe handling of URLs, Angular's DomSanitizer is used to bypass security restrictions when displaying the file.

  • Close Functionality: The closePdf function revokes the object URL and resets flags to ensure the modal can be safely closed.

4. No External Dependencies

This approach does not rely on any external libraries or dependencies such as pdf.js or ng2-pdf-viewer. Everything is handled with standard Angular features, HTML tags, and native JavaScript functions. The file rendering process is done using standard HTML elements (<object> for PDFs and <img> for images) that are natively supported by modern browsers.

5. Additional Considerations

  • Browser Support: Most modern browsers support viewing PDFs and images directly using the <object> and <img> tags. However, be aware that older browsers might not render PDFs correctly.

  • Performance: When working with large PDF files or images, consider optimizing the file sizes and using lazy loading techniques to improve performance.

  • Error Handling: Ensure to handle cases where the file type is unsupported or the file URL is broken, offering a fallback experience for users.

Conclusion

By following this approach, you can easily implement a document viewer in your Angular application without adding extra dependencies. This method provides a lightweight solution for displaying PDFs and images, making it perfect for simple use cases where you want a minimal footprint.

PreviousFinal ConfigurationNextDisplaying Colored Logs with Search Highlighting in Angular 6

Last updated 3 months ago