Adjusting the alignment of text within a table column with jspdf

I utilized jspdf to export an HTML table into a PDF. My goal is to format the table by aligning specific columns to the right and others to the left. Specifically, I want the first column to be aligned to the left and the last column to the right.

<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8">
<title></title>

{{ HTML::script("js/jspdf/js/jquery/jquery-1.7.1.min.js")}}
{{ HTML::script("js/jspdf/js/jquery/jquery-ui-1.8.17.custom.min.js")}}
{{ HTML::script("js/jspdf/js/libs/polyfill.js")}}
{{ HTML::script("js/jspdf/jspdf.js")}}
{{ HTML::script("js/jspdf/js/libs/deflate.js")}}
{{ HTML::script("js/jspdf/js/libs/adler32cs.js/adler32cs.js")}}
{{ HTML::script("js/jspdf/js/libs/FileSaver.js/FileSaver.js")}}
{{ HTML::script("js/jspdf/js/libs/Blob.js/Blob.js")}}
{{ HTML::script("js/jspdf/jspdf.plugin.standard_fonts_metrics.js")}}
{{ HTML::script("js/jspdf/jspdf.plugin.split_text_to_size.js")}}
{{ HTML::script("js/jspdf/jspdf.plugin.addimage.js")}}
{{ HTML::script("js/jspdf/jspdf.plugin.cell.js")}}
{{ HTML::script("js/jspdf/jspdf.plugin.from_html.js")}}
{{ HTML::script("js/jspdf/js/basic-test.js")}}

</head>
 <body>
     <div id="tblSaveAsPdf" class="table-details margin-top-small collapse" style="display: none; margin-top: -10em;">
                    <table class="table table-bordered table-striped table-hover bootstrap-datatable dataTable table-responsive">
                        <thead>
                            <tr role="row"> <%--class="headerRow"--%>
                                <th role="columnheader" class="col-lg-2"></th>
                                <th role="columnheader" class="col-lg-3"></th>
                                <th role="columnheader" class="col-lg-3"></th>
                                <th role="columnheader" class="col-lg-2"></th>
                                <th role="columnheader" class="col-lg-2"></th>
                            </tr>
                        </thead>
                         <tfoot>
                            <tr role="row">
                                <td style="text-align: center">
                                    <span>TOTAL</span>
                                </td>     
                                <td></td>  
                                <td></td>                                                        
                                <td  style="text-align: right">
                                    <span data-bind="text: pp_formattedDebitTotal"></span>
                                </td>
                                <td   style="text-align: right">
                                    <span data-bind="text: pp_formattedCreditTotal"></span>
                                </td>
                            </tr>
                      </tfoot>
                        <tbody  data-bind="foreach: pp_voidCheckGLSummarys">
                            <tr >
                                <td>
                                    <span data-bind="text: pp_account"></span>
                                </td>
                                <td >
                                    <span data-bind="text: pp_accountName"></span>
                                </td>
                                <td>
                                    <span data-bind="text: pp_entry"></span>
                                </td>
                                <td>
                                    <span data-bind="text: pp_amountDebit"></span>
                                </td>
                                <td>
                                    <span data-bind="text: pp_amountCredit"></span>
                                </td>
                            </tr>
                            </table>
                            </div>
                        </tbody>  
      <div>
     <button onclick="demoFromHTML()" class="button">SAvePDF</button></p></div></div>
     </div>

Below is the JavaScript code:

       <script>
      $(document).ready(function() {
       demoFromHTML();
      });

     function demoFromHTML() {
     var pdf = new jsPDF('p', 'pt', 'letter')
     , source = $('#tblSaveAsPdf')[0]
     ,  specialElementHandlers = {
     '#bypassme': function(element, renderer){
      return true;
       }
      };

     margins = {
      top: 80,
      bottom: 60,
      left: 40,
      width: 522
      };

  pdf.fromHTML(
     source // HTML string or DOM elem ref.
     , margins.left // x coord
     , margins.top // y coord
     , {
     'width': margins.width // max width of content on PDF
     , 'elementHandlers': specialElementHandlers
     },
    function (dispose) {   
        pdf.save('Test.pdf');
      },
    margins

     );
   }
   </script>

Answer №1

To resolve the issue, consider separating your table into distinct sections according to columns and arranging them using jspdf.plugin.htmltable.js. This method should assist you in achieving the desired outcome.

Answer №2

A more effective approach would involve making modifications to the jspdf.plugin.htmltable.js file in order to change the cell alignment dynamically. It is also important to include alignment settings within the cells of the HTML table.

switch (options.align || cell.align) {
     case '-webkit-center':
     case 'center':
       if (!(txt instanceof Array)) {
           txt = [txt];
       }
       for (i = 0; i < txt.length; i++) {
         var textSize = this.getStringUnitWidth(txt[i]) * this.internal.getFontSize();
         this.text(txt[i], cursor.x + cell_widths[x] - textSize - padding, cursor.y + this.internal.getLineHeight()*(i+1));
        }
   break;

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

Efficiently managing modules with requirejs and Backbone.Marionette

After organizing the file structure of my web app, utilizing RequireJs and Backbone.Marionette, it now looks like this: |- main.js |- app.js |- /subapp1 |- subapp1.js |- subapp1.router.js |- /subapp2 |- subapp2.js | ...

Is there a better method to accomplish this task in a more effective manner?

Is there a more efficient way to achieve this code with fewer lines of code? I'm looking for a solution that avoids repetition and makes it easier to manage, especially since I plan on creating multiple instances of this. Performance is a key consider ...

Chat Room with Stable Div Size

I am working on developing a chat feature, but I am facing an issue where the new message does not appear on the screen after a certain number of messages. I want the messages to overflow so that users can scroll down to view them, but only a few messages ...

`Incorporating width and vertical alignment in an image`

I am trying to figure out a way to make the image fill up 100% of the width, aligning it vertically with the text below. The code I'm working on is for email newsletters using foundation. Check out my Example Site Unfortunately, I can't seem to ...

When using multiple select tags with *ngFor in Angular, modifying the value of the first select tag will have an

<table id="DataTable" border="1" ALIGN="center"> <tr ALIGN="center"> <th>name</th> <th>address</th> <th>number</th> <th>type</th> </tr> <tr class="tcat" *ngFor ...

I am really struggling to comprehend this CSS calc() calculation - it's really giving me a headache

Struggling to grasp a CSS calculation that evenly spaces children in a flexed container with a defined gap between them? You're not alone! I'm looking to streamline this process by creating a SASS(SCSS) function for the calculation, but I can&ap ...

"Exploring the world of remote_form_tag in Rails with jrails

After transitioning to jQuery with jRails for my application, most of my previous RJS code is working perfectly. However, I am facing an issue with the :loading => callback when using the remote_form_tag. <% form_remote_tag :url => '/hostels ...

Utilizing TypeScript with Redux-Saga: Incorporating a generator function within an object

I have a file called static.js where I define all generator functions: For example: export function* getSettings() { try { const settings: Array<SettingElement> = yield callHttp(get, GET_SETTINGS); yield put(setSettings(settings) ...

Twitter Bootstrap enables the creation of a responsive layout for websites

I need help creating a responsive layout with Bootstrap. I'm not sure how to code the section below to ensure it functions properly with Bootstrap. Following Twitter's guidelines, I have already used div.row and div.span12. In this section, ther ...

The significance of using the Spread operator in React-Redux Reducers

Exploring the essence of the spread operator has been quite intriguing. Based on my interpretation of the documentation, it seems that the spread syntax essentially duplicates the existing object and then gets replaced by a new object when one is introduce ...

Is it possible to obtain the className of a leaflet divIcon within the <style scoped> portion of a vue component?

If you're looking for a Vue 2 sample project, check out this link When working on the declaration of divIcon in LeafletTest.vue, here is an example: const cloudIcon = L.divIcon({ html: thecloud, className: 'my-custom-icons& ...

What could be causing my for loop to not function properly within the ngOnInit lifecycle hook?

I am attempting to create a nested loop structure in order to access an array that is inside an object within an array of objects, and then store this data into a new array. My issue arises as the first loop executes successfully but the second one does no ...

Error encountered: _moment2.default.date is not a recognized function within the React application

I keep encountering an issue when attempting to utilize a date from Moment.js in the constructor, componentWillMount, or componentDidMount. The error message I receive is: Uncaught TypeError: _moment2.default.date is not a function It's worth noting ...

Removing all jQuery scripts from the WordPress admin panel: A step-by-step guide

Currently, I am developing a plugin and incorporating the WordPress color picker In the color_picker.js file: jQuery(document).ready(function($){ jQuery('.cp-field').wpColorPicker(); }); And in the index.php file: add_action('admin_i ...

Tips for enabling multiple v-list-group components to remain open simultaneously (bypassing the default Vue behavior)

Currently, I am facing an issue with Vue's default behavior where only one v-list-group can be open at a time. I am using Vuetify 2.6 and have attempted to use the multiple prop without success. Additionally, individually assigning the :value prop to ...

Mongoose allows for the dynamic loading of various schemas within a single collection

I am working with nodejs and currently have a registration page that includes a select tag for choosing between Client and Employee options. My goal is to create 1 model and 2 schemas: - User: containing common properties such as email, name, password... ...

Struggling to chart out a series of outcomes in react js with no success

I am currently working on creating a YouTube app using React and the YouTube v3 API. After fetching the data with Axios, I am facing an issue while trying to map the data. Can anyone provide some assistance? import React,{useState,useEffect ...

Image in Bootstrap is not resizing its height based on the height of the parent

I am facing an issue with resizing images inside buttons. Despite using the Bootstrap-4 class ("img-fluid"), the images are not adjusting properly when the button height or text size is altered. The image height remains unchanged. Here is a snippet of my H ...

What's the best way to organize Python objects for optimal JSON serialization?

Recently transitioning from JavaScript to Python, I am facing a challenge in understanding how to effectively communicate between client and server using JSON. Specifically, I am struggling to find the equivalent of an easily jsonifyable object attribute i ...

bootstrap 4.5 navbar spanning the entire width of the screen

I'm facing an issue with creating a basic navbar. It's not extending the full width of my page and not responding to color classes either. Here's the code for my header: <body> <div class="container-fluid"> <header> ...