Cell text colour refuses to change jsdpdf-autotable - jspdf

I have followed the steps to some answers on this topic already, but none of them are working. I have the following text which needs to display in a red text:
<table id="heading1">
<tr>
<td class="hrow"><h4>1. DETAILS</h4></td>
</tr>
</table>
Here is the code I have written for the PDF:
<script>
exportGraph = function () {
var pdfsize = 'a4';
var pdf = new jsPDF('l', 'mm', pdfsize);
var totalPagesExp = "{total_pages_count_string}";
var res2 = pdf.autoTableHtmlToJson(document.getElementById("heading1"));
pdf.autoTable(res2.columns, res2.data, {
createdCell: function(cell, data) {
var tdElement = cell.raw;
if (tdElement.classList.contains("hrow")) {
cell.styles.textColor = "[255,72,72]";
}
},
startY: 10,
margin: {left: 5 },
styles: { halign: 'left', fontsize: 12 }
});
pdf.save('Submission-Printout.pdf');
}
</script>
As you can see, what I have done SHOULD in theory work, but the text still appears as not red. Does anyone know why it's not appearing in red text colour?

What about this example ?
function generate() {
var doc = new jsPDF('p', 'pt', 'a4');
var elem = document.getElementById('example');
var data = doc.autoTableHtmlToJson(elem);
doc.autoTable(data.columns, data.rows, {
createdCell: function (cell, data) {
if ($(cell.raw).hasClass("demo1")) {
cell.styles.textColor = [200, 0, 0];
cell.styles.fontStyle = 'bolditalic';
};
if ($(cell.raw).hasClass("demo2")) {
cell.styles.textColor = [0, 0, 205];
cell.styles.fontStyle = 'bold';
};
return false;
}
});
doc.save("table.pdf");
}

Related

Highcharts gantt chart task progress indicator data labels for multi-color in a single task progress

Please refer the image. I need to show datalabels name over on each color of the progress.
var markers = JSON.parse('<%=ConvertDataTabletoString("uspTaskProgress1","",null,1,10) %>');
var colors = ['skyblue', 'orange', 'red','blue'];
var statusprogress = ['Overall Subtask Percentage'];
var Arrayset = [];
var starts1 = [];
var ends1 = [];
var val1 = [];
var val2 = [];
var categories = [];
if (markers != null) {
if (markers.length > 0) {
var prj=document.getElementById("param1").value;
for (var i = 0; i < markers.length; i++) {
var syearval = parseInt(markers[i].ActualStart.substr(0, 4));
var smonthval = parseInt(markers[i].ActualStart.substr(5, 2))-1;
var sdateval = parseInt(markers[i].ActualStart.substr(8, 2));
var eyearval = parseInt(markers[i].ActualEnd.substr(0, 4));
var emonthval = parseInt(markers[i].ActualEnd.substr(5, 2))-1;
var edateval = parseInt(markers[i].ActualEnd.substr(8, 2));
val1 = [Date.UTC(syearval, smonthval, sdateval)];
val2 = [Date.UTC(eyearval, emonthval, edateval)];
starts1.push(val1[0]);
ends1.push(val2[0]);
Arrayset.push({ color:colors[i],name: markers[i].Task, start: starts1[i], end: ends1[i], completed: markers[i].OverallSubtaskPercentage, y:0});
}
for (var j = 0; j < markers.length; j++) {
categories.push(markers[j].Task);
}
MainLoadChart(Arrayset, categories);
}
}
function MainLoadChart(array,categories) {
var dta = array;
Highcharts.ganttChart('container8', {
chart: {
type: 'xrange'
},
xAxis: {
type: 'datetime'
},
yAxis: {
categories: categories,
},
title: {
text: 'Task Progress Indicator Status'
},
tooltip: {
formatter() {
let output = ` <span style="font-size: 20px;color:green">${prj}</span><br>
<span><b>${this.key}(Overall Subtask Percentage):${this.point.completed}% </b></span><br>
<span>Start: ${Highcharts.dateFormat('%A, %e. %b, %Y', this.x)}</span><br>
<span>End: ${Highcharts.dateFormat('%A, %e. %b, %Y', this.x2)}</span>`
return output
}
},
series: [{
data:dta,
dataLabels: {
formatter() {
let output1 = ` <span style="font-size: 10px">${this.point.completed}%</span>`
return output1
}
}
}]
});
}
I added datalabels property in series.data but it's not showing in the output. Can let us know how to add the data labels name on each color of the task progress. Image attached. It's a highcharts gantt chart.Code is attached please have a review on the code
You can set the dataLabels options, like formatter to set what data label should display, for each point in the data config.
Like this:
data: [{
name: 'test1',
start: Date.UTC(2014, 10, 18),
end: Date.UTC(2014, 10, 25),
completed: 0.25,
y: 0,
dataLabels: {
enabled: true,
x: 150,
formatter() {
return 'test1'
}
}
}, ...]
Demo: https://jsfiddle.net/BlackLabel/am0w5Lkr/
In the above demo I set the x to some fixed value because I am not sure if your chart should be responsive or not. In case of the responsive chart, I encourage to use the render callback https://api.highcharts.com/highcharts/chart.events.render to calculate datalabels position after each resizes.
API: https://api.highcharts.com/highcharts/series.line.dataLabels.x
API: https://api.highcharts.com/highcharts/series.line.dataLabels.formatter

Format content after table (jsPDF autotable)

i want to add content after a table in a pdf file that was created with jsPDF autotable.
My Code:
$('#printBtn').on('click', function() {
var pdf = new jsPDF('p', 'pt', 'a4');
var res = pdf.autoTableHtmlToJson(document.getElementById("tablePrint"));
var anfang = "Anfang";
pdf.text(anfang, 14, 30);
pdf.autoTable(res.columns, res.data, {
theme : 'plain',
styles: {
fontSize: 12
},
showHeader: 'never',
createdCell: function(cell, data) {
var tdElement = cell.raw;
if (tdElement.classList.contains('hrow')) {
cell.styles.fontStyle = 'bold';
}
}
});
var ende = $('#ende_text').text();
pdf.text(ende, 0, 12);
pdf.save("test.pdf");
});
My Problem is that the code isn't formatted. The tags and everything else was ignored by jsPDF.
How can i fix that or what can i do that the text has line breaks and not overflow?
Thanks for help!
margins={
top=50,
left=30,
bottom=50,
width=520
}
var pdf = new jsPDF("p", "pt","a4");
var res = pdf.autoTableHtmlToJson(document.getElementById("table2"));
pdf.autoTable(res.columns, res.data,{
margin: { left: 30,bottom:100},
startY: 30, pageBreak: 'always',
styles: {overflow: 'linebreak', columnWidth: 'wrap', font: 'arial',
cellPadding: 8, overflowColumns: 'linebreak'}
});
pdf.fromHTML($("#editor1").get(0), 30, pdf.autoTableEndPosY() + 20, {
'width': margins.width
},function(dispose)
{
var iframe = document.createElement('iframe');
iframe.setAttribute('style','position:absolute;right:0; top:0; bottom:0; height:100%; width:40%; padding:20px;');
document.body.appendChild(iframe);
iframe.src = pdf.output('datauristring');
//pdf.save('name.pdf');
},
margins);
iam using the latest version of jspdf.min.js and jspdf.autotable.js
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/2.3.5/jspdf.plugin.autotable.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.4.1/jspdf.min.js"></script>

How to get table row image in PDF using jsPDF?

i have a html table with images.When i was trying to convert as PDF Only data are coming.Image not displaying in PDF.
How to get table td images in pdf ?
Contract Title Contains a Checkbox image.But is not coming in pdf ?
my pdf code :
function fnExportDIVToPDF() {
var pdf = new jsPDF('l', 'pt', 'a2');
pdf.setFontSize(8);
source = $('#divReport')[0];
specialElementHandlers = {
'#bypassme': function (element, renderer) {
return true
}
};
margins = {
top: 30, bottom: 40, left: 10, width: 1300};
pdf.fromHTML(
source, margins.left, margins.top, {
'elementHandlers': specialElementHandlers},
function (dispose) {
pdf.save('Report.pdf');
}
, margins);
}
Div:
<div id="divReport">
<div width="100%">
<p><span id="oHeadingSummary" class="rptheader"></span></p>
</div>
<table class="table table-striped rpttable" border="1" cellspacing="0" id="oReportContractDetailsByCA" width="100%">
<colgroup>... <col width="10%">
</colgroup></table>
Autogenerate table i added a image :
function GenerateTable(data) {
document.getElementById('divExport').style.display = "";
if (i == 0) {
$('#oReportContractDetailsByCA').append("<tr style='background-color:" + bkColor + ";'><td><img src='../../../_layouts/15/1033/IMAGES/eContracts/checked-checkbox-512.jpg'></img></td></tr>")
}
You can use the didDrawCell hook to add any content to a cell.
https://codepen.io/someatoms/pen/vLYXWB
function generate() {
var doc = new jsPDF();
doc.autoTable({
html: '#mytable',
bodyStyles: {minCellHeight: 15},
didDrawCell: function(data) {
if (data.column.index === 5 && data.cell.section === 'body') {
var td = data.cell.raw;
// Assuming the td cells have an img element with a data url set (<td><img src="data:image/jpeg;base64,/9j/4AAQ..."></td>)
var img = td.getElementsByTagName('img')[0];
var dim = data.cell.height - data.cell.padding('vertical');
var textPos = data.cell.textPos;
doc.addImage(img.src, textPos.x, textPos.y, dim, dim);
}
}
});
doc.save("table.pdf");
}

Highcharts low performance when adding yAxis dynamically

I am trying to add/delete yAxis dynamically but I observe performance issues. It takes more than a second (sometimes it goes upto 4 seconds) to dynamically add or remove a series into a new yAxis. I need to load end of day data (price point for each day) for 10 or more years in the chart.
Any advice in improving the performance will be much appreciated.
Few points to note -
I can use different type of charts (line, ohlc, candlestick, area etc.)
I need mouse tracking to be enabled as I am using click events on the series.
User will have option to either choose to apply data grouping or to not.
Below is my code sample to illustrate the problem.
var chart;
var index = 2;
var groupingUnitsD = {units:[['day',[1]]], enabled:true};
var groupingUnitsWM = [[
'week', // unit name
[1] // allowed multiples
], [
'month',
[1, 2, 3, 4, 6]
]];
$(function () {
var ohlc = [];
$.getJSON('http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-ohlcv.json&callback=?', function (data) {
// split the data set into ohlc
var volume = [],
dataLength = data.length,
i = 0;
for (i; i < dataLength; i++) {
ohlc.push([
data[i][0], // the date
data[i][1], // open
data[i][2], // high
data[i][3], // low
data[i][4] // close
]);
}
loadChart(data);
});
function loadChart(cdata){
var highchartOptions = {
plotOptions:{
line: {
enableMouseTracking: true,
animation:false,
marker: {
enabled: false
}
},
series:{
cursor: 'pointer',
}
},
chart:{
renderTo:'container'
},
navigator: {
outlineColor: '#0066DD',
outlineWidth: 1
},
xAxis: [{
gridLineWidth: 1,
gridLineColor: "#eaf5ff",
lineColor: '#FF0000',
lineWidth: 1
}],
yAxis:[{
title:{
text:"initial data"
},
id:'myaxis-1',
height:'14%',
top:'0%'
}],
series: [{
data: cdata,
turboThreshold:0,
dataGrouping:groupingUnitsD
}]
};
chart = new Highcharts.StockChart(highchartOptions);
}
$button = $('#button');
$delButton = $('#delbutton');
$button.click(function () {
var axisObj = {
title: {
text: "axis-" + index,
},
id:'myaxis-'+ index
};
chart.addAxis(axisObj, false);
console.log("Added axis:" + 'myaxis-'+ index);
$('#axisList').append($('<option></option>').text('myaxis-'+ index));
var seriesData = new Object();
seriesData.name = 'axis-' + index;
seriesData.id = 'myaxis-' + index;
seriesData.yAxis = 'myaxis-'+ index;
seriesData.data = ohlc;
seriesData.type = 'line';
seriesData.dataGrouping = groupingUnitsD;
chart.addSeries(seriesData);
updateAxisHeight();
index++;
});
$delButton.click(function () {
var $select = $('#axisList');
console.log($select.val());
console.log(chart.get($select.val()));
var selId = $select.val();
chart.get(selId).remove();
$('option:selected', $select).remove();
var i=0;
updateAxisHeight();
});
updateAxisHeight = function(){
var i=0;
$("#axisList > option").each(function() {
chart.get(this.value).update({ height: '14%',top: (i*15) + '%',offset:0 });
i++;
});
}
});
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="http://code.highcharts.com/stock/highstock.js"></script>
<script src="http://code.highcharts.com/stock/highcharts-more.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<button id="button" class="autocompare">Add yAxis</button><br>
<!--Entrt yAxis index to delete:<input type='text' id="delAxis"/> -->
<select id="axisList" name="axisList">
<option value="myaxis-1" selected="selected">myaxis-1</option>
</select>
<button id="delbutton" class="autocompare">Delete yAxis</button>
<div id="container" style="height: 800px"></div>
You can significantly improve the performance in this case with one trick: when performing several consecutive operations that each require a redraw (add series, add axis, update axis height), don't redraw until you've told Highcharts about all the operations.
On my machine, this improves the performance of your add axis function by 5x-6x. See code and comments below.
var chart;
var index = 2;
var groupingUnitsD = {units:[['day',[1]]], enabled:true};
var groupingUnitsWM = [[
'week', // unit name
[1] // allowed multiples
], [
'month',
[1, 2, 3, 4, 6]
]];
$(function () {
var ohlc = [];
$.getJSON('http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-ohlcv.json&callback=?', function (data) {
// split the data set into ohlc
var volume = [],
dataLength = data.length,
i = 0;
for (i; i < dataLength; i++) {
ohlc.push([
data[i][0], // the date
data[i][1], // open
data[i][2], // high
data[i][3], // low
data[i][4] // close
]);
}
loadChart(data);
});
function loadChart(cdata){
console.time("chart load");
var highchartOptions = {
plotOptions:{
line: {
enableMouseTracking: true,
animation: false,
marker: {
enabled: false
}
},
series:{
cursor: 'pointer',
}
},
chart:{
alignTicks: false,
events: {
load: function () {
console.timeEnd("chart load");
}
},
renderTo:'container'
},
yAxis:[{
title:{
text:"initial data"
},
id:'myaxis-1',
height:'14%',
top:'0%'
}],
series: [{
data: cdata,
turboThreshold:0,
dataGrouping:groupingUnitsD
}]
};
chart = new Highcharts.StockChart(highchartOptions);
}
$button = $('#button');
$delButton = $('#delbutton');
$button.click(function () {
var startTime = new Date().getTime();
var axisObj = {
title: {
text: "axis-" + index,
},
id:'myaxis-'+ index
};
chart.addAxis(axisObj, false, false); // don't redraw yet
console.log("Added axis:" + 'myaxis-'+ index);
$('#axisList').append($('<option></option>').text('myaxis-'+ index));
var seriesData = new Object();
seriesData.name = 'axis-' + index;
seriesData.id = 'myaxis-' + index;
seriesData.yAxis = 'myaxis-'+ index;
seriesData.data = ohlc;
seriesData.type = 'line';
seriesData.dataGrouping = groupingUnitsD;
chart.addSeries(seriesData, false); // don't redraw yet
updateAxisHeight(false); // don't redraw yet
index++;
// finally, redraw now
chart.redraw();
var endTime = new Date().getTime();
console.log("add axis took " + (endTime - startTime) + " msec");
});
$delButton.click(function () {
var $select = $('#axisList');
console.log($select.val());
console.log(chart.get($select.val()));
var selId = $select.val();
chart.get(selId).remove();
$('option:selected', $select).remove();
var i=0;
updateAxisHeight();
});
updateAxisHeight = function(redraw){
// set redraw to true by default, like Highcharts does
if (typeof redraw === 'undefined') {
redraw = true;
}
var i=0;
$("#axisList > option").each(function() {
// don't redraw in every iteration
chart.get(this.value).update({ height: '14%',top: (i*15) + '%',offset:0 }, false);
i++;
});
// redraw if caller asked to, or if the redraw parameter was not specified
if (redraw) {
chart.redraw();
}
}
});
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="http://code.highcharts.com/stock/highstock.js"></script>
<script src="http://code.highcharts.com/stock/highcharts-more.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<button id="button" class="autocompare">Add yAxis</button><br>
<!--Entrt yAxis index to delete:<input type='text' id="delAxis"/> -->
<select id="axisList" name="axisList">
<option value="myaxis-1" selected="selected">myaxis-1</option>
</select>
<button id="delbutton" class="autocompare">Delete yAxis</button>
<div id="container" style="height: 800px"></div>

Infobox not working

I'm not a developer and i'm trying to learn javascript step by step. Now, I need to add a simple infobox in the gmaps that I'm working on. The problem is that, I add the code as explained in the google reference but it doesn't work: in the beginning i was using infowindow wich worked well but wasn't so customized. I also put the infobox.js link in that page and it is the last release.
This is test page: http://www.squassabia.com/aree_espositive_prova2.asp
What i need to do is to display the message you see in the code (boxText.innerHTML), just to understand it step by step and to keep things simple. After that I'm going to style it and add data from xml (which I think is not going to be that difficult).
As i didn't fint any solution in any of the old posts, if anyone of you can give me a clue on how to solve the problem, would be very appreciated, I've tried everything and put infobox stuff pretty much everywhere :(
Cheers
I give you the initialize() code:
//icone custom
var customIcons = {
negozio: {icon: '/images/gmaps/mc.png'},
outlet: {icon: '/images/gmaps/pin_fuc_outlet.png'},
sede: {icon: '/images/gmaps/pin_fuc_home.png'}
};
var clusterStyles = [
{
textColor: 'white',
url: '/images/gmaps/mc.png',
height: 48,
width: 48
}];
function initialize() {
//creo una istanza della mappa
var map = new google.maps.Map(document.getElementById("mapp"), {
center: new google.maps.LatLng(45.405, 9.867),
zoom: 9,
mapTypeId: 'roadmap',
saturation: 20, //scrollwheel: false
});
//stile della mappa
var pinkroad = [ //creo un array di proprietà
{
featureType: "all", //seleziono la feature
stylers: [{gamma: 0.8 },{ lightness: 50 },{ saturation: -100}]
},
{
featureType: "road.highway.controlled_access",
stylers: [{ hue: "#FF3366" },{ saturation: 50 },{ lightness: -5 }]
}
];
map.setOptions({styles: pinkroad});
var name;
//Creates content and style
var boxText = document.createElement("div");
boxText.style.cssText = "border: 1px solid black; margin-top: 8px; background: yellow; padding: 5px;";
boxText.innerHTML = "Prova Infobox<br >Successo!!Test Text";
var myOptions = {
content: boxText
,disableAutoPan: false
,maxWidth: 0
,pixelOffset: new google.maps.Size(-140, 0)
,zIndex: null
,boxStyle: {background: "url('tipbox.gif') no-repeat", opacity: 0.75, width: "280px"}
,closeBoxMargin: "10px 2px 2px 2px"
,closeBoxURL: "http://www.google.com/intl/en_us/mapfiles/close.gif"
,infoBoxClearance: new google.maps.Size(1, 1)
,isHidden: false
,pane: "floatPane"
,enableEventPropagation: false
};
var ib = new InfoBox(myOptions);
//creo il marker
downloadUrl("xml/negozi.xml", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++)
{
var type = markers[i].getAttribute("tipo");
var address = markers[i].getElementsByTagName("indirizzo")[0].childNodes[0].nodeValue;
var city = markers[i].getElementsByTagName("citta")[0].childNodes[0].nodeValue;
var phone = markers[i].getElementsByTagName("telefono")[0].childNodes[0].nodeValue;
name = markers[i].getElementsByTagName("nome")[0].childNodes[0].nodeValue;
var point = new google.maps.LatLng(parseFloat(markers[i].getAttribute("lat")), parseFloat(markers[i].getAttribute("lng")));
var html = name + '<br />' + address + '<br />' + city + '<br />' + phone;
var icon = '/images/gmaps/pin_fuc.png';
var marker = new google.maps.Marker({map: map, position: point, icon :'/images/gmaps/pin_fuc.png'});
/*google.maps.event.addListener(marker,"click", function(){
map.panTo(this.position);
});*/
createMarkerButton(marker);
google.maps.event.addListener(marker, "click", function (e) {
ib.open(map);
});
}
});
function createMarkerButton(marker) {
//Creates a sidebar button
var ul = document.getElementById("list");
var li = document.createElement("li");
li.appendChild(document.createTextNode(name));
ul.appendChild(li);
//Trigger a click event to marker when the button is clicked.
google.maps.event.addDomListener(li, "mouseover", function(){
marker.setAnimation(google.maps.Animation.BOUNCE);
setTimeout (function (){marker.setAnimation(null);}, 750);
});
google.maps.event.addDomListener(li, "mouseout", function(){
google.maps.event.trigger(marker, "mouseout");
});
}
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}

Resources