> For the complete documentation index, see [llms.txt](https://wisdom.gitbook.io/gyan/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://wisdom.gitbook.io/gyan/angular/how-to-open-a-pdf-or-an-image-in-angular-without-dependencies.md).

# 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:

```html
<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.

```typescript
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.
