The jspdf tool tries to cram my extensive data into a single page, resulting in an overcrowded and barely visible PDF document

My PDF generated using Jspdf is being forced to fit in one page, making it difficult to see all the data because there is a huge amount of information present. To view the issue, please visit this link: https://jsfiddle.net/frost000/04qt7gsm/21/

var pdf = new jsPDF('p', 'pt', 'a4');
var btn = document.getElementById("btn");

btn.addEventListener('click', function() {
  pdf.addHTML(document.body, function() {
    pdf.save('test.pdf');
  });
});
.card-header {
  height: 8vh;
  background-color: #0062cc;
  color: white;
}

.card-header i {
  margin-left: 26rem;
}
...
[Rest of CSS code]
...
[Javascript and CDN scripts]

[Additional details regarding the issue]

To address the challenge of displaying a large volume of data on a PDF using JsPDF, I am seeking assistance. The current sample provided does not represent my actual dataset, which is significantly larger.

I am also curious why the pdf.addHTML method works in JavaScript but encounters issues in TypeScript despite proper installation via npm.

Answer №1

It is important to regularly check the page size when adding new content and use the addPage() function as needed:

doc = new jsPdf();
...
pageHeight= doc.internal.pageSize.height;

// Checking page height before adding new content
y = 500 // Position of new content
if (y >= pageHeight)
{
  doc.addPage();
  y = 0 // Reset position
}
doc.text(x, y, "value");

Answer №2

Tip: Instead of using jspdf, try utilizing pdfmake [https://www.npmjs.com/package/pdfmake]

(Why settle for a buggy tool when there's a superior one available with enhanced features and easier coding?

Admittedly, no library is flawless. However, some are more bug-ridden than others, especially when it comes to specific functions or uses. For instance: In my scenario of converting an HTML table to PDF in TypeScript, I experimented with jspdf-autotable but encountered issues)

Now, my task has become simpler. No longer do I need a screenshot tool like html2canvas to capture all table contents as images. Gone are the concerns about screenshot quality, resizing, etc. Moreover, I have tangible data in PDF format that can be copied, rather than just being a static image.

Let’s get started.

Get pdfmake:

(In my case, it was installed for Angular)

npm i pdfmake --save

TypeScript Code:

Import It:

import pdfMake from "../../../../node_modules/pdfmake/build/pdfmake";
import pdfFonts from "../../../../node_modules/pdfmake/build/vfs_fonts";
pdfMake.vfs = pdfFonts.pdfMake.vfs;

Develop Function:

Create a function for downloading the desired PDF file upon clicking a download button

  peopleExportToPdf() {
    let docDefinition = {
      content: [
        {
          table: {
            body: [
              [{ text: 'SL#', bold: true }, { text: 'Name', bold: true }, { text: 'Age', bold: true }],
              [{ text: 'Bold value', bold: true }, 'Val 2', 'Val 3'],
            ]
          }
        }]
    }

    docDefinition.content[0].table.body.pop(); //remove the unnecessary 2nd row
    let slno: number = 1;
    for (let p of this.people) {
      docDefinition.content[0].table.body.push([{ text: slno.toString(), bold: true }, p.name, p.age.toString()]);
      slno = slno +1;
    }
    pdfMake.createPdf(docDefinition).download('Report.pdf');
  }

Quick Tips:

  1. Align your table columns - SL#, name, age - according to your requirements.
  2. If dealing with non-string data, ensure conversion to string (I had to convert age to string to avoid errors).
  3. I added and removed an extra row due to complications. You might encounter similar challenges (If you have a better solution, please share!)

Acknowledgment:

I received guidance from the following sources:

  1. How to convert html table to pdf using pdfmake
  2. https://github.com/bpampuch/pdfmake/issues/1046

Answer №3

If you have a substantial amount of data in a column, consider using this code snippet to customize the width of your PDF based on the contents of your mat-table. It could potentially be beneficial for someone seeking assistance with this issue.

Begin by importing the 'autoTable' and 'jsPDF' libraries:

 downloadpdf() {
const doc = new jsPDF('l', 'pt', [3400, 3000]); // Adjust the PDF width by modifying these two values 
;
autoTable(doc, {
html: '#my-table', // Replace 'my-table' with your table's ID
columnStyles: {
//   0: { cellWidth: 100 },
//   1: { cellWidth: 200 },
//   2: { cellWidth: 200 },
}
});
doc.save('my_table.pdf')

}

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

Ways to launch numerous URLs in express.js

I am currently developing a service similar to a URL shortener. While a typical URL shortener redirects the user to one page, my service needs to open multiple URLs simultaneously. When a user clicks on a link from my website, I want it to open multiple l ...

Struggling to delete items from an array in react.js

I am attempting to remove an item from a nested childArray within another Array. This is my current approach: const childArrayHandler = (childData, sub, questionId, data, btnId) => { // Manage color change on click const isInList = selectedBtnL ...

Merging two arrays to create a JSON object

column_names: [ "School Year Ending", "Total Students", "American Indian/Alaskan Native: Total", "American Indian/Alaskan Native: Male", "American Indian/Alaskan Native: Female", "Asian/Pacific Islander: Total", "Asian/Pacific I ...

Using TypeScript's conditional types for assigning types in React

I'm tasked with creating a component that can belong to two different types. Let's call them Type A = { a: SomeCustomType } Type B = { b: SomeOtherDifferentType } Based on my understanding, I can define the type of this component as function C ...

Unable to display scrollbar when generating dynamic content with jquery ajax

I have a jQuery report where I am generating dynamic HTML content (nested divs, span, label) using JSON. The report utilizes jQuery, mCustomScrollbar, commons, and jQueryUI. When I have a <div>...//some static code </div>, everything works per ...

Angular2 module encounters failure when trying to inject InjectionToken using @Inject()

I've recently encountered an issue with InjectionToken that is declared within a module. import {InjectionToken, NgModule} from '@angular/core'; import {SampleComponent} from './sample.component'; export let SOME_TOKEN = new Inje ...

"jQuery Hide-and-Seek: A Fun Way to Manip

I am facing a challenge with a set of divs that I need to dynamically show and hide based on user interactions with questions. Essentially, the user will be presented with a question. Based on their answer, specific content with a title and description wi ...

Transferring Information Between Components

After logging into my login component, I want to pass data to my navbar component but unfortunately, my navbar content does not update. The navbar component is located in the app-module while the login component is in a separate module. I attempted to us ...

Is there an issue with my JavaScript append method?

Within the following method, an object named o gets appended to a list of objects called qs. The section that is commented out seems to be causing issues, while the uncommented section is functional. What could possibly be wrong with the commented part? on ...

What causes the Invariant Violation: Invariant Violation: Maximum update depth exceeded error to occur when using setState()?

Looking for some help with this component: // here are the necessary imports export default class TabViewExample extends Component { state = { index: 0, routes: [ { key: 'first', title: 'Drop-Off', selected: true }, ...

Designing a toggle button interface with Material UI

Looking to add a toggle button to my page. Here is an image of what I have in mind: https://i.sstatic.net/tiQAP.png Unable to find any material-ui component or API for this specific toggle button design. Considering building a custom toggle button with CS ...

The Express server is failing to deliver a response to the client when using the fetch method

Currently, I am utilizing express for the server side of my project. To send a post request from the client to the server, I am using fetch. The data that I am sending to the server is being successfully transmitted and displayed. However, I am encounteri ...

What is the best approach to extracting tightly-coupled code and converting it into an external library?

I have a question regarding paradigms that I would like to address, and if this is not the appropriate platform, please guide me to the right place. Your recommendations are most welcome :) Currently, I am tasked with extracting a significant piece of fun ...

What is the process for redirecting to a different URL when the button is clicked?"

I am trying to display Home.js at localhost/posts, but when the button is clicked, it displays information at the auth.js URL. How can I link the button so that if the login information is correct, it redirects to "localhost/posts" instead of rendering its ...

Request Pending | Observation of WebSockets in NestJS

I'm currently working on a NestJS application that interacts with the Binance Websocket API to retrieve some data. While I am able to see all the data in my console.log, I'm facing an issue where the request seems to be pending when using Postman ...

Unforeseen SyntaxError: Unexpected symbol detected

Encountering an issue while attempting to send raw data as parameters in express. Specifically, there is an error occurring at the 'fields' variable... function getWithQuery(req,res){ console.log(req.params); var query = {name: new RegEx ...

What is the best way to transform an Object into an Array?

[ { id: '5b3a223296fb381a29cf6fd9', number: 1, name: 'Tablet White EliteBook Revolve 810 G2', dprice: '0', image: '' } ] This message is generated by the angular application. Upon inspecting its type, it was identi ...

Is it necessary to retrieve the data that was posted from the back-end? Implementation using Angular and Node.js

I need some advice on how to handle worker data in my Angular, NodeJS, and MySQL app. In the FORM, users can add workers whose information is then sent to the backend for processing. The user can preview the posted information and delete workers if needed. ...

Creating a connection between properties and their values

I am looking to implement a property for data binding on my own terms. For instance, consider the following list of items: [{name='name1', invalid='error.name1'}] Along with another list of errors. errors : any= ['name1': & ...

Assign the values from the axios response to variables within the exported const

Currently, I am incorporating axios into my vue.js application to perform an HTTP POST request and retrieve some variables for a vue-echart. However, I have encountered a bit of a roadblock in determining the most effective approach. The snippet below is ...