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

The Add/Remove button functionality is not functioning as expected for duplicated form fields when using jQuery

I am experiencing an issue with the functionality of the "Add another" and "Remove row" buttons in my form. I implemented code from a specific Stack Overflow answer (jquery clone form fields and increment id) to create a cloneable section, but only the ori ...

Can a single file in NextJS 13 contain both client and server components?

I have a component in one of my page.tsx files in my NextJS 13 app that can be almost fully rendered on the server. The only client interactivity required is a button that calls useRouter.pop() when clicked. It seems like I have to create a new file with ...

What is the best way to sequentially invoke an asynchronous function within an Observable method?

Presently, I have the following method: public classMethod( payload: Payload, ): Observable<Result> { const { targetProp } = payload; let target; return this.secondClass.secondClassMethod({ targetProp }).pipe( delayWhen(() ...

Techniques to dynamically insert database entries into my table using ajax

After acquiring the necessary information, I find myself faced with an empty table named categorytable. In order for the code below to function properly, I need to populate records in categoryList. What should I include in categoryList to retrieve data fro ...

Tips for launching different web browsers via hyperlinks?

My app has a link that I want mobile users from apps like LinkedIn to open in a browser such as Safari. I attempted this: <a href="safari-https://meed.audiencevideo.com">May open on Safari</a>' However, when I click the link, it opens i ...

The center div is not functioning properly

After scouring numerous sources on the web, I have found various tips for centering a div. However, no matter what I try, there seems to be a persistent white space to the left of my div that I just can't seem to resolve. If you're curious, her ...

When trying to access the DOM from another module in nwjs, it appears to be empty

When working with modules in my nwjs application that utilize document, it appears that they are unable to access the DOM of the main page correctly. Below is a simple test demonstrating this issue. The following files are involved: package.json ... "ma ...

The navigation in Framework 7 is causing issues with the on-click functionality

Utilizing the framework's built-in formToJSON() function, I have been able to retrieve form values. By utilizing a click event, I am able to log the values. $$("#query-submit").on("click", function () { var queryForm = app.formToJSON("#query-form ...

Transferring the AJAX response into a JavaScript variable

New to AJAX and JS here. I am implementing an AJAX code that fetches data from a php service. I am trying to figure out how to store the returned data in a JavaScript variable, which I can then display on the UI. Below is my AJAX code snippet: <script ...

The ajax request does not support this method (the keydown event is only active during debugging)

I've encountered a strange issue with an AJAX request. The server-side code in app.py: #### app.py from flask import Flask, request, render_template app = Flask(__name__) app.debug = True @app.route("/myajax", methods=['GET', ...

Executing functions in TypeScript

I am facing an issue while trying to call a function through the click event in my template. The error message I receive is "get is not a function". Can someone help me identify where the problem lies? This is my template: <button class="btn btn-prima ...

Is searching for duplicate entries in an array using a specific key?

Below is an array structure: [ { "Date": "2020-07", "data": [ { "id": "35ebd073-600c-4be4-a750-41c4be5ed24a", "Date": "2020-07-03T00:00:00.000Z", ...

Setting up global color variables for React with Material UI theming is essential for ensuring consistent and

Is there a way to customize the default material-ui theme using global CSS? Additionally, how can we incorporate HEX values for colors when setting primary and secondary colors in the theme? In my App.js root file, I have defined a custom theme and want t ...

What's the best approach: Backbone-Relational discovery or retrieval?

Although the model caching feature in Backbone-Relational is effective, loading a simple model securely requires considerable code. For example: // Attempt to locate a model in the cache this.model = MyModel.find({id:id}); if(this.model){ // Model re ...

input access is granted through the post method using an integer as the name parameter

Suppose there is a dynamic form with multiple fields generated with integer names based on the iteration that creates them. The goal is to retrieve their values using either post or get method (though focusing on post here). Below is the code for generati ...

Having trouble getting the same styles to show up on .class::before and .class::after elements, even though I've applied them. The changes aren't reflecting on the live server

Currently, I am working on a project that involves an ordered list (ol), and I am trying to add pseudo elements (::before,::after) to enhance its appearance. Strangely, when I write ::before and ::after separately, the styles are applied and visible on the ...

Running a series of functions consecutively with JQUERY

Currently, I am facing an issue with using an ajax method .load to replace the content of a div. The library I am working with does not allow me to replace the content of a div as some functions continue to run in the background. To overcome this challeng ...

Removing a SubDocument from an Array in Mongoose

For my project, I am utilizing mongoose to create a database. The schema for my Class looks like this: const mongoose = require('mongoose') const classSchema = mongoose.Schema({ _id: mongoose.Schema.Types.ObjectId, consultant: { type: mo ...

Using jQuery to incorporate a variable into JSON schema markup

For my current project, I am attempting to extract the meta description and incorporate it into JSON schema markup. However, I am facing difficulty in passing the variable properly into the JSON structure. My initial approach was as follows: <script&g ...

Please ensure you have selected at least one item before submitting the form

I have been working on validating a form using a combination of bootstrap and angularjs. The form includes two groups of checkboxes that need to be validated. It is required for the user to select at least one checkbox from each group in order for the Subm ...