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

React is unable to identify the property that was passed to a styled-component in Material UI

Custom Styled Component Using Material-UI: import { Typography } from '@material-ui/core'; const CustomText = styled(Typography)<TextProps>` margin-bottom: 10px; color: ${({ textColor }) => textColor ?? textColor}; font-size: ${( ...

Incorporate fresh data into dropdown options upon selection using Vue3

Can anyone assist me with populating specific input fields on a form using Vue 3? Currently, when a user selects an option from my dropdown menu, all inputs are displayed instead of just the relevant ones. Below is the select dropdown code: <select v- ...

VueJS: using dynamic class names within the style attribute

Within my VueJS application, I have implemented Materializecss modals within single page components. Each modal requires a unique dynamic ID due to the application's requirements. The code snippet below showcases this: <template> <div :i ...

Converting the first page of the Vuepress README.doc from yaml format to markdown format document

I am struggling to locate instructions on customizing the homepage of Vuepress. While I appreciate its layout, the .yaml format is preventing me from adding links. Is there a way to include links? Or even better, can the page be converted to markdown whi ...

Identifying imports from a barrel file (index.ts) using code analysis

Can anyone help me understand how the Typescript compiler works? I am trying to write a script that will parse each typescript file, search for import declarations, and if an import declaration is using a barrel-file script, it should display a message. Af ...

The proxy request gets delayed unless I utilize the http-proxy-middleware

Here is the code for a provider: @Injectable() export class GameServerProxyService { private httpProxy: httpProxy; constructor(@Inject(GameServerDetailsService) private gameServiceDetailsService: GameServerDetailsService) { this.httpP ...

Utilizing Angular2 with Firebase for efficient denormalized data queries

I am currently working on crafting a query for a denormalized database. Drawing inspiration from the example showcased in Firebase's blog post, my objective is to: Retrieve the array of forms associated with the current user and return references to ...

I'm having trouble locating a declaration file for the module 'vue-prism-component'

Currently utilizing Vue 3 (Composition API), Vite, and Typescript but encountering a missing module issue with vue-prism-component. <script lang="ts" setup> import 'prismjs' import 'prismjs/themes/prism-tomorrow.css' imp ...

Output each element of an array in Vuejs2 with a line break between each

I am currently working with vuejs2 and have a select tag where a person is selected, with their address properties directly bound to the element. I need to display the address of the selected person. I attempted to use an array in order to print out the el ...

Trouble accessing nested components in Angular CLI beyond the first level of components

I'm diving into Angular CLI for the first time and trying to recreate a previous web project of mine. I've managed to nest and display components inside the root component successfully, but after that, I'm facing issues referencing any compo ...

A Guide to Handling Errors while Converting a Map to a Promise in Typescript

I am attempting to capture errors if any of the asynchronous code within my map function fails. It seems to enter the error block but does not log anything, as the error variable remains null. Is there an alternative method for handling errors within map ...

Tips for Disabling ML5 Posenet

Looking to halt Posenet after completing app task private sketch(p: any) { p.setup = () => { this.poseNet = ml5.poseNet(p.createCapture(p.VIDEO), { outputStride: 8 }); this.poseNet.on(&apos ...

Angular 2: Issue with disabled functionality not functioning correctly

In my TypeScript code, I have created a boolean variable called readOnlyMode. When this variable is set to true, all elements should be disabled. To achieve this, I am using [disabled]="readOnlyMode" in the HTML for elements that need to be disabled. Howev ...

The v-for loop specifically iterates over an array that relates to the current dynamic page number

I keep track of results per page number, illustrated below: <ul v-for="item in listingsData" :key="item.id"> <li>{{ item.name }}</li> </ul> <button @click="pushPrev">Push Prev Results</butt ...

In the world of Sass and Vue, it is crucial to remember that the "@use" rules should always come before any other rules

When attempting to include the "sass:colors" module in my colors.scss stylesheet, I am encountering a SassError stating that "@use rules must be written before any other rules", despite it being the first line in my file. It seems like the line is being pr ...

Intellisense with JavaScript methods is not supported in Vue files

While running Vue 2.6 in VSCode, I've noticed that my intellisense functions perfectly within js files. However, as soon as I switch to a vue file, all my intellisense capabilities disappear. I have the most up-to-date version of VSCode installed and ...

Utilizing VueJS to transfer information for constructing a pricing plan chart

This is my first experience with VueJS, so I would greatly appreciate any advice or alternative methods to solve the issue. You can view my progress so far here. I am working on creating a pricing plan table where users can explore four different payment ...

Using Angular's ngForm within an ng-template

Within my ng-template, there is a form displayed in a modal. .ts @ViewChild('newControlForm', {static: false}) public newControlForm: NgForm; .html <ng-template> <form role="form" #newControlForm="ngForm"> </form> </ng ...

Getting a JSON value and saving it to a variable in Angular 4

Here is the JSON structure: { "Semester": [ { "queueName": "Science", "totalCount": 300, "unassignedCount": 10, "subjectDetails": [ { "subjectName": "Chemistry", "sectionOne": 100, "secti ...

What is the best way to display HTML code using Vue syntax that is retrieved from an Axios GET request

I am currently working on a project that involves a Symfony 5 and Vue 3 application. In this setup, a Symfony controller creates a form and provides its HTML through a JSON response. The code snippet below shows how the form HTML is returned as a string: i ...