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:
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.
3. How It Works
Base64 Decoding: The
openDocumentModal
function decodes the base64 data and converts it into a binary format usingwindow.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
) usingURL.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.
Last updated