A guide to implementing PDF.js within an Angular 2/4/5 application

I am currently working on creating a PDfViewer Application using Mozilla's PDF.js (see example here). I would greatly appreciate it if anyone knows of a Github project that I could use as reference.

Thank you in advance!

Answer №1

Using PDF.js with typings in Angular 10

If you find yourself needing to work with PDF.js directly within Angular 10, without the need to create a separate component, ng2-pdf-viewer could be a useful solution.

Below are the steps to make this work seamlessly in Angular 10:

  • npm i pdfjs-dist
  • npm i @types/pdfjs-dist

Importing and Usage Instructions. Make sure to set

GlobalWorkerOptions.workerSrc = pdfWorkerSrc;
:

import { getDocument, GlobalWorkerOptions, PDFDocumentProxy, PDFRenderParams, version, ViewportParameters } from 'pdfjs-dist';

export class MyPdfService {
  private document: Document;

  constructor(@Inject(DOCUMENT) document) {
    this.document = document;
    const pdfWorkerSrc = `https://cdnjs.cloudflare.com/ajax/libs/pdf.js/${version}/pdf.worker.min.js`;
    GlobalWorkerOptions.workerSrc = pdfWorkerSrc;
  }

  // Example use case showcasing strongly typed usage.
  public async convertPdfToImageDataURLAsync(pdfFile: File): Promise<string> {
    const arrayBuffer = await new Response(pdfFile).arrayBuffer();
    const canvas = this.document.createElement('canvas'),
      ctx = canvas.getContext('2d') as CanvasRenderingContext2D,
      data = arrayBuffer;

    const pdf: PDFDocumentProxy = await getDocument(data).promise;
    const page = await pdf.getPage(1);

    const viewPortParams: ViewportParameters = { scale: 2 };
    const viewport = page.getViewport(viewPortParams);

    canvas.height = viewport.height;
    canvas.width = viewport.width;

    const renderContext: PDFRenderParams = {
      canvasContext: ctx,
      viewport: viewport
    };

    const renderedPage = await page.render(renderContext).promise;
    const imageDataURL = canvas.toDataURL();
    if (pdf != null) pdf.destroy();
    return imageDataURL;
  }
}

Answer №2

If you're looking for an alternative to Mozilla's PDF.js, consider using the ng2-pdf-viewer npm module, which utilizes PDF.js in the background. Here's how you can get started:

Installation

npm install ng2-pdf-viewer --save

Note: If you're using Angular 4 or earlier, make sure to use version 3.0.8.

Next, import the module into your app.module.js

import { PdfViewerModule } from 'ng2-pdf-viewer';

@NgModule({
  imports: [BrowserModule, PdfViewerModule],
  declarations: [AppComponent],
  bootstrap: [AppComponent]
})

Finally, integrate it into your component

@Component({
  selector: 'example-app',
  template: `
  <pdf-viewer [src]="pdfSrc" 
              [render-text]="true"
              style="display: block;">
  </pdf-viewer>
})

For more information, check out the following GitHub URL and demo URL.

https://github.com/VadimDez/ng2-pdf-viewer

We hope this guide proves helpful to you.

Answer №3

For those looking to directly integrate pdfjs with Angular, here is a guide on how to do so:

  1. Start by copying the 'web' and 'build' folders from https://github.com/mozilla/pdfjs-dist into your application's assets folder.
  2. Obtain or create your own `Blob() object.
this.http.get(url, { responseType: ResponseContentType.Blob }).map(
(res) => {
  return new Blob([res.blob()], { type: fileType });
});

3. Generate a URL using the blob and pass it to viewer.html

// myBlob object is created from the http call response. Refer to step 2.
const fileUrl = URL.createObjectURL(myBlobObject);
let myFileName = "sample";
var viewerUrl = `assets/pdfjs/web/viewer.html?file=${encodeURIComponent(fileUrl)}&fileName=${sample}.pdf`;
window.open(viewerUrl);

If you choose to follow these steps, keep in mind that manual upgrading of pdfjs may be necessary.

Alternatively, for a simpler solution without the need for manual configurations, consider installing https://www.npmjs.com/package/ng2-pdfjs-viewer and following the provided instructions.

The implementation will be as straightforward as

<ng2-pdfjs-viewer pdfSrc="report.pdf"></ng2-pdfjs-viewer>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Uncover the content of a base64 encoded string and convert it into

A JSON response has been linked on the user's request to retrieve an excel document. The structure of the response is as follows: { "format": // file extn ----only xls "docTitle": //file name "document" :// base 64 encoded data } The attem ...

Enhance the functionality of Spartacus CMS component with a new extension library

I am currently working on developing an Angular library that enhances the functionality of the product-images component within the product details page of Spartacus. Upon customizing a CMS component, I have realized the necessity to include code lines sim ...

Error in initializing UI-router wrapper due to circular dependency in Angular.js

I've been following the angular style guide of John Papa (https://github.com/johnpapa/angular-styleguide#routing) and implementing a custom wrapper for angular ui-router as suggested. However, I'm encountering an issue with the wrapper causing a ...

React is having trouble rendering the current weather information

My code is not functioning properly and I am encountering a TypeError that says "cannot read the property of undefined ('temp')". import React, { useEffect, useState } from "react"; import "./css/style.css"; import { BiStreetV ...

Rendering React component within a production build of Angular 7

I've been in the process of gradually moving an Angular app to React. After exploring options like single-spa and nx, I found that they weren't suitable due to the messy script-injected nature of the existing app. So, I decided to go for a semi-m ...

Utilize TypeScript File array within the image tag in HTML with Angular 2

I am in the process of developing a web application that allows users to upload CSV data and images, which are then displayed on the application. However, I have encountered an issue where I am unable to display the imported images. The images are imported ...

JavaScript: How to Build a Digital Grocery List with Browser Storage

Struggling with a tough exercise question, I could use some help deciphering it. https://i.stack.imgur.com/V5he2.png Here is how I've started the code: <!DOCTYPE html> <html> <head> <title></title> <script> fun ...

Changing the color of the timePicker clock in material-ui: a step-by-step guide

I have been attempting to update the color of the time clock in my timeInput component (material-ui-time-picker) for material-ui, but unfortunately, it is not reflecting the change. Here is the code I am using: <TimeInput style ={heure} ...

What circumstances cause a string not to be considered a string in the context of JWT?

Currently, I am in the process of working with JWT and have a function set up as seen below: export async function decodeJwt(token: string): Promise<string> { console.log('token is a string: ', typeof token === 'string'); con ...

changing pictures with jquery

Struggling with this code snippet: $('#clicked_package').css({"background-image" : "url(img/head_2.png)"}).fadeOut("slow"); $('#clicked_package').css({"background-image" : "url(img/head_2_normal.png)"}).fadeIn("slow"); No matter which ...

The 'canvas' module could not be located in the system.Here are the required stacks:- /var/task/index.js- /var/runtime/index.mjs

I am currently developing a lambda function using the serverless framework. The function utilizes chartjs-node-canvas to create graphics, and everything runs smoothly on my MacBook when tested locally. However, when I deploy the function to AWS either dire ...

Even though the model value is set to true, the material check box remains unchecked

My mat-table contains data and checkboxes. The checkboxes should only be checked when the element.select property is true. However, when I use [(ngModel)]="element.select", all the checkboxes end up getting checked. Below you can find the code snippet: &l ...

Encountering difficulties integrating Bootstrap with Angular CLI project

I am facing an issue while trying to integrate Bootstrap 4 RC6 into my Angular CLI project. Despite following the necessary steps, I am encountering an error that I cannot quite explain. Here is a detailed overview of what I did to create the project: Fir ...

Every time I try to set up the MailChimp pop-up javascript, I encounter an Uncaught Error message saying that Bootstrap tooltips need Tether and an Uncaught ReferenceError message

Utilizing Wordpress and Understrap. Upon inserting the following code: <script type="text/javascript" src="//downloads.mailchimp.com/js/signup- forms/popup/embed.js" data-dojo-config="usePlainJson: true, isDebug: false"> </script><script ty ...

Generating dynamic anchor tags in Vue.JS

I have a JavaScript object that I want to convert into HTML elements and display it in Vue.js. So far, my approach has been to convert the object into strings representing HTML elements and then add them to the template. However, even though this method di ...

Teaching you how to incorporate empty spaces and punctuation within JOI

How can I modify Joi to permit spaces/whitespaces in a title field within a form? Scheduled to work with Jude tomorrow. I want to allow entries like: Morningwalk Currently, only the second example is passing validation. Below is my existing Joi val ...

Identify when the user ceases typing in Angular 2

I am currently working on implementing a feature that detects whether the user is typing or not. I need to determine when the user has stopped typing for at least 3 seconds in order to perform certain actions. I have successfully detected when the user sta ...

The JSON response is returning an undefined value

While working on my react app, I am logging JSON data from the backend of the application. When I log the main body of the data: console.log('........section2', options2ndSection[2]); The returned JSON data is as follows: Object item: ...

Implementing the Tab key functionality without redirecting to the address bar

I recently integrated a Tab control into my project, but I'm encountering an issue where pressing the Tab key causes the address bar to jump when I try to press another key. This only happens after the Tab key functions correctly in the scene. How can ...

Instant urban locator

Is there a way to automatically populate the visitor's city in the membership form? Member Register Form Name: Emre Email:--- Pass:--- City: Istanbul // Automatically detected location How can I implement automatic location detection for the ...