generate a PDF file from an HTML table in AngularJS with the help of jsPDF

I have integrated FileSaver.js, jspdf.plugin.table.js, and jspdf.js files into my project. Below is the code snippet from my controller:

$scope.exportPdf = function(sampletable){
     alert('pppp');

   var tbldata = [], fontSize = 8, height = 0, doc;
   doc = new jsPDF('p', 'pt', 'a4', true);
   doc.setFont("times", "normal");
   doc.setFontSize(fontSize);
         tbldata = [];
   tbldata = doc.tableToJson('sampletable');
   height = doc.drawTable(tbldata, {

   });


  // doc.text(120, height + 20, 'Congrats!');
   doc.save("dwnld.pdf");
  }

However, I am facing issues when trying to include an image within my table. The current setup does not support tables with images. My table structure is as follows:

<style>
                            .tab{
                                margin-left:10%;
                                }

                                        .table1, .tr1 ,.td1{
                                                            border: 1px solid black;

                                                        }
                                                th, td {
                                                            padding: 5px;
                                                        }
                                    </style>
<table border="1" style="width:80%" class="table1 tab" ng-repeat="m in empname" id="sampletable">
 <tr class="tr1"> 
   <td class="td1">Name</td>
    <td class="td1">uu</td>     
    <td class="td1">hh</td>
   <td class="td1">uu</td>
    </tr>
    <tr class="tr1">
    <td class="td1">uuu</td>
    <td class="td1">hhh</td>        
    <td class="td1">iit</td>
    <td class="td1">iii</td>
                                                                </tr>
                                                                <tr class="tr1">
    <td class="td1">Nojjjjjj</td>
    <td class="td1">22</td>     
    <td class="td1">yyyyyy</td>
    <td class="td1">21</td>
    </tr>

 <tr class="tr1">
  <th height="50" colspan="4">yyyyyyyyyy</th>   
 </tr>
 <tr class="tr1">
    th colspan="4" class="td1">hhhhhhhh</th>
   </tr>

 <tr class="tr1"  >
   <td class="td1" colspan="2">hh</td>
<td class="td1" colspan="2">hh</td>
  </tr>
 <tr class="tr1">
  <td class="td1" colspan="2">hhhhh</td><td class="td1" colspan="2">888</td>
                                                         </tr>

  <tr class="tr1">
    <th height="100" colspan="4" >ggggggggggggggggggggg bbbbbbbbbbbb</th>   
                                                                </tr>


                                            </table> 

Although I'm able to generate a PDF file, it doesn't meet my requirements precisely. Any assistance in resolving this issue would be greatly appreciated.

Answer №1

If you're looking to export HTML tables in different formats like PDF, Excel, or DOC, consider using the Ngiriraj Html Table Export jQuery plugin with AngularJS custom directives. This will allow you to easily switch between formats suitable for logistics purposes.

(function(){
//export html table to pdf, excel or doc
var exportTable = function(){
var link = function($scope, elm, attr){
$scope.$on(‘export-pdf’, function(e, d){
      elm.tableExport({type:’pdf’, escape:’false’});
 });
$scope.$on(‘export-excel’, function(e, d){
       elm.tableExport({type:’excel’, escape:false});
 });
$scope.$on(‘export-doc’, function(e, d){
     elm.tableExport({type: ‘doc’, escape:false});
 });
}
return {
  restrict: ‘C’,
  link: link
   }
 }
angular
 .module(‘CustomDirectives’, [])
 .directive(‘exportTable’, exportTable);
})();

For the controller file:

$scope.exportAction = function(){ 
      switch($scope.export_action){ 
          case ‘pdf’: $scope.$broadcast(‘export-pdf’, {}); 
                      break; 
          case ‘excel’: $scope.$broadcast(‘export-excel’, {}); 
                      break; 
          case ‘doc’: $scope.$broadcast(‘export-doc’, {});
                      break; 
          default: console.log(‘no event caught’); 
       }
}

Include this HTML code in your view page:

<table class=’export-table’></table>

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

What is the process for implementing Bootstrap 5.3.3 css to restore button colors to their default shades and include glyphicons?

I've utilized Dropzone.js for a few years now and have an application that's been functioning smoothly. There are three buttons being used. <span class="btn btn-success fileinput-button"> <i class="glyphicon gl ...

"Maximize Interaction: Integrate interact.js with your Vue components

Previously, I had set up my project with two boards for dragging and dropping cards. However, I am now interested in experimenting with interact.js because it seems like a reliable library that is well-maintained. Since I am using vue for this project, I a ...

What is the best way to ensure that the scroll inside a container automatically starts at a specific link?

https://codepen.io/jimjamjom/pen/oBoEgz If you check out the codepen link above, you'll see that when a visitor lands on the page, the container defaults to "Section 3," requiring them to scroll up or down to view the other sections. Despite attempt ...

Tips for preventing repetition of code in tests for AngularJS using Jasmine

For a while now, my team has been dedicated to working with angularjs. We have noticed that our unit tests are starting to contain a lot of duplicate code. Is there a more angular-friendly approach to handling this issue? We are looking for a way to mainta ...

Remove the new line break at the top of the text and replace it with the remaining text

[text area control has a new line break that needs to be removed and replaced with the remaining string like image two][1] This image illustrates ...

Tips for extracting specific field titles from a RESTful API with the help of ExpressJS and Axios

Recently, I have been working on some code that allows me to retrieve data from an external API. Below is an example of the code: //endpoint to fetch data from an external API app.get("/externalapi", (req, res) => { let apiURL = &apos ...

Tips for transferring localstorage values from the view to the controller in order to utilize them as a PHP variable in a separate view

How can I pass the value from local storage as a PHP variable when using location.href in the controller after clicking a button? In the view: echo Html::button('Proceed', [ 'onclick' => " var dataVal = localStorage.g ...

Why does Math.max.apply not prioritize the first parameter?

function findSmallestNumber(numbers){ return Math.min.apply(Math, numbers); } This code sets the context to be the Math object. However, this is not required because the min() and max() methods will still function properly regardless of the specified co ...

Compilation error - TypeScript has encountered a poorly attached object

Encountering a puzzling React and TypeScript issue where a component loads momentarily, then abruptly crashes with the error: [internal] TypeScript error in [internal] (undefined,undefined): badly attached item found. TSINTERNAL_ERROR The problematic ...

Utilize dropdown selections to generate a custom function for calculating prices using JavaScript

Currently, I am facing a challenge in writing the calcTotal function as I am uncertain about how to distinguish between the selected pizza and the quantity of pizzas requested. My goal is to assign specific prices to each type of pizza (Cheese $6, Pepperon ...

Retrieve the AngularJS scope object by using an alternate scope object as the identifier

As I loop through an array of person objects using ng-repeat, imagine the array looks something like this: [{ "display_name": "John Smith", "status": "part-time", "bio": "I am a person. I do people stuff.", }, { "display_name": "Jane Doe", "stat ...

Retrieve the index of several callbacks created within a loop iteration

While working with an API function that requires a callback in a for loop, I encountered an issue where the callback needed to be index-specific. However, I couldn't alter the willCallBack function (as it's part of the API) and didn't want t ...

Can AJAX be utilized to update a single attribute of a model?

I have a model called JobApplicationForm with two parts - a short application and a long application. The first page posts certain attributes to the model, and once the last 3 pages are completed, another post updates the model to be fully filled out. publ ...

Is there a way to substitute the function variable using JavaScript?

Is there a method to dynamically replace the variable 'abc' with 'cde' in HTML using JavaScript? For example, if I have the following code: <table width="150" border="0" cellspacing="0" cellpadding="2" id="productBox"> <tr> ...

What is the process for retrieving the value of a text box using V-Model?

Link to the code snippet <td><input class="input" v-model="user.name" /></td> After accessing the provided link, I noticed a unique input textbox. Is there a way to extract specific text values like a,b,c from this te ...

Modifying routes within the beforeEach function causes issues when the callback incorrectly passes in erroneous routes to and from

I'm currently in the process of developing a mobile frontend using Vue. My goal is to have route transitions dynamically change to slide either left or right based on the current tab index. To accomplish this, I've set up a transition component ...

Navigating in React Router Dom v6

Can someone please provide guidance on the correct method for redirects in v6? In v5, I used the code below and it worked perfectly: <Route path="/login"> {user ? <Redirect to="/" /> : <LoginStandard />} </Route&g ...

Remove an item from an Ionic list

I am currently in the process of developing an Ionic to-do list application. I am facing an issue with the delete function where the delete button is not working as expected. When the button is clicked, nothing happens. HTML: <ion-view view-title="To ...

Which is the optimal choice: subscribing from within a subscription or incorporating rxjs concat with tap?

After storing data in the backend, I proceed to retrieve all reserved data for that specific item. It is crucial that the data retrieval happens only after the reservation process to ensure its inclusion. Presented with two possible solutions, I am cont ...

What is the best way to extract the URL value and insert it into a text box?

After submitting the form, the URL looks like this: from=Paris%2C+France&to=Rome%2C+Italy On the new page, I need the value of 'from' to be inserted into the following input field: <input id="from" class="form-control" type="text" name= ...