Issue with jsPDF: PNG file is either incomplete or corrupted

I'm encountering an issue while attempting to pass Image data to the addImage function. I have tried downgrading the versions of jspdf and html2canvas, as well as experimenting with different ways to import the two libraries, but the problem still persists.

Here is the code snippet:

  export() {
    console.log('printing');
     const data = document.getElementById('reportContent');
     this.generatePDF(data);
   }
   
   generatePDF(htmlContent) {
     html2canvas(htmlContent).then(canvas => {
       const imgWidth = 290;
       const imgHeight = (canvas.height * imgWidth / canvas.width);
       const contentDataURL = canvas.toDataURL('image/png');
       const pdf = new jsPDF('l', 'mm', 'a4');
       const position = 10;
       pdf.addImage(contentDataURL, 'PNG', 0, position, imgWidth, imgHeight);
       pdf.save('report.pdf');
     });
   }

Here is the HTML:

<div #reportContent style="display: none;" id = "reportContent"> 
      <table>
        <tr>
          <td style="color: red;background-color: blue;">1111
          </td>
          <td>2222
          </td>
        </tr>
      </table>
    </div>

Answer №1

The solution to the issue I encountered was due to the usage of display:none; within the HTML code. I made modifications to this function as follows:

  export() {
    console.log('printing');
    const content = document.getElementById('reportContent');
    content.style.display = "block";
    this.generatePDF(content);
    content.style.display = "none";
  }

It's important to note that a hidden Canvas cannot be printed.

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

Is it possible to eliminate additional properties from an object using "as" in Typescript?

I am looking for a way to send an object through JSON that implements an interface, but also contains additional properties that I do not want to include. How can I filter out everything except the interface properties so that only a pure object is sent? ...

Guide on creating a Jasmine test for a printer utility

Currently, I am working on writing a Jasmine test for the print function shown below: printContent( contentName: string ) { this._console.Information( `${this.codeName}.printContent: ${contentName}`) let printContents = document.getElementById( c ...

Pair two values from the interface

I need to extract and combine two values from an Interface: export interface CurrenciesList { currency: string; country: string; } The initial mapping looks like this: this.optionValues["currency"] = value.map(i => ({ id: i.currency, name: i.curr ...

What is the best location for storing test utilities in Next.js applications?

My Next.js (12.x) React (18.x) project includes Jest (28.x) for testing. While my tests in files like __tests__/Product.test.tsx work smoothly, I encountered an issue when trying to reuse some utils across tests: __tests__/util/my-test-helper.ts export fu ...

Do interfaces in Typescript require nested properties to be mandatory?

My interface contains a nested object: export interface Person { PersonWrapper: { name: string; address: string email?: string; } } When attempting to create an object from this interface, it appears that name is not mandat ...

The function getServerSideProps does not return any value

I'm a beginner with Next.js and I'm currently using getServerSideProps to retrieve an array of objects. This array is fetched from a backend API by utilizing the page parameters as explained in the dynamic routes documentation: https://nextjs.org ...

Checking nested arrays recursively in Typescript

I'm facing difficulty in traversing through a nested array which may contain arrays of itself, representing a dynamic menu structure. Below is how the objects are structured: This is the Interface IMenuNode: Interface IMenuNode: export interface IM ...

Sign up for the completion event within the datetime picker feature in Ionic 2

How can I subscribe to the "done" event in Ionic2, where I want to trigger a function after selecting a date? <ion-icon class="moreicon" name="funnel"> <ion-datetime type="button" [(ngModel)]="myDate" (click)="getData()"></ion-datetime> ...

Customizing the appearance of the Material UI MuiClockPicker with unique style

I am wondering how I can override the styles for MuiClockPicker? I discovered that using createTheme to override the styles actually works for me, but I encountered an error from TypeScript: TS2322: Type '{ MuiOutlinedInput: { styleOverrides: { roo ...

Utilizing TypeScript to reference keys from one interface within another interface

I have two different interfaces with optional keys, Obj1 and Obj2, each having unique values: interface Obj1 { a?: string b?: string c?: number } interface Obj2 { a: boolean b: string c: number } In my scenario, Obj1 is used as an argument ...

Is there a clever method to transform the property names of child objects into an array of strings?

I have a similar object that looks like this: { "name":"sdfsd", "id":1, "groups":[ { "name":"name1", "id":1, "subGroups":[..] }, { "name":"name2", "id":21, ...

How can I inform Typescript that an interface will exclusively consist of defined members?

My interface looks like this interface Person { name?:string; age? :number; gender?:string } I need to reuse the same interface type, but with a modification indicating that all members will never be undefined. The updated version would look like this: ...

What is the best way to sort through an array depending on a specific sequence of elements provided

I am trying to create a custom pipe in Angular 5 that filters an array of events based on a given sequence. For instance, if my data is: ["submit", "click", "go_back", "click",...] I want to filter this data based on up to three inputs. If input ...

How to determine the frequency of a specific word in a sentence using Angular 5

I need help finding a solution to count how many times a word appears in sentences. Input: k = 2 keywords = ["anacell", "cetracular", "betacellular"] reviews = [ "Anacell provides the best services in the city", "betacellular has awesome services", ...

Need to import Vue component TWICE

My question is simple: why do I need to import the components twice in the code below for it to function properly? In my current restricted environment, I am unable to utilize Webpack, .vue Single File Components, or npm. Despite these limitations, I mana ...

How to toggle CSS class in Angular2/Typescript to mimic radio buttons behavior

Is there a way to create a radio button group using UL and LI elements in Angular2 and Typescript? The goal is to have all the anchors function like a radio button group where only one can be selected at a time. The selected anchor should remain "clicked" ...

Determine whether there are a minimum of two elements in the array that are larger than zero - JavaScript/Typescript

Looking for an efficient way to determine if there are at least two values greater than 0 in an array and return true? Otherwise, return false. Here's a hypothetical but incorrect attempt using the example: const x = [9, 1, 0]; const y = [0, 0, 0]; c ...

Tips for utilizing functions in an inline HTML translation pipe

My objective is to streamline the code by using the Angular translate pipe. Currently, I find myself using 8 curly brackets and repeating the word "translate" twice... there must be a more efficient approach. Here is my current code setup: <s ...

What are the steps to initiating a phone call using Nativescript?

When I click the button, I want to initiate a phone call dialing the number displayed on the label. Here is my custom button: <ActionBar> <NavigationButton (tap)="onBackTap()" android.systemIcon="ic_menu_back"></NavigationButton> ...

Discover an alternative to Events by harnessing the power of Observables to effectively listen for dismiss events in Angular Ionic

Currently, I am utilizing Ionic's inline modal feature that is activated by a boolean value. However, after the modal is closed, the boolean does not automatically reset to zero. The Ionic documentation suggests that developers should monitor the ionM ...