Typescript PDFjs encountering loading issues with corrupt files

In my Vue.js application, I have the following TypeScript class:

/** Taken from https://github.com/VadimDez/ng2-pdf-viewer/blob/master/src/app/pdf-viewer/pdf-viewer.component.ts */
import { Component, Vue } from 'vue-property-decorator';

import { PDFDocumentProxy, PDFViewerParams, PDFSource, PDFPromise } from 'pdfjs-dist';

let PDFJS: any;
let PDFJSViewer: any;

PDFJS = require('pdfjs-dist/build/pdf');
PDFJSViewer = require('pdfjs-dist/web/pdf_viewer');

@Component
export default class FileViewer extends Vue {

public pdfLinkService: any;
public pdfViewer: any;
public pdfFindController: any;
private _renderText: boolean = true;
private _externalLinkTarget: string = 'blank';
private _pdf: PDFDocumentProxy;
private src: string | Uint8Array | PDFSource = "http://mozilla.github.io/pdf.js/web/compressed.tracemonkey-pldi-09.pdf";
private cMapsUrl: string = 'https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8bfbefede1f8a6efe2f8ffcbb9a5bba5bfb3b2">[email protected]</a>/build/pdf.js';

mounted(){
    this.setupViewer();
}
static getLinkTarget(type: string) {
    switch (type) {
      case 'blank':
        return (<any>PDFJS).LinkTarget.BLANK;
      case 'none':
        return (<any>PDFJS).LinkTarget.NONE;
      case 'self':
        return (<any>PDFJS).LinkTarget.SELF;
      case 'parent':
        return (<any>PDFJS).LinkTarget.PARENT;
      case 'top':
        return (<any>PDFJS).LinkTarget.TOP;
    }

    return null;
}
static setExternalLinkTarget(type: string) {
    const linkTarget = FileViewer.getLinkTarget(type);

    if (linkTarget !== null) {
      (<any>PDFJS).externalLinkTarget = linkTarget;
    }
}
private getDocumentParams() {
    const srcType = typeof(this.src);

    const params: any = {
      cMapUrl: this.cMapsUrl,
      cMapPacked: true
    };

    if (srcType === 'string') {
      params.url = this.src;
    } else if (srcType === 'object') {
      if ((this.src as any).byteLength !== undefined) {
        params.data = this.src;
      } else {
        Object.assign(params, this.src);
      }
    }

    return params;
}

loadPDF(){
    const loadingTask: any = (PDFJS as any).getDocument(this.getDocumentParams());

    (<PDFPromise<PDFDocumentProxy>>loadingTask.promise)
    .then((pdf: PDFDocumentProxy) => {
        if (this._pdf) {
            this._pdf.destroy();
        }
        this._pdf = pdf;
        this.pdfViewer.setDocument(pdf);
    }, (error: any) => {
        console.log(error);
    });
}

destroy(){
    this._pdf.destroy();
}

public setupViewer() {
    (PDFJS as any).disableTextLayer = !this._renderText;

    FileViewer.setExternalLinkTarget(this._externalLinkTarget);

    this.pdfLinkService = new PDFJSViewer.PDFLinkService();

    let container = document.getElementById('viewerContainer');
    const pdfOptions: PDFViewerParams | any = {
      container: container,
      removePageBorders: false
    //   linkService: this.pdfLinkService
    }

    this.pdfViewer = new PDFJSViewer.PDFViewer(pdfOptions);
    this.pdfLinkService.setViewer(this.pdfViewer);
    this.pdfFindController = new PDFJSViewer.PDFFindController({ pdfViewer: this.pdfViewer });
    this.pdfViewer.setFindController(this.pdfFindController);
    this.loadPDF();
}    
doSomething(){
    this.pdfFindController.executeCommand('find', { query: 'trace', highlightAll: true });
}

While the PDF is loading correctly for page 1, subsequent pages show text overlapping, as seen in these images:

Page 1

https://i.stack.imgur.com/vbuMm.png

Page 2

https://i.stack.imgur.com/GwO0n.png

Page 3

https://i.stack.imgur.com/lkxq3.png

This overlapping text issue on the left side of pages 2 and 3 is something that needs further investigation to determine the root cause.

Have any ideas on what could be causing this problem?

Answer №1

The reason for this issue was a failure to load the PDF viewer CSS file.

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

Customize the theme of Ant Design for VueJS

I have successfully set up my Vue3 application with Tailwind and Ant Design. However, I am facing issues with customizing the Ant Design theme. I have been referring to this guide. When trying to customize the theme, I encountered the following error: Err ...

"Optimize Your Data with PrimeNG's Table Filtering Feature

I'm currently working on implementing a filter table using PrimeNG, but I'm facing an issue with the JSON structure I receive, which has multiple nested levels. Here's an example: { "id": "123", "category": "nice", "place": { "ran ...

What is the best approach to validating GraphQL query variables while utilizing Mock Service Worker?

When simulating a graphql query with a mock service worker (MSW), we need to verify that the variables passed to the query contain specific values. This involves more than just type validation using typescript typings. In our setup, we utilize jest along ...

"Enhancing User Experience with Hover States in Nested React Menus

I have created a nested menu in the following code. My goal is to dynamically add a selected class name to the Nav.Item element when hovering, and remove it only when another Nav.Item is hovered over. I was able to achieve this using the onMouseOver event. ...

What is the best way to send an array of locationIds to the getLocationData service?

Seeking Assistance on Sending an Array of Location IDs to a Service I currently have an array consisting of location IDs. locationArr=[40871, 60009, 38149, 40868, 43240, 15299, 53897, 40976, 38151, 23183, 38152, 78579, 23180, 40977, 23176, 39565, 40884, ...

Contrasts in data manipulation within Vue.js

I have been trying to understand the reason behind this issue, but it remains a mystery to me. Let me share the code and explain the situation. I am baffled by why this problem persists and it's driving me absolutely crazy! Button: <a href=" ...

Using JavaScript/TypeScript to sort through and separate two arrays

Creating a list of checkboxes on a UI allows users to toggle and filter data results. To achieve this, I am storing the selected checkboxes as a string array. The structure of my code is outlined below: export interface IMyObjectFromAPI { status: { ...

A guide to mocking Prisma using Jest mock functionality

Utilizing prisma for database interactions and eager to implement jest-mock to simulate the findMany call. https://jestjs.io/docs/jest-object#jestmockedtitem-t-deep--false brands.test.ts import { PrismaService } from "@services/mysql.service"; i ...

Navigating to a different page in Ionic 2 upon app initialization

Is there a way to automatically redirect the page to the home page instead of displaying the login page if there is already a token stored in localStorage? I currently have the following code in the constructor() of app.component.ts, but it still display ...

A bespoke Typescript implementation of nested lists containing numbers

Currently, I am trying to figure out how to declare and populate a TypeScript list of lists. The structure of the list should be as follows: List<CustomList<>, number> Typically, I would create a standard list like this: someList: { text: a ...

Decorating AngularJS' ExceptionHandler with TypeScript is not feasible because a function is not identified as such

Scenario: In the project I am currently involved in, there has been a transition from utilizing AngularJS (1.6.2) with JavaScript to TypeScript 2.1.5. We had implemented a decorator on the $exceptionHandler service which would trigger a call to a common ...

What is the reason for receiving an error with one loop style while the other does not encounter any issues?

Introduction: Utilizing TypeScript and node-pg (Postgres for Node), I am populating an array of promises and then executing them all using Promise.all(). While pushing queries into an array during iteration over a set of numbers, an error occurs when the ...

Having trouble displaying Laravel 5.4 vue components? Explore potential solutions within the Laravel Passport framework

Currently, I am in the process of installing passport and using Taylor's tutorial video on laracast for assistance with integrating it into my vue components. However, after pasting these components I'm experiencing some issues as it's not ...

Looking to establish combinations in typescript? The answer lies in utilizing a discriminated union

I've been working with Typescript and I'm curious if it's possible to specify the valid combinations of input for a function. Below is a simplified version of the code: interface ActionType { type: string, payload: { count?: ...

Struggling to identify the error while utilizing Jasmine's throwError function

I am relatively new to using Jasmine and have been experimenting with the toThrowError() function. However, I can't seem to get my test to pass successfully. In one of my functions, I purposely throw an error: test.service.ts test(list:{}){ if ...

Issue with React.js code not being detected in TSX file (Visual Studio 2015 Update 1 RC)

Currently, I am utilizing Visual Studio 2015 with update 1 release candidate. Interestingly, I have managed to successfully incorporate React.js code and syntax highlighting within a .JSX file. However, when it comes to a .TSX file, nothing seems to be wor ...

Is it necessary to specify the inputs property when defining an Angular @Component?

While exploring the Angular Material Button code, I came across something interesting in the @Component section - a declared inputs property. The description indicates that this is a list of class property names to data-bind as component inputs. It seems ...

Ways to store data in the localStorage directly from a server

I'm facing an issue - how can I store data in localStorage that was received from the server? Should I use localStorage.setItem for this purpose? And how do I handle storing an array in localStorage? Or am I missing something here? import { HttpCli ...

What is the method for creating an array of strings in VueJS?

In my VueJS and Vuetify project, I am working on creating a modal that allows users to input strings into a text field. What I aim to achieve is adding the inputted string to an array when the user clicks on create button. For example, if I enter 'inp ...

What is the best approach to organize data from an observable based on a nested key?

I'm currently developing a new application and struggling with grouping data. The data is being pulled from an observable, and I need to group objects by their status and push them into an array. I attempted to use the groupBy() method, but unfortunat ...