Chart not rendered completely when using JSPDF - javascript

I am trying to print charts (JSChart) in a pdf using jsPDF. It seems like the chart image is created while the chart is not rendered completely (the data points are still on the bottom of the chart).
var ssvCanvas = document.querySelector('#line-chart-ssv');
var ssvCanvasImg = ssvCanvas.toDataURL("image/png", 1.0);
var doc = new jsPDF();
var ssvImgProps = doc.getImageProperties(ssvCanvasImg);
var width = doc.internal.pageSize.getWidth()-20;
var ssvHeight = (ssvImgProps.height * width) / ssvImgProps.width;
doc.addImage(ssvCanvasImg, 'JPEG', 10, 40, width, ssvHeight );
I have no idea what could help. A wait function wasnt useful as of now.
Can somebody please help?

Related

How to convert as pdf while dealing with xml nodes in mxGraph?

I am implementing the graph editor using mxGraph javascript library and able to display the diagram and save the diagram.
Now,I have to export the diagram in to PDF file.
Primary question is,
Is there any other builtin feature is available on mxGraph library itself?
I used mxImageExport() class to exporting PNG image then its is redirecting to null url page.redirect page image
Here is the code:
function convertPDF() {
var graph = universalGraph; // get xml form the graph stored in graph variable
var xmlDoc = mxUtils.createXmlDocument();
var root = xmlDoc.createElement('output');
xmlDoc.appendChild(root);
var xmlCanvas = new mxXmlCanvas2D(root);
var imgExport = new mxImageExport();
imgExport.drawState(graph.getView().getState(graph.model.root), xmlCanvas);
var bounds = graph.getGraphBounds();
var w = Math.ceil(bounds.x + bounds.width);
var h = Math.ceil(bounds.y + bounds.height);
var xml = mxUtils.getXml(root);
new mxXmlRequest('export', 'format=png&w=' + w +
'&h=' + h + '&bg=#F9F7ED&xml=' + encodeURIComponent(xml))
.simulate(document, '_self');
}
(or) else I have to use regular JS PDF library?(I cannot convert the HTML content inside tag in to PDF, While converting it is showing
graph's background only no single shapes are in it. Since it is from XML nodes, I referred the internet and asked me to convert from XML in to SVG then PDF
but this method also not work because I have received the blank PDF file.)
Here is the code:
function savePDF() {
var imgData;
html2canvas($(".svgClass"), {
useCORS: true,
onrendered: function(canvas) {
imgData = canvas.toDataURL(
'image/png');
console.log(imgData);
var doc = new jsPDF('p', 'pt', 'a4');
doc.addImage(imgData, 'PNG', 10, 10);
doc.save('sample-file.pdf');
window.open(imgData);
}
});
}

ChartJS and jsPDF - why the background is black?

I am generating PDF file using jsPDF library. Everything is okay, but at page my chart has white background ( on PDF - black ):
Chart from my webpage:
And from PDF:
my code for generating file:
var newCanvas = document.querySelector('#canvasChart');
var newCanvasImg = newCanvas.toDataURL("image/jpeg", 1.0);
var doc = new jsPDF('landscape');
doc.setFontSize(20);
doc.text(15, 15, "Super Cool Chart");
doc.addImage(newCanvasImg, 'JPEG', 10, 10, 280, 150 );
doc.save('new-canvas.pdf');
Do you have an idea how to solve this ?
Thanks in advance,
Maybe later, but I solved using PNG image:
var newCanvasImg = newCanvas.toDataURL("image/png", 1.0);
Hope this helps.

How to find selected path on svg image in xamarin forms

I'm using a C# library in which I'm unable to select path of a svg image.
I'm developing a hybrid mobile application, using the Xamarin.Forms platform where I have to display svg image and I have to highlight the selected parts. So, I have added SVG nuget package. The SVG image is working fine but, I am unable to find the selected parts. Can anyone please help me?
var svgPaths = new List<string>
{
"SampleApp.Images.sample1.svg",
};
var grid = new Grid
{
RowDefinitions = new RowDefinitionCollection(),
ColumnDefinitions = new ColumnDefinitionCollection()
};
var svgPath = svgPaths[0];
var svgImage = new SvgImage
{
SvgPath = svgPath,
SvgAssembly = typeof(App).GetTypeInfo().Assembly,
HeightRequest = 400,
WidthRequest = 400,
HorizontalOptions = LayoutOptions.Center,
VerticalOptions = LayoutOptions.Center,
BackgroundColor = Color.White
};
grid.Children.Add(svgImage);

Export Highcharts to PDF (using javascript and local server - no internet connection)

I am using Highcharts in my application (without any internet connection)
I have multiple charts on a html page, and I want to generate a PDF report that contains all the charts from this page.
How can I do this without sending the data to any server on the internet ?
I will be thankful for any help or any example you can provide.
Thank you in advance :)
Yes this is possible but involves a few different libraries to get working. The first Library is jsPDF which allows the creation of PDF in the browser. The second is canvg which allows for the rendering and parsing of SVG's, the bit that is really cool though is it can render an svg on to canvas element. Lastly is Highcharts export module which will allow us to send the svg to the canvg to turn into a data URL which can then be given to jsPDF to turn into your pdf.
Here is an example http://fiddle.jshell.net/leighking2/dct9tfvn/ you can also see in there source files you will need to include in your project.
So to start highcharts provides an example of using canvg with it's export to save a chart as a png. because you want all the iamges in a pdf this has been slightly altered for our purpose to just return the data url
// create canvas function from highcharts example http://jsfiddle.net/highcharts/PDnmQ/
(function (H) {
H.Chart.prototype.createCanvas = function (divId) {
var svg = this.getSVG(),
width = parseInt(svg.match(/width="([0-9]+)"/)[1]),
height = parseInt(svg.match(/height="([0-9]+)"/)[1]),
canvas = document.createElement('canvas');
canvas.setAttribute('width', width);
canvas.setAttribute('height', height);
if (canvas.getContext && canvas.getContext('2d')) {
canvg(canvas, svg);
return canvas.toDataURL("image/jpeg");
} 
else {
alert("Your browser doesn't support this feature, please use a modern browser");
return false;
}
}
}(Highcharts));
Then for the example i have set up export on a button click. This will look for all elements of a certain class (so choose one to add to all of your chart elements) and then call their highcharts.createCanvas function.
$('#export_all').click(function () {
var doc = new jsPDF();
// chart height defined here so each chart can be palced
// in a different position
var chartHeight = 80;
// All units are in the set measurement for the document
// This can be changed to "pt" (points), "mm" (Default), "cm", "in"
doc.setFontSize(40);
doc.text(35, 25, "My Exported Charts");
//loop through each chart
$('.myChart').each(function (index) {
var imageData = $(this).highcharts().createCanvas();
// add image to doc, if you have lots of charts,
// you will need to check if you have gone bigger
// than a page and do doc.addPage() before adding
// another image.
/**
* addImage(imagedata, type, x, y, width, height)
*/
doc.addImage(imageData, 'JPEG', 45, (index * chartHeight) + 40, 120, chartHeight);
});
//save with name
doc.save('demo.pdf');
});
important to note here that if you have lots of charts you will need to handle placing them on a new page. The documentation for jsPDF looks really outdated (they do have a good demos page though just not a lot to explain all the options possible), there is an addPage() function and then you can just play with widths and heights until you find something that works.
the last part is to just setup the graphs with an extra option to not display the export button on each graph that would normally display.
//charts
$('#chart1').highcharts({
navigation: {
buttonOptions: {
enabled: false
}
},
//this is just normal highcharts setup form here for two graphs see fiddle for full details
The result isn't too bad i'm impressed with the quality of the graphs as I wasn't expecting much from this, with some playing of the pdf positions and sizes could look really good.
Here is a screen shot showing the network requests made before and after the export, when the export is made no requests are made http://i.imgur.com/ppML6Gk.jpg
here is an example of what the pdf looks like http://i.imgur.com/6fQxLZf.png (looks better when view as actual pdf)
quick example to be tried on local https://github.com/leighquince/HighChartLocalExport
You need to setup your own exporting server, locally like in the article
Here is an example using the library pdfmake:
html:
<div id="chart_exchange" style="width: 450px; height: 400px; margin: 0 auto"></div>
<button id="export">export</button>
<canvas id="chart_exchange_canvas" width="450" height="400" style="display: none;"></canvas>
javascript:
function drawInlineSVG(svgElement, canvas_id, callback) {
var can = document.getElementById(canvas_id);
var ctx = can.getContext('2d');
var img = new Image();
img.setAttribute('src', 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(svgElement))));
img.onload = function() {
ctx.drawImage(img, 0, 0);
callback(can.toDataURL("image/png"));
}
}
full working code:
https://jsfiddle.net/dimitrisscript/f6sbdsps/
Maybe this link can help you out.
http://bit.ly/1IYJIyF
Try refer to the exporting properties (fallbackToExportServer: false) and the necessary file that need to be include (offline-exporting.js).
Whereas for the export all at once part, currently I myself also still trying. Will update here if any.
This question is a bit old but was something i was working on myself recently and had some trouble with it.
I used the jsPDF library: https://github.com/MrRio/jsPDF
Issues i ran into involved jsPDF not supporting the SVG image exported by the high chart + images being blurry and low quality.
Below is the solution I used to get two charts into one pdf document:
function createPDF() {
var doc = new jsPDF('p', 'pt', 'a4'); //Create pdf
if ($('#chart1').length > 0) {
var chartSVG = $('#chart1').highcharts().getSVG();
var chartImg = new Image();
chartImg.onload = function () {
var w = 762;
var h = 600;
var chartCanvas = document.createElement('canvas');
chartCanvas.width = w * 2;
chartCanvas.height = h * 2;
chartCanvas.style.width = w + 'px';
chartCanvas.style.height = h + 'px';
var context = chartCanvas.getContext('2d');
chartCanvas.webkitImageSmoothingEnabled = true;
chartCanvas.mozImageSmoothingEnabled = true;
chartCanvas.imageSmoothingEnabled = true;
chartCanvas.imageSmoothingQuality = "high";
context.scale(2, 2);
chartCanvas.getContext('2d').drawImage(chartImg, 0, 0, 762, 600);
var chartImgData = chartCanvas.toDataURL("image/png");
doc.addImage(chartImgData, 'png', 40, 260, 250, 275);
if ($('#chart2').length > 0) {
var chart2SVG = $('#chart2').highcharts().getSVG(),
chart2Img = new Image();
chart2Img.onload = function () {
var chart2Canvas = document.createElement('canvas');
chart2Canvas.width = w * 2;
chart2Canvas.height = h * 2;
chart2Canvas.style.width = w + 'px';
chart2Canvas.style.height = h + 'px';
var context = chart2Canvas.getContext('2d');
chart2Canvas.webkitImageSmoothingEnabled = true;
chart2Canvas.mozImageSmoothingEnabled = true;
chart2Canvas.imageSmoothingEnabled = true;
chart2Canvas.imageSmoothingQuality = "high";
context.scale(2, 2);
chart2Canvas.getContext('2d').drawImage(chart2Img, 0, 0, 762, 600);
var chart2ImgData = chart2Canvas.toDataURL("image/png");
doc.addImage(chart2ImgData, 'PNG', 300, 260, 250, 275);
doc.save('ChartReport.pdf');
}
chart2Img.src = "data:image/svg+xml;base64," + window.btoa(unescape(encodeURIComponent(chart2SVG)));
}
}
chartImg.src = "data:image/svg+xml;base64," + window.btoa(unescape(encodeURIComponent(chartSVG)));
}
}
scripts to include:
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.2.61/jspdf.min.js"></script>

Converting Google Chart into Image

I'm trying convert a Google Chart into a image like this link but I don't understand about the line
var chartArea = chartContainer.getElementsByTagName('iframe')[0].contentDocument.getElementById('chartArea');
The code generated by the Google Chart, doesn't create any iFrame or elements called chartArea
Can someone help me ?
UPDATED
Follow the source of the generated by the chart, when I transform him into a image
http://chart.googleapis.com/chart?cht=lc&chs=500x200&chtt=Acessos%20ao%20im%C3%B3vel%20dos%20ultimos%20sete%20dias&chxt=x%2Cy&chxl=0%3A%7C24%2F01%7C25%2F01%7C26%2F01%7C27%2F01%7C28%2F01%7C29%2F01%7C30%2F01%7C1%3A%7C%7C0%7C&chdlp=r&chdl=San%7CSite%7CAtendimento&chco=ff8a00%2C585857%2C5501ff&chd=e%3Af.f.f.f.f.f.f.%2Cf.f.f.f.f.f.f.%2Cf.f.f.f.f.f.f.
This can be done by following the steps on this page. Note that the code in the article is based on an old version of Google Visualization which used iframes, and will not work as posted. However, you can do the same using the following code (found in the comments):
var svg = $(chartContainer).find('svg').parent().html();
var doc = chartContainer.ownerDocument;
var canvas = doc.createElement('canvas');
canvas.setAttribute('style', 'position: absolute; ' + '');
doc.body.appendChild(canvas);
canvg(canvas, svg);
var imgData = canvas.toDataURL("image/png");
canvas.parentNode.removeChild(canvas);
return imgData;
Note: I did not create this code, it was originally created by the author of the above site (Riccardo Govoni) and updated in the comments section by user Thomas.
You can get a PNG version of your chart using chart.getImageURI() like following:
Needs to be after the chart is drawn, so in the ready event!
var my_div = document.getElementById('my_div');
var my_chart = new google.visualization.ChartType(chart_div);
google.visualization.events.addListener(my_chart, 'ready', function () {
my_div.innerHTML = '<img src="' + chart.getImageURI() + '">';
});
my_chart.draw(data);

Categories