How to make table of PDF 100% width for datatables - javascript

I have a table that I'm saving as a pdfHtml5 in datatable. I'm trying to make the table full width but I have been unsuccessful. How can I make my table 100% width using styles for my pdfHtml5?
dom: 'Bfrtip',
buttons: [
{
extend: 'collection',
text: '<div class="image"><img src="/Asset/Image/Capture.jpg" alt="" /></div>',
autoClose: true,
buttons: [{
extend: 'pdfHtml5', text: 'Download PDF Document', className: 'pdfdoc', title: podTitle, message: pod.data.pod_description_text + "\n" + "\n" + printDate, customize: function (doc) {
doc.defaultStyle.alignment = 'left';
doc.styles.tableHeader.alignment = 'left';
doc.styles.message = {
alignment: 'center'
}
doc.styles.table = {
alignment: 'center',
width: '100%',
}
/*doc.content[1].table.widths = Array(doc.content[1].table.body[0].length + 1).join('*').split('');*/
doc.pageMargins = [ 80, 20, 80, 20 ];
}
}, { extend: 'excel', text: 'Download Excel Document', className: 'exceldoc' },
]
}
]
});

By further extending pdfHtml5, you can instruct the pdfmake library, used by the Buttons extension, to use 100% width. The DataTables forum has a post with the required code:
var tbl = $('.dTable');
var settings={};
settings.buttons = [
{
extend:'pdfHtml5',
text:'Export PDF',
orientation:'landscape',
customize : function(doc){
var colCount = new Array();
$(tbl).find('tbody tr:first-child td').each(function(){
if($(this).attr('colspan')){
for(var i=1;i<=$(this).attr('colspan');$i++){
colCount.push('*');
}
}else{ colCount.push('*'); }
});
doc.content[1].table.widths = colCount;
}
}
];
$('.dTable').dataTable(settings);
Note that if you just copy the customize portion of the code above, you must replace tbl by "#myTable" or something similar.
See also the related GitHub ticket, including another implementation (which may or may not be out-of-date).

I use this and works for me. Good luck.
{
extend: 'pdfHtml5',
charset: 'utf-8',
title:tableOptions.title.toUpperCase(),
orientation: 'landscape',
text: '<i class="fas fa-file-pdf"></i> PDF',
exportOptions: {
columns: [1,2,3,4]
},
customize: function(doc) {
doc.content.splice( 0, 0, {
margin: [ 7, 0, 0, -45 ],
width: 85,
height: 55,
alignment: 'right',
image: 'base64...'
});
let downloadDate=`${moment(new Date(), 'YYYY-MM-DD HH:mm:ss').format('DD-MM-YYYY')}`;
let downloadTime=`${moment(new Date(), 'YYYY-MM-DD HH:mm:ss').format('YYYY-MM-DD HH:mm:ss')}`.slice(11,16);
doc.content.splice( 2, 0, {
alignment: 'left',
fontSize:12,
margin: [ 0, 0, -10, 20 ],
color:"#003d66",
text:`${downloadDate} / ${downloadTime} Hrs`
});
doc.defaultStyle.alignment = 'center';
doc.defaultStyle.color = '#666';
doc.styles.title.color="#00c4cc";
doc.styles.title.alignment="left";
doc.styles.title.fontSize=14;
if(doc.content[3].table.body[0]){
let columns=doc.content[3].table.body[0].length;
let widths=[];
for (let i = 0; i < columns; i++) {
widths.push(`${99/columns}%`)
}
doc.content[3].table.widths = widths;
}
doc.styles.tableHeader.fontSize=12;
doc.styles.tableHeader.fillColor="#003d66";
doc.styles.tableBodyOdd.margin =[5, 5, 5, 5];
doc.styles.tableBodyEven.margin = [5, 5, 5, 5];
}
},

Related

pdfMake pageBreakBefore feature is not working

I am trying to concatenate multiple pdf files to a content variable. However I want each pdf content to be on a new page, but pdfmake.js just concatenate each content right after the other. I have added 'pageBreakBefore' function right after my content but it still doesn't work. Is there a way to make each content to be on separate page. (I am using jpdmake.js 1.60). Thanks!
Below is my code:
let content = [];
content = this.getContent(checkedOrders, selectedLabOrders);
this.docDefinition = {
info: {
title: 'Title',
subject: 'labOrder-'
},
pageSize: 'LETTER',
pageOrientation: 'landscape',
pageMargins: [40, 30, 40, 30],
content: content,
pageBreakBefore: function(currentNode, followingNodesOnPage, nodesOnNextPage, previousNodesOnPage) {
return currentNode.headlineLevel === 1 && followingNodesOnPage.length === 0;
},
unbreakable: true,
styles: {
titleHeader: {
fontSize: 16,
bold: true,
margin: [0, 10, 0, 0],
},
tableHeader: {
bold: true,
fontSize: 13,
color: 'black'
}
},
defaultStyle: {
fontSize: 9,
lineHeight: .9
}
};

Change Column titles in dataTables when exporting to excel

I am trying to rename a column in dataTables when exporting to excel.
The reason is cause I have added a select filter option on one of the header titles.
When I try to export it, the whole name shows like this:
CategoryBeautyChristmasDecorFood - BakeryFood - DeliFood - DrinksGardenGift Cards and StationaryGifts - Children - ClothingGifts - Children - ToysGifts - LadiesGifts - MenJeweleryPets
Instead of just saying: Category
Please help!
My code:
$(document).ready(function () {
$('#datatables').DataTable({
"pagingType": "full_numbers",
"lengthMenu": [
[10, 25, 50, -1],
[10, 25, 50, "All"]
],
responsive: true,
language: {
search: "_INPUT_",
searchPlaceholder: "Search records",
},
'columns': [ // see https://datatables.net/reference/option/columns.searchable
null,
null,
null,
null,
null,
{'searchable': false},
{'searchable': false}
],
dom: 'Bfrtip',
buttons: [
{
extend: 'excelHtml5',
orientation: 'landscape',
exportOptions: {
columns: [0, 1, 2, 3],
customize: function ( xlsx ) {
var sheet = xlsx.xl.worksheets['sheet1.xml'];
$('c[r=A2] t', sheet).text( 'Custom text' );
}
/**format: {
//this isn't working....
header: function (data, columnIdx) {
return columnIdx + ': ' + data;
}
}*/
}
}
/**,{
extend: 'pdfHtml5',
orientation: 'landscape',
exportOptions: {
columns: [ 0, 1, 2, 3 ],
header: false
}
}*/
],
//add drop downs to columns
initComplete: function () {
this.api().columns([3]).every(function () {
var column = this;
var select = $('<select><option value="">Category</option></select>')
.appendTo($(column.header()).empty())
.on('change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
column
.search(val ? '^' + val + '$' : '', true, false)
.draw();
});
column.data().unique().sort().each(function (d, j) {
select.append('<option value="' + d + '">' + d + '</option>')
});
});
}
});
var table = $('#datatables').DataTable();
});
I've looked everywhere and cant seem to find a solution.
I managed to figure out the customize placement was wrong.
$(document).ready(function () {
$('#datatables').DataTable({
"pagingType": "full_numbers",
"lengthMenu": [
[10, 25, 50, -1],
[10, 25, 50, "All"]
],
responsive: true,
language: {
search: "_INPUT_",
searchPlaceholder: "Search records",
},
'columns': [ // see https://datatables.net/reference /option/columns.searchable
null,
null,
null,
null,
null,
{'searchable': false},
{'searchable': false}
],
dom: 'lBfrtip',
buttons: [
{
extend: 'excelHtml5',
text: 'Excel Export',
customize: function (xlsx) {
var sheet = xlsx.xl.worksheets['sheet1.xml'];
$('c[r=D2] t', sheet).text('Category');
},
exportOptions: {
columns: [0, 1, 2, 3],
modifier: {
page: 'current',
}
}
}
],
initComplete: function () {
this.api().columns([3]).every(function () {
var column = this;
var select = $('<select><option value="">Category</option></select>')
.appendTo($(column.header()).empty())
.on('change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
column
.search(val ? '^' + val + '$' : '', true, false)
.draw();
});
column.data().unique().sort().each(function (d, j) {
select.append('<option value="' + d + '">' + d + '</option>')
});
});
}
});
var table = $('#datatables').DataTable();
});
I had the exact same issue. I managed to get it working using the the header formatting function inside the exportOptions object instead of the customize function. Assuming that the header that needs to be modified is the first one i.e the header index is 0, you could script your header function like this to make it work.
...
exportOptions: {
format: {
header: function ( data, columnIdx ) {
return columnIdx === 0 ? "Category" : data;
}
}
},
...
Reference: https://datatables.net/extensions/buttons/examples/html5/outputFormat-function

Datatables ordering showing older dates before new

I am using datatables v1.10 to display my data and for some reason, it is displaying older dates before new dates in the grid. I am using the correct syntax (I think) to order the data but it is not displaying in the correct order. I have tried both asc and desc and although it is changing the date order, i am confused as to why a newer date is inserted after an older date.
Do I need to add ORDER BY to my sql or does dt ignore that?
I have done screenshot to show problem and would be grateful if someone could point out my error. Many thanks
js
$(function() {
$('#nirqst').DataTable({
"order": [[
9, "desc"
]],
"columnDefs": [
{
"orderable": false,
"targets": [ 10 ]
},
{
className: "hide_id",
"targets": [ 0 ]
}
],
dom: 'lBfrtip',
buttons: [{
extend: 'print',
exportOptions: {
columns: [1, 2, 3, 4, 5, 6, 7, 8, 9]
},
title: 'New Intake Report',
messageTop: 'This report was prepared for ' + usrname + ' on ' + rptDate,
//text: 'Print current page',
autoPrint: true,
customize: function(win) {
// $(win.document.body).find('table').css({'background': 'red !important', 'font-size': '24px' });
$(win.document.body).find('thead').css({
'background': '#000',
'font-size': '14px',
'max-height': '30px'
});
$(win.document.body).find('tr:nth-child(odd) td').each(function(index) {
$(this).css({
'background-color': '#f7f7f7',
color: 'black',
padding: '12px 10px',
'margin-left': '10px !important'
});
});
$(win.document.body).find('tr:nth-child(even) td').each(function(index) {
$(this).css({
'background-color': '#fff',
color: 'black',
padding: '12px 10px',
'margin-left': '10px !important'
});
});
$(win.document.body).find('h1').css({
'text-align': 'left',
color: 'black',
'margin-left': '36px',
'margin-bottom': '7px',
'font-size': '28px'
});
}
}, 'copy', 'pdf', 'excel']
});
$("#nirqst_wrapper > .dt-buttons").appendTo("#buttons");
// setInterval(function() {
//table.ajax.reload();
//}, 3000 );
});
If you pull out data from sql the datas that are recorded first will be the first one to be shown so you should put a order by in the date column.
select * from [table_name] orderby [date] ASC

Add buttons in grid column. ExtJs

I want to add buttons in one of columns in the grid. I try this code
listeners: {
render: {
fn: function(kad_tab){
var view = kad_tab.getView();
for (var i = 0; i < store.getCount(); i++) {
var cell = Ext.fly(view.getCell(i, 2));
new Ext.Button({
handler: function(){
alert('Suppression')
},
renderTo: cell.child(".btn"),
text: 'Supprimer'
});
}
},
// delay: 200
}
}
{header: "", width: 70, dataIndex: '', renderer: function(){ return '<div class="btn" style="height: 11px; width: 60px"></div>';}}
But firebug says that he see error here Ext.fly(this.getRow(c)) is null.
if i use delay: 200. There is no errors in firebug but dont see a buttons in column.
What im doing wrong?
I found a simple way...
{
xtype: 'actioncolumn',
width: 50,
items: [{
icon : url_servlet+'externals/gxp/src/theme/img/pencil.png',
tooltip: 'Button click',
handler: function(grid, rowIndex, colIndex) {
alert("DAMACIA!!!!!");
}
}]
}

Add margins between items in the Ext.Panel

I have a Panel with two buttons that is used inside another panel. Right now it renders the buttons correctly but I'd like to add a margin between them. How to configure layout properly to get this ?
return Ext.create('Ext.panel.Panel', {
width: 220,
height: 35,
border: false,
collapsible: false,
renderTo: renderTo,
items : [
{
xtype: 'button',
scale: 'medium',
text: this.exportButtonText,
handler: function() {
var form = this.form.getForm();
if (form.isValid()) {
var values = form.getValues();
form.reset();
this.plugin.printSettings = values;
this.progressBar.show();
this.plugin.doPrint();
}
},
scope: this
},
{
xtype: 'button',
scale: 'medium',
text: this.cancelButtonText,
handler: function() {
me.close();
},
scope: this
}
]
});
Or add this to left button definition:
{
margin: '0 5px 0 0'
}
Add this in between them:
{
xtype: 'tbspacer',
flex: 1
}

Categories