Is there a way to incorporate CSS or tables when converting HTML to PDF using JavaScript?

While working on a project, I successfully converted an HTML file into a PDF. However, the output did not display the CSS design. Can anyone provide suggestions on how to include CSS design in the PDF file?

Below is the JavaScript function code:

 $(function(){
         var doc = new jsPDF();
    var specialElementHandlers = {
        '#editor': function (element, renderer) {
            return true;
        }
    };

    $('#cmd').click(function () {
        doc.fromHTML($('#StudentInfoListTable').html(), 15, 15, {
            'width': 170,
                'elementHandlers': specialElementHandlers
        });
        doc.save('sample-file.pdf');
    });

I utilized resources from this repository: https://github.com/MrRio/jsPDF

Description of my table layout:

The resulting PDF output:

Attempts were made to add a table

$('#cmd').click(function () {

        var table = tableToJson($('#StudentInfoListTable').get(0))
        var doc = new jsPDF('p', pt, 'a1', true);
        doc.cellInitialize();
        $.each(table, function (i, row){
            console.debug(row);
            $.each(row, function (j, cell){
                doc.cell(10, 50,120, 50, cell, i);  
            })
        })


        doc.save('sample-file.pdf');
    });

Function used for conversion:

function tableToJson(table) {
    var data = [];

    // Extract headers from the first row
    var headers = [];
    for (var i=0; i<table.rows[0].cells.length; i++) {
        headers[i] = table.rows[0].cells[i].innerHTML.toLowerCase().replace(/ /gi,'');
    }


    // Process cells in each row
    for (var i=0; i<table.rows.length; i++) {

        var tableRow = table.rows[i];
        var rowData = {};

        for (var j=0; j<tableRow.cells.length; j++) {

            rowData[ headers[j] ] = tableRow.cells[j].innerHTML;

        }

        data.push(rowData);
    }       

    return data;
}

This challenge has been quite frustrating!

Is there a way to prevent overlapping issues? How can we effectively incorporate CSS into the PDF document?

Answer №1

Finally, I was able to crack it after numerous attempts. A special shoutout to mihaidp for the assistance. Below is the code that helped me resolve the table row issue:

$('#cmd').click(function () {
        var table = tableToJson($('#StudentInfoListTable').get(0))
        var doc = new jsPDF('p', 'pt', 'a4', true);
        doc.cellInitialize();
        $.each(table, function (i, row){
                doc.setFontSize(10);

                $.each(row, function (j, cell){
                if(j=='name')
                {
                    doc.cell(10, 50,100, 30, cell, i);
                }
                else if(j=='email')
                {
                    doc.cell(10, 50,130, 30, cell, i);
                }
                else if(j=='track')
                {
                    doc.cell(10, 50,40, 30, cell, i);
                }
                else if(j=='s.s.croll')
                {
                    doc.cell(10, 50,51, 30, cell, i);
                }
                else if(j=='h.s.croll')
                {
                    doc.cell(10, 50,51, 30, cell, i);
                }
                else 
                {
                    doc.cell(10, 50,70, 30, cell, i);  
                }
            })
        }) 

After implementing this solution, the desired output was achieved.

Answer №2

Interesting! I believe this particular post will provide you with all the information you require, utilizing mPDF: how to include css file in mpdf

As for jsPDF, my knowledge is limited to the more complicated approach: (Refer to Method Summary).

I trust this proves helpful for your needs!

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 there a way to automatically open an expand/collapse section when linking to it?

I am attempting to automatically open the bootstrap expand/collapse details when linking to them from another page. For instance, I want to link to a page similar to , which includes multiple expand/collapse sections. My goal is to link to a specific sect ...

Using Ajax with Angular services

Recently, I decided to explore Angular JS and Async calls as an alternative to $JQuery. However, I encountered a peculiar issue while making ajax calls. To adhere to 'best practices', I shifted my ajax requests to a service and then initiated th ...

What is the process for retrieving the value of the 2nd td by clicking on the checkbox in the 1st td with JavaScript

When I click on "in", I am looking to retrieve the value of "out". This can be easily understood by referring to the image below: The timesheet displayed is generated using an array. All the data is stored in the array and needs to be presented in a table ...

Traverse Through Nested JSON Data and Display it in an HTML Table using Vue

Struggling to find a way to loop through my data, I have JSON data presented like this: [ { "STATUS":"CUTTING INHOUSE", "STID":"1", "CATS":[ { "CAT":"ORIGINALS ", "ARTS":[ { "ARTNO":"GY8252", ...

Could you assist me in setting up a loop for this Slideshow that times out and then resets back to the beginning?

Currently, I am in the process of developing a slideshow using jQuery. My main struggle lies in creating a loop that will timeout the slideshow for a specific duration, say 10 minutes, before it reappears and resumes indefinitely. Unfortunately, my attempt ...

Update the text within a table in real time by simply checking a box

I've got some data in JSON format that I've converted into an HTML table. Now, my goal is to update the text from False to True if a checkbox is checked. How can I achieve this? Below is the code used to create the HTML table: $.each(result, fu ...

How to utilize local functions within a ko.computed expression

Why isn't this line of code working? I'm using durandal/knockout and my structure is like this define(function () { var vm = function() { compute: ko.computed(function() { return _compute(1); // encountering errors }); ...

Is it possible to globally delay the execution of WebElement.sendKeys() in Protractor's onPrepare function?

While running protractor on a sluggish machine, I am in need of slowing down each key press and action performed. The action part has been successfully implemented, but how can I achieve the same for key presses? I have come up with a local solution which ...

Tips for utilizing rowspan and colspan in BootstrapTable

I am creating a table using bootrapTable and would like to know how I can use rowspan or colspan to achieve a table layout similar to the one shown in this image: Click here for image description $table.bootstrapTable({ columns: [{ ...

Error: The function coolArr.printArray is not defined in the npm package being imported

My custom package contains an index.js file with the following code: module.exports = class CoolArray extends Array { printArray() { console.log(this); } } After transpiling the code using es2015 syntax with Babel, I connected the package to my te ...

When the submit button is clicked on a React form, it not only submits the current form

I am working on a React application with multiple forms, where each form is rendered based on the current page index. I would like the "Next" button that retrieves the next component to also act as a submit button. The issue I am facing is that while the n ...

In JavaScript, JSON data is parsed using a comma separator

Here is the format of my data: [{"QualID":1,"Qualification":"Van Driver"},{"QualID":3,"Qualification":"Safety Cert"},{"QualID":4,"Qualification":"Welder"}] I am look ...

Incorporate Error Text Spacing in Input Group Design

I'm currently working on developing a method to incorporate space for error messages within my form input group component. The main objective is to prevent any displacement of elements on my forms when displaying error messages. In this scenario, it ...

div that adjusts its max-width to always perfectly match the width of its contents

Check out this jsfiddle for more information: http://jsfiddle.net/tN6QE/2/ The CSS code we are using is as follows: div { display: inline-block; border: solid 1px black; padding: 10px; max-width: 200px; } We are dealing with two scenarios here. ...

Incorporating dynamic numerical values into image names within a Vue JS application

I have linked an image with the following code <img title="head" :src="availableParts.heads[selectNextHeadIndex].src"/> This image is called from a JSON file: { id: 1, description: 'A robot head with an ...

Integrate new functionality into the plugin's JavaScript code without directly editing the JS file

I need to incorporate a new function called 'setInputDataId' at the same level as the existing function '_select' in the plugin js file without directly modifying the file itself. I am seeking guidance on how to add this new function. ...

CSS not displaying hover color in Internet Explorer 8

Can you take a look at ? The links should turn red when hovered over. It seems to work perfectly in FF, Opera, and Chrome, but not in IE8. I'm stumped as to why this is happening. Changing a:link to text-decoration:underline makes the underline red on ...

Is there a way to reverse a string in Javascript without using any built-in functions?

I am looking for a way to reverse a string without using built-in functions like split, reverse, and join. I came across this code snippet on Stack Overflow (), but I'm having trouble understanding what the code does on the fourth line. I need more cl ...

What will occur if I invoke response.end in Node.js while asynchronous I/O operations and callbacks are still executing?

When working with Node.js, what happens if you call "response.end()" while I/O calls and/or callbacks are still being executed? Take a look at the code snippet below: var app = http.createServer(function(request, response) { response.writeHead(200, { ...

What could be the reason why a specific item is not being retrieved by its ID?

Whenever I navigate to the route: '/gallery', all the items from the file './posts.json' are fetched and displayed on the screen. However, upon navigating to the route: '/gallery/:id', my intention is to retrieve a single item ...