Arabic sentence for words are reversed on datatables pdfhtml5 "pdfmake" - javascript

I have changed the default font to a font that supports arabic
The words supposed to be shown this way:
تقارير حركة الرسائل
But they are shown as
الرسائل حركة تقارير
function processDoc(doc) {
// https://pdfmake.github.io/docs/fonts/custom-fonts-client-side/
pdfMake.fonts = {
Roboto: {
normal: 'Roboto-Regular.ttf',
bold: 'Roboto-Medium.ttf',
italics: 'Roboto-Italic.ttf',
bolditalics: 'Roboto-MediumItalic.ttf'
},
scheherazade: {
normal: 'Scheherazade-Regular.ttf',
bold: 'Scheherazade-Regular.ttf',
italics: 'Scheherazade-Regular.ttf',
bolditalics: 'Scheherazade-Regular.ttf'
}
};
// modify the PDF to use a different default font:
doc.defaultStyle.font = "scheherazade";
}
$(function () {
var table = $('.data-table').DataTable({
processing: true,
serverSide: true,
ajax: {
url: "{{ route('messaage_movements.index') }}",
"method": "GET",
data: function (d) {
d.search = $('input[type="search"]').val()
}
},
dom: 'Bfrtip',
buttons: [
// {
// extend: 'pdfHtml5',
// text: 'PDF',
// } ,
'copyHtml5',
'excelHtml5',
'csvHtml5',
'print',
{
extend: 'pdfHtml5',
// download: 'open',
title: '{{__('messages.messaage_movements')}}',
customize: function ( doc ) {
processDoc(doc);
doc.content.splice( 1, 0, {
margin: [ 0, 0, 0, 12 ],
alignment: 'right',
} );
},
}
],
columns: [
{data: 'id', name: 'id'},
{data: 'message', name: 'message'},
{data: 'user_id', name: 'user_id'},
{data: 'number_massages', name: 'number_massages'},
{data: 'status', name: 'status'},
{data: 'reason', name: 'reason'},
{data: 'date_sent', name: 'date_sent'},
{
data: 'action',
name: 'action',
orderable: true,
`enter code here` searchable: true
},
]
});
});
I have followed a code like that but turned it into arabic
I don't know where to put the direction="rtl" in the code cause It's not a visible html tag
enter link description here
-----edit
The changes I've made above solved the problem of the title and the rows but not the thead.
customize: function ( doc ) {
processDoc(doc);
doc.content[0]['text'] = doc.content[0]['text'].split(' ').reverse().join(' ');
},
}
],
columns: [
{data: 'id', name: 'id'},
{data: 'message', name: 'message',targets: '_all',render: function(data, type, row) {
if (type === 'myExport') {
return data.split(' ').reverse().join(' ');
}
console.log(data);
return data;
}},

This library doesn't support rtl very well.. but you could fix this issues in table body using "render" function in columns option to reverse the content..
the problem is with your table head, because you can't customize table header content..
but I figured out a trick to solve this issue..
the idea is to create two table headers.. one reversed and hidden from the html page.. while the other is not reversed and shown in html, the library will only detect the reversed one and display it in the pdf file
to apply this just add this code to your js file..
let thead = document.getElementsByTagName('thead')[0].children[0]
const reversedHead = thead.cloneNode(true)
thead.parentNode.appendChild(reversedHead)
let headCells = reversedHead.children
Object.keys(headCells).forEach(i=>{
headCells[i].textContent = headCells[i].textContent.split(' ').reverse().join(' ')
})
reversedHead.setAttribute('hidden',"")

Related

How to check size file CSV export by jQuery Datatables?

I'm doing the CSV export function with Datatables, but now I want to check if the file size is greater than 1MB, I won't export the file.
But I don't know how to do it, hope someone will know or have done a check on CSV file size Datatables.
This is my current code:
var otable = $table.DataTable({
"scrollX": true,
"ordering": false,
language: lg_opt,
data: data_json,
columns: [
{ title: "No", data: "No" },
{ title: "Name", data: "Name" },
{ title: "Data", data: "Data" },
],
dom: 'Bfrtip',
buttons: [
{
filename: 'Report_'+d+'_'+i,
extend: 'csv',
title: 'Report,
bom: true,
customize: function ( csv ) {
var split_csv = csv.split("\n");
split_csv.splice(0, 1);
csv = split_csv.join("\n");
return csv;
}
}
],
"bDestroy": true,
});
Thanks in advance!

Datatables - Export values inside and outside the field input and value of the select field

let's see who can help me solve this problem.
I have several tables with the JS datatables plugin (https://datatables.net/)
My problem is in exporting the data in PDF and Excel.
I can not export to PDF or Excel the values that are inside the input or select fields (only the selected value)
I have several tables where there are columns that are inputs, another column selects and another column simple text. I would like to know how I can do to export all these values to Excel or PDF, if you can with this plugin. So far I have not been able to get it.
Here a extract of my code to build the datatable:
var tabla_table = $('#table').DataTable({
dom: 'Blfrtip',
buttons: [{
extend: 'collection',
text: "<i class='fa fa-cog'></i>",
buttons: [
{
extend: 'pdfHtml5',
orientation: 'landscape',
customize: function ( doc ) {
doc.defaultStyle.fontSize = 10;
},
exportOptions: {
columns: ':visible',
columns: ':not(.no-print)',
/* format: {
body: function ( data, row, column, node, sValue, nTr, type ) {
//
//check if type is input using jquery
// console.log('data val: ' + $(data).val() );
console.log('data: ' + data );
console.log('row: ' + row );
console.log('nTr: ' + nTr );
console.log('node: ' + node );
console.log('type: ' + type );
/*if( $(data).is("input") ){
return data;
}else{
return $(data).val();
}
}
}*/
//columns: [4, 8, 9, 10, 11, 12, 13, 14]
}
},{
extend: 'excel',
orientation: 'landscape',
exportOptions: {
columns: ':visible',
columns: ':not(.no-print)',
format: {
body: function ( data, row, column, node ) {
//
//check if type is input using jquery
//console.log('PRUEBA: ' + $(data).val() );
if( $(data).is("input") ){
return data;
}else{
return $(data).val();
}
}
}
//columns: [4, 8, 9, 10, 11, 12, 13, 14]
}
},{
text: 'Imprimir',
extend: 'print',
orientation: 'landscape',
exportOptions: {
columns: ':visible',
columns: ':not(.no-print)'
}
},
/* 'colvis'*/
]
}
],.....
Out put in PDF:
I hope I could have provided enough information to resolve this, if it can be resolved. And if more information is needed, do not hesitate to tell me.
Thank you very much in advance
I've been struggling with this one recently and finally found the solution. I'll try to make it a bit more detailed.
Here's a function that checks if the exported node is the node. In such case it returns the input.value - otherwise just the data:
//function for DataTable data export to export <input>.value
var buttonCommon = {
exportOptions: {
format: {
body: function ( data, row, column, node ) {
//check if type is input using jquery
return node.firstChild.tagName === "INPUT" ?
node.firstElementChild.value :
data;
}
}
}
};
Now, with this function defined, we use it to extend the buttons:
buttons: [
$.extend( true, {}, buttonCommon, {
extend: 'copyHtml5'
} ),
$.extend( true, {}, buttonCommon, {
extend: 'excelHtml5'
} ),
$.extend( true, {}, buttonCommon, {
extend: 'pdfHtml5'
} ),
$.extend( true, {}, buttonCommon, {
extend: 'csvHtml5'
} )
],
var buttonCommon = {
exportOptions: {
format: {
body: function(data, column, row, node) {
if (row == 1) {
return $(data).is("div") ? $(data).text() : data
}
else if (row == 4) {
return $(data).is("select") ? $(data).val() : data
}
else {
return $(data).is("input") ? $(data).val() : data
}
}
}
}
};
$(document).ready(function() {
$('#tables').DataTable({
dom: 'Bfrtip',
"paging": !1,
buttons: [$.extend(!0, {}, buttonCommon, {
extend: "excel"
})]
})
});
ok, in your button
exportOptions: {
orthogonal: 'export',
}
in your columns :
render: function (data, type, row) {
return type === 'export' ? row.Descripcion: "";
}

How to make status "active" or "expired" in a column in datatables?

I am using laravel 5 and I have a datatables like in the picture below. In the status column, I want to make if the date is more than current date, then the status is "expired". And if the date is less than or equal with the current date, then the status is "active". Else status is "deactive". Do you know how to do it?
This below is my datatables javascript:
$(document).ready(function(){
var oTable = $('#surat').DataTable({
processing: true,
serverSide: true,
ajax: {
url: '{!! route("datasurat") !!}',
data: function (d) {
d.jenis_surat = $('input[name=jenis_surat]').val();
d.nomor_surat = $('input[name=nomor_surat]').val();
d.perihal = $('input[name=perihal]').val();
}
},
columns: [
{data: 'no', name: 'no'},
{data: 'jenis_surat', name: 'jenis_surat'},
{data: 'nomor_surat', name: 'nomor_surat'},
{data: 'perihal', name: 'perihal'},
{data: 'date_to', name: 'date_to'},
{data: 'status', name: 'status',
mRender: function(data, type, full) {
if (strtotime($request['date_to']) < strtotime(date("Y-m-d")) || strtotime($request['date_to']) = '0000-00-00') {
return '<span class="label label-default">Active</span>';
}
else if(strtotime($request['date_to']) > strtotime(date("Y-m-d"))){
return '<span class="label label-default">Expired</span>';
}
else {
return '<span class="label label-default">Deactive</span>';
}
}
},
{data: 'action', name: 'action'}
]
});
$('#search_form').on('submit', function(e) {
oTable.ajax.reload();
e.preventDefault();
});
});
Have a look at column rendering in the datatables initialization. The example code from datatables documentation:
$(document).ready(function() {
$('#example').DataTable( {
"columnDefs": [
{
// The `data` parameter refers to the data for the cell (defined by the
// `data` option, which defaults to the column being worked with, in
// this case `data: 0`.
"render": function ( data, type, row ) {
return data +' ('+ row[3]+')';
},
"targets": 0
},
{ "visible": false, "targets": [ 3 ] }
]
} );
} );
This will generate the first column with the data provided in the first column combined with the data provided in the 3rd column. You could use it in a similar way to compare data from one column to another and then define a string to render.
Here's a rough idea of how you might use it with your data:
columns: [
{data: 'no', name: 'no'},
{data: 'jenis_surat', name: 'jenis_surat'},
{data: 'nomor_surat', name: 'nomor_surat'},
{data: 'perihal', name: 'perihal'},
{data: 'date_to', name: 'date_to'},
{data: 'status', name: 'status'},
]
columnDefs: [
{
"render": function(data, type, row) {
if (strtotime(row.date_to) < strtotime(date("Y-m-d"))) {
return '<span class="label label-default">Active</span>';
}
else if (strtotime(row.date_to) > strtotime(date("Y-m-d"))) {
return '<span class="label label-default">Expired</span>';
}
else {
return '<span class="label label-default">Deactive</span>';
}
}, "targets": [5]
}
]

EnhancedGrid within another EnhancedGrid

I'm using the dojo grid cell formatter to display an inner grid within another grid. Even though the inner grid is added, it does not display on the HTML page cause its height and width are 0px.
My JSP page and the JS page where the grids are created is shown below. Any help will be appreciated.
My guess is that calling grid.startup() in the cell formatter is probably not the right place. But where should I move the startup() call to -or- is there something else that needs to be done to get the inner grid to render correctly.
----JSP file ----
<script type="text/javascript"> dojo.require("portlets.ListPortlet"); var <portlet:namespace/>args = { namespace: '<portlet:namespace/>', listDivId: 'listGrid' }; var <portlet:namespace/>controller = new portlets.ListPortlet(<portlet:namespace/>args); dojo.addOnLoad(function(){ <portlet:namespace/>controller.init(); }); </script>
</div>
----JS file ----
dojo.declare("portlets.ListPortlet", null, {
constructor: function(args){
dojo.mixin(this,args);
this.params = args;
},
init: function(){
var layout = [[
{field: 'site', name: 'Site', width: '30px' }
{field: 'name', name: 'Full Name', width: '100px'},
{field: 'recordStatus', name: 'Status', width: '80px' }
],[
{field: '_item', name: ' ', filterable: false, formatter: this.formatNotesTable, colSpan: 3 }
]];
this.grid = new dojox.grid.EnhancedGrid({
autoHeight: true,
autoWidth: true,
selectable: true,
query:{
fromDate: start,
toDate: end
},
rowsPerPage: 10
});
this.grid.placeAt(dojo.byId(this.listDivId));
this.dataStore = new dojox.data.JsonRestStore({target: dataURL, idAttribute: idAttribute});
this.grid.setStructure(layout);
this.grid.startup();
},
formatNotesTable(rowObj) {
var gridData = {
identifier:"id",
items: [
{id:1, "Name":915,"IpAddress":6},
{id:2, "Name":916,"IpAddress":7}
]
};
var gridStructure = [{
cells:[
[
{ field: "Name",
name: "Name",
},
{ field: "IpAddress",
name: "Ip Address" ,
styles: 'text-align: right;'
}
]
]
}];
var gridStore = new dojo.data.ItemFileReadStore( { data: gridData} );
var cpane = new dijit.layout.ContentPane ({
content: "inner grid should be displayed below"
});
var subgrid = new dojox.grid.DataGrid({
store: gridStore,
structure: gridStructure,
style: {width: "325px", height: "300px"}
});
subgrid.placeAt(cpane);
subgrid.startup();
return cpane;
}
}
I solved my problem by using a dojox.layout.TableContainer inside the EnhancedGrid.

ExtJS 4.1 Infinite Grid Scrolling doesnt work with Dynamic store using loadData

I have to load first grid panel on tab and then load data into store using loadData() function which is working fine, but now I have to integrate infinite grid scrolling with it.
Is there any way to integrate infinite scrolling on fly after loadData into store..? I am using ExtJS 4.1. Please help me out.
Here I am showing my current script in controller and grip view panel in which I have tried out but not working.
Controller Script as below:
var c = this.getApplication().getController('Main'),
data = c.generateReportGridConfiguration(response,true),
tabParams = {
title: 'Generated Report',
closable: true,
iconCls: 'view',
widget: 'generatedReportGrid',
layout: 'fit',
gridConfig: data
},
generatedReportGrid = this.addTab(tabParams);
generatedReportGrid.getStore().loadData(data.data);
On Above script, once I get Ajax call response, adding grid panel with tabParams and passed data with gridConfig param which will be set fields and columns for grid and then last statement supply grid data to grid. I have tried out grid panel settings by following reference example:
http://dev.sencha.com/deploy/ext-4.0.1/examples/grid/infinite-scroll.html
On above page, Included script => http://dev.sencha.com/deploy/ext-4.0.1/examples/grid/infinite-scroll.js
My Grid Panel Script as below:
Ext.define('ReportsBuilder.view.GeneratedReportGrid', {
extend: 'Ext.grid.Panel',
alias: 'widget.generatedReportGrid',
requires: [
'ReportsBuilder.view.GenerateViewToolbar',
'Ext.grid.*',
'Ext.data.*',
'Ext.util.*',
'Ext.grid.PagingScroller',
'Ext.grid.RowNumberer',
],
initComponent: function() {
Ext.define('Report', {extend: 'Ext.data.Model', fields: this.gridConfig.fields, idProperty: 'rowid'});
var myStore = Ext.create('Ext.data.Store', {model: 'Report', groupField: 'name',
// allow the grid to interact with the paging scroller by buffering
buffered: true,
pageSize: 100,
autoSync: true,
extraParams: { total: 50000 },
purgePageCount: 0,
proxy: {
type: 'ajax',
data: {},
extraParams: {
total: 50000
},
reader: {
root: 'data',
totalProperty: 'totalCount'
},
// sends single sort as multi parameter
simpleSortMode: true
}
});
Ext.apply(this, {
dockedItems: [
{xtype: 'generateviewToolbar'}
],
store: myStore,
width:700,
height:500,
scroll: 'vertical',
loadMask: true,
verticalScroller:'paginggridscroller',
invalidateScrollerOnRefresh: false,
viewConfig: {
trackOver: false,
emptyText: [
'<div class="empty-workspace-bg">',
'<div class="empty-workspace-vertical-block-message">There are no results for provided conditions</div>',
'<div class="empty-workspace-vertical-block-message-helper"></div>',
'</div>'
].join('')
},
columns: this.gridConfig.columns,
features: [
{ftype: 'groupingsummary', groupHeaderTpl: '{name} ({rows.length} Record{[values.rows.length > 1 ? "s" : ""]})', enableGroupingMenu: false}
],
renderTo: Ext.getBody()
});
// trigger the data store load
myStore.guaranteeRange(0, 99);
this.callParent(arguments);
}
});
I have also handled start and limit from server side query but it will not sending ajax request on scroll just fired at once because pageSize property in grid is 100 and guaranteeRange function call params are 0,99 if i will increased 0,299 then it will be fired three ajax call at once (0,100), (100,200) and (200,300) but showing data on grid for first ajax call only and not fired on vertical scrolling.
As, I am new learner on ExtJs, so please help me out...
Thanks a lot..in advanced.
You cannot call store.loadData with a remote/buffered store and grid implementation and expect the grid to reflect this new data.
Instead, you must call store.load.
Example 1, buffered store using store.load
This example shows the store.on("load") event firing.
http://codepen.io/anon/pen/XJeNQe?editors=001
;(function(Ext) {
Ext.onReady(function() {
console.log("Ext.onReady")
var store = Ext.create("Ext.data.Store", {
fields: ["id", "name"]
,buffered: true
,pageSize: 100
,proxy: {
type: 'rest'
,url: '/anon/pen/azLBeY.js'
reader: {
type: 'json'
}
}
})
store.on("load", function(component, records) {
console.log("store.load")
console.log("records:")
console.log(records)
})
var grid = new Ext.create("Ext.grid.Panel", {
requires: ['Ext.grid.plugin.BufferedRenderer']
,plugins: {
ptype: 'bufferedrenderer'
}
,title: "people"
,height: 200
,loadMask: true
,store: store
,columns: [
{text: "id", dataIndex: "id"}
,{text: "name", dataIndex: "name"}
]
})
grid.on("afterrender", function(component) {
console.log("grid.afterrender")
})
grid.render(Ext.getBody())
store.load()
})
})(Ext)
Example 2, static store using store.loadData
You can see from this example that the store.on("load") event never fires.
http://codepen.io/anon/pen/XJeNQe?editors=001
;(function(Ext) {
Ext.onReady(function() {
console.log("Ext.onReady")
var store = Ext.create("Ext.data.Store", {
fields: ["id", "name"]
,proxy: {
type: 'rest'
,reader: {
type: 'json'
}
}
})
store.on("load", function(component, records) {
console.log("store.load")
console.log("records:")
console.log(records)
})
var grid = new Ext.create("Ext.grid.Panel", {
title: "people"
,height: 200
,store: store
,loadMask: true
,columns: [
{text: "id", dataIndex: "id"}
,{text: "name", dataIndex: "name"}
]
})
grid.on("afterrender", function(component) {
console.log("grid.afterrender")
})
grid.render(Ext.getBody())
var data = [
{'id': 1, 'name': 'Vinnie'}
,{'id': 2, 'name': 'Johna'}
,{'id': 3, 'name': 'Jere'}
,{'id': 4, 'name': 'Magdalena'}
,{'id': 5, 'name': 'Euna'}
,{'id': 6, 'name': 'Mikki'}
,{'id': 7, 'name': 'Obdulia'}
,{'id': 8, 'name': 'Elvina'}
,{'id': 9, 'name': 'Dick'}
,{'id': 10, 'name': 'Beverly'}
]
store.loadData(data)
})
})(Ext)

Categories

Resources