Duplicate content in pdf created using jsPDF - javascript

I am using jsPDF to convert html to pdf. In some cases, where html has svg charts, some of the data is duplicated in the generated pdf.
e.g. If the charts have legends, they are getting duplicated. See the screenshot below. City names and the percentages are repeated.
Below is the code to create pdf.
pdf.addHTML($("#page1"), options, function(){
pdf.addPage();
pdf.addHTML($("#page2"), options, function(){
pdf.addPage();
pdf.output('dataurlnewwindow');
});
});
EDIT 1:
This is what I have figured so far.
<div id="outerDiv">
<div id="pieChart"></div>
</div>
When I do this, pdf.addHTML($("#pieChart"), no issues here.
But, when I do this, pdf.addHTML($("#outerDiv"), then labels get repeated.
and this is how I generate my c3js charts
var pieChart = c3.generate({
bindto: '#pieChart',
EDIT 2:-
Below is my entire code.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/c3/0.4.10/c3.min.css">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/c3/0.4.10/c3.min.js"></script>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
<script type="text/javascript" src="http://gabelerner.github.io/canvg/rgbcolor.js"></script>
<script type="text/javascript" src="http://gabelerner.github.io/canvg/StackBlur.js"></script>
<script type="text/javascript" src="http://gabelerner.github.io/canvg/canvg.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.2.61/jspdf.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.5.0-alpha1/html2canvas.js"></script>
<script type='text/javascript'>
function replaceAllSVGsWithTempCanvas(elemSelector) {
var svgElements = $(elemSelector).find('svg');
//replace all svgs with a temp canvas
svgElements.each(function() {
var canvas, xml;
// canvg doesn't cope very well with em font sizes so find the calculated size in pixels and replace it in the element.
$.each($(this).find('[style*=em]'), function(index, el) {
$(this).css('font-size', getStyle(el, 'font-size'));
});
canvas = document.createElement("canvas");
canvas.className = "screenShotTempCanvas";
//convert SVG into a XML string
xml = (new XMLSerializer()).serializeToString(this);
// Removing the name space as IE throws an error
xml = xml.replace(/xmlns=\"http:\/\/www\.w3\.org\/2000\/svg\"/, '');
//draw the SVG onto a canvas
canvg(canvas, xml);
$(canvas).insertAfter(this);
//hide the SVG element
$(this).attr('class', 'tempHide');
$(this).hide();
});
}
jQuery(document).ready(function($) {
genChart();
});
function genPDF() {
var options = {
background: '#fff'
};
var pdf = new jsPDF('p', 'pt', 'a4');
replaceAllSVGsWithTempCanvas(".content");
pdf.addHTML($("#chartOuter"), options, function() {
pdf.output('dataurlnewwindow');
$(".content").find('.screenShotTempCanvas').remove();
$(".content").find('.tempHide').show().removeClass('tempHide');
});
}
function genChart() {
var chart = c3.generate({
data: {
columns: [
['data1', 30],
['data2', 120],
],
type: 'pie'
}
});
}
</script>
</head>
<body class="content">
<table width="100%">
<tr>
<td width="50%">
<div id="chartOuter">
<div id="chart"></div>
</div>
</td>
</tr>
<tr>
<td colspan="2" align="left">
<input type="button" onclick="genPDF();" value="Generate PDF" />
</td>
</tr>
</table>
</body>
</html>
EDIT 3:-
I tried just converting html to canvas using html2canvas. It is also giving the same issue.
Edit 4:
I could fix the duplicate issue now. But the charts and the text written to pdf are little bit blurry. Basically, I added function replaceAllSVGsWithTempCanvas and then use that while writing to pdf. But it seems this function does smething to the html that makes content written to pdf blurry. In fact pie charts etc, are no more circles but looks like oval shape.
Edited the question with modified js.

Looks like it is a bug in html2canvas. You should add the bottom code after html2canvas is loaded to fix that (Credits goes to this guy):
NodeParser.prototype.getChildren = function(parentContainer) {
return flatten([].filter.call(parentContainer.node.childNodes, renderableNode).map(function(node) {
var container = [node.nodeType === Node.TEXT_NODE && node.parentElement.tagName !== "text" ? new TextContainer(node, parentContainer) : new NodeContainer(node, parentContainer)].filter(nonIgnoredElement);
return node.nodeType === Node.ELEMENT_NODE && container.length && node.tagName !== "TEXTAREA" ? (container[0].isElementVisible() ? container.concat(this.getChildren(container[0])) : []) : container;
}, this));
};
Fiddle
Since html2canvas loads as a module, you should directly find NodeParser.prototype.getChildren in the source code and edit it to match above. That means you can't load it from CDN.

I think made it work correctly in two steps.
First, I commented out the "addhtml plugin" because I had this error in my console:
Refused to execute script from 'https://raw.githubusercontent.com/MrRio/jsPDF/master/plugins/addhtml.js' because its MIME type ('text/plain') is not executable, and strict MIME type checking is enabled.
Second, I changed the pdf source from #chartOuter to #chart.
pdf.addHTML($("#chart"), options, function () {
var string = pdf.output('datauristring');
$('.preview-pane').attr('src', string)
});
And there is no more dedoubling.
-----
EDIT (since I misunderstood the question at first)
It is needed to use the outer div... And maybe the full page.
Okay... To be honest, I don't know why this text issue happens.
But I noticed that the duplicate text has serif even if it is specified "sans-serif".
So I focused on this.
I tried to change the font-size... It affected the duplicate, but the text didn't follow the css rule. Okay.
Then I tried to just remove the text before the pdf creation part... And magic!
;)
$(".c3 svg").css({"font-size":"0px"});
Here is the complete script, I didn't touch the rest of your original code.
jQuery(document).ready(function ($) {
genChart();
});
function genPDF() {
var options = { background: '#fff'};
var pdf = new jsPDF('p', 'pt', 'a4');
$(".c3 svg").css({"font-size":"0px"}); // <-- This does the trick !
pdf.addHTML($("#chartOuter"), options, function () {
var string = pdf.output('datauristring');
$('.preview-pane').attr('src', string)
});
}
function genChart() {
var chart = c3.generate({
data: {
columns: [
['data1', 30],
['data2', 120],
],
type : 'pie'
}
});
}

You can try using ChartJS instead of C3.
I've adapted your code and tried it with success.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/c3/0.4.10/c3.min.css">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/c3/0.4.10/c3.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.3/Chart.min.js"></script>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
<!-- <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.2.61/jspdf.debug.js"></script> -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.2.61/jspdf.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.5.0-alpha1/html2canvas.js"></script>
<script type="text/javascript" src="https://raw.githubusercontent.com/MrRio/jsPDF/master/plugins/addhtml.js"></script>
<script type='text/javascript'>
jQuery(document).ready(function ($) {
genChart();
});
function genPDF() {
var options = { background: '#fff'};
var pdf = new jsPDF('p', 'pt', 'a4');
pdf.addHTML($("#chartOuter"), options, function () {
var string = pdf.output('datauristring');
$('.preview-pane').attr('src', string)
});
}
function genChart () {
var ctx = $("#chart");
var options = {};
var myPieChart = new Chart(ctx, {
type: 'pie',
data: {
labels: [
"data1",
"data2"
],
datasets: [{
data: [30, 120],
backgroundColor: [
"#FF6384",
"#36A2EB"
],
hoverBackgroundColor: [
"#FF6384",
"#36A2EB"
]
}]
},
options: options
});
}
</script>
</head>
<body>
<table width="100%">
<tr>
<td width="50%">
<div id="chartOuter">
<!-- <div id="chart"></div> -->
<canvas id="chart" width="400" height="400"></canvas>
</div>
</td>
<td>
<iframe height="550px" class="preview-pane" type="application/pdf" width="100%" frameborder="0" style="position:relative;z-index:999"></iframe>
</td>
</tr>
<tr>
<td colspan="2" align="left">
<input type="button" onclick="genPDF();" value="Generate PDF"/>
</td>
</tr>
</table>
</body>
</html>

Dynamically loading pdf blurry, the same file official demo is very clear. I can't locate the problem?
Use the chrome browser. Version 73.0.3683.86 (official version) (64-bit)
Here is my code:
async process(buffer, index) {
// Processing the decrypted data stream
let uint8Array = new Uint8Array(buffer);
var word = await this.Uint8ToBase64(uint8Array);
var decryptedData = CryptoJS.AES.decrypt(word, this.authorKey, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
});
// Then turn wordArray to uint8Array
let getUint8Array = await this.wordArrayToU8(decryptedData);
// decryption ends
this.loadingPdf(getUint8Array, index);
},
async loadingPdf(getUint8Array, index) {
// render canvas
let pdf = await pdfjsLib.getDocument({ data: getUint8Array, cMapUrl: cMapUrl, cMapPacked: cMapPacked });
let page = await pdf.getPage(1).then(page => {
return page;
});
let canvas = document.getElementById("the-canvas" + index);
const CSS_UNITS = 96.0 / 72.0;
const DEFAULT_SCALE = 1.7;
const UNKNOWN_SCALE = 0;
let viewport = page.getViewport( DEFAULT_SCALE * CSS_UNITS);
if (canvas.dataset.runed) return;
canvas.width = viewport.width*CSS_UNITS;
canvas.height = viewport.height*CSS_UNITS;
this.canvasW =
this.canvasW > (1000 / viewport.height) * viewport.width
? this.canvasW
: (1000 / viewport.height) * viewport.width;
canvas.style.width = (1000 / viewport.height) * viewport.width;
canvas.dataset.runed = true;
var context = canvas.getContext('2d');
// [Important] Turn off anti-aliasing
context.mozImageSmoothingEnabled = false;
context.webkitImageSmoothingEnabled = false;
context.msImageSmoothingEnabled = false;
context.imageSmoothingEnabled = false;
await page.render({
//enableWebGL: true,
// canvasContext: context,
transform: [CSS_UNITS, 0, 0, CSS_UNITS, 0, 0],
// transform: [1, 0, 0, 1, 0, 0],
canvasContext: canvas.getContext("2d"),
viewport: viewport
});
this.loadedPages.push(index)
},

Related

image processing by Opencvjs

I'm trying to convert an image using prewitt method using javascript. When I run it I get this error:
BindingError {name: 'BindingError', message: 'Cannot pass "array([[ 1, 1, 1],\n [ 0, 0, 0],\n [-1,-1,-1]])" as a Mat', stack: 'BindingError: Cannot pass "array([[ 1, 1, 1],\n …p://localhost:3000/static/js/1.chunk.js:103232:9)'}
Error at Filter2D
const prewitt=new cv.Mat()
const KERNEL_X=np.array([[1,1,1],[0,0,0],[-1,-1,-1]])
const KERNEL_Y=np.array([[-1,0,1],[-1,0,1],[-1,0,1]])
let img_prewittx=cv.filter2D(img,prewitt,-1,KERNEL_X)
let img_prewitty=cv.filter2D(img,prewitt,-1,KERNEL_Y)
cv.imshow(this.prewittRef.current,img_prewittx,img_prewitty)
Here is a good example for using cv.filter2D by OpenCV.js.
The type of the kernel argument should be cv.Mat() and not np.array (it's not Python where we can use np.array as OpenCV Mat).
The destination matrix is stored in the second argument of cv.filter2D (it is not returned as in Python).
It is recommended to apply the filter on Grayscale input (especially not on BGRA input, because the output alpha channel may be fully transparent).
Assume gray is the input image.
Apply cv.filter2D as follows:
const KERNEL_X = cv.matFromArray(3, 3, cv.CV_32FC1, [1,1,1, 0,0,0, -1,-1,-1]);
cv.filter2D(gray, img_prewittx, -1, KERNEL_X)
Complete code sample:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Hello OpenCV.js</title>
</head>
<body>
<p id="status">OpenCV.js is loading...</p>
<div>
<div class="inputoutput">
<img id="imageSrc" alt="No Image" />
<div class="caption">imageSrc <input type="file" id="fileInput" name="file" /></div>
</div>
<div class="inputoutput">
<canvas id="canvasOutput" ></canvas>
<div class="caption">canvasOutput</div>
</div>
</div>
<script async src="opencv.js" type="text/javascript"></script>
<script type="text/javascript">
let imgElement = document.getElementById('imageSrc');
let inputElement = document.getElementById('fileInput');
inputElement.addEventListener('change', (e) => {
imgElement.src = URL.createObjectURL(e.target.files[0]);
}, false);
//Read image and execute the OpenCV code sample.
imgElement.onload = function () {
let img = cv.imread(imgElement);
let gray = new cv.Mat()
let img_prewittx = new cv.Mat();
let img_prewitty = new cv.Mat();
if (img.channels() == 4)
{
cv.cvtColor(img, gray, cv.COLOR_BGRA2GRAY); //Convert from BGRA to Grayscale.
}
else if (img.channels() == 3)
{
cv.cvtColor(img, gray, cv.COLOR_BGR2GRAY); //Convert from BGR to Grayscale.
}
else
{
gray = img.clone();
}
//const prewitt = new cv.Mat()
//const KERNEL_X = np.array([[1,1,1],[0,0,0],[-1,-1,-1]])
//const KERNEL_Y = np.array([[-1,0,1],[-1,0,1],[-1,0,1]])
const KERNEL_X = cv.matFromArray(3, 3, cv.CV_32FC1, [1,1,1, 0,0,0, -1,-1,-1]);
const KERNEL_Y = cv.matFromArray(3, 3, cv.CV_32FC1, [-1,0,1, -1,0,1, -1,0,1]);
//https://answers.opencv.org/question/224848/how-do-i-create-and-use-a-custom-kernel-with-cvfilter2d/
cv.filter2D(gray, img_prewittx, -1, KERNEL_X)
cv.filter2D(gray, img_prewitty, -1, KERNEL_Y)
cv.imshow('canvasOutput', img_prewittx); //Show img_prewittx for testing
img.delete();
gray.delete();
img_prewittx.delete();
img_prewitty.delete();
};
//check openCV
var Module = {
// https://emscripten.org/docs/api_reference/module.html#Module.onRuntimeInitialized
onRuntimeInitialized() {
document.getElementById('status').innerHTML = 'OpenCV.js is ready.';
}
};
</script>
</body>
</html>

How to get the data attribute of the canvas chart created using chartjs

Hi all i am using ChartJs to create charts.i am setting some data attribute on the canvas.on clicking on the chart i need to get the data attribute assigned in the canvas.i have found a method in the documentation which i used to get the label and values of the region of the chart clicked,but i don't know how to get the data attributes.
<!DOCTYPE html>
<html>
<head>
<title> Pie Chart </title>
<style>
.pie-chart-canvas-wrapper{
box-sizing:border-box;
width:500px;
height:300px;
float:left;
}
</style>
</head>
<body>
<div id="pie-charts-whole-wrapper" >
<div class="pie-chart-canvas-wrapper">
<canvas data-region="RO1" data-role="sales" width="500px" height="300px" id="pie1" ></canvas>
</div>
</div> <!--/ Pie Charts whole Wrapper -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<script>
var ctx1 = document.getElementById("pie1");
var pieChart1 = new Chart(ctx1, {
type: 'pie',
data: {
labels: ["signed", "Not Signed"],
datasets: [
{
data: [20, 50],
backgroundColor:['#2ecc71','#34495e']
}
]
}
});
ctx1.onclick = function(evt) {
var activePoints = pieChart1.getElementsAtEvent(evt);
if (activePoints[0]) {
var chartData = activePoints[0]['_chart'].config.data;
var idx = activePoints[0]['_index'];
var label = chartData.labels[idx];
var value = chartData.datasets[0].data[idx];
console.log(label);
console.log(value);
}
};
</script>
</body>
</html>
If you want to get the attribute data-role, .getAttribute() is doing the job.
console.log(this.getAttribute("data-role"));
CodePen

Google chart doesnt load with javascript on Sharepoint

I am relatively new to google charts and was trying to run a basic chart for demo and further development.
Its a pretty basic script and was working well till yesterday and now it doesnt load anything.
I am loading this script in script editor webpart of Sharepoint and trying to load it. Not sure if its my case or just that Google Charts has a problem.
Pl help. Am I missing something conceptual here? Its a pretty basic code that I got from http://www.evoketechnologies.com/blog/visualizing-sharepoint-google-charts/ and modified it a bit for my use.
I have run window.alert and it is extracting all values in the enumerator correctly. I think then something happens and the chart doesnt load.
javascript alerts also pop up after the barChart.draw(data, options), and lineChart.draw(data, options) code part, so the code has execute fully.
Thank you
Niraj
*<html>
<head>
<script src="https://www.gstatic.com/charts/loader.js" type="text/javascript"></script>
<script src="https://code.jquery.com/jquery-3.0.0.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.SPServices/2014.02/jquery.SPServices.min.js" type="text/javascript"></script>
<script language="javascript">
var returnedItems = null;
function loadGoogleLibAndDraw(){
google.charts.load('current', {'packages':['bar','line']});
google.charts.setOnLoadCallback(visualizeData);
}
function visualizeData() {
var context = new SP.ClientContext();
var list = context.get_web().get_lists().getByTitle(document.getElementById('customListName').value);
var caml = new SP.CamlQuery();
caml.set_viewXml("<View></View>");
returnedItems = list.getItems(caml);
context.load(returnedItems);
context.executeQueryAsync(onSucceededCallback, onFailedCallback);
}
function onSucceededCallback(sender, args) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Part No');
data.addColumn('number', 'Volume');
var enumerator = returnedItems.getEnumerator();
var markup = '';
while (enumerator.moveNext()) {
var row = [];
var listItem = enumerator.get_current();
row.push(listItem.get_item('Part_x0020_No'));
row.push(listItem.get_item('Volume'));
data.addRow(row);
}
var options = {
chart: {
title: 'KPIs',
},
bars: 'vertical'
};
var barChart = new google.charts.Bar(document.getElementById('BarChart'));
barChart.draw(data, options);
var lineChart = new google.charts.Line(document.getElementById('LineChart'));
lineChart.draw(data, options);
}
function onFailedCallback(sender, args) {
var markup = '<p>The request failed: <br>';
markup += 'Message: ' + args.get_message() + '<br>';
displayDiv.innerHTML = markup;
}
</script>
</head>
<body onload="loadGoogleLibAndDraw()">
<form name="metricsform" id="metricsform">
<input id="customListName" name="customListName" value="Projects" type="hidden"/>
</form>
<div>
<div id="displayDiv"></div>
<div id="BarChart" style="width: 300px; height: 200px;"></div>
<div id="LineChart" style="width: 300px; height: 200px;"></div>
</div>
</body>
</html>*
recommend not using inline tag events --> <body onload="...
especially if there are multiple editor web parts / <body> tags
also, it isn't necessary since the loader...
will wait for the document to finish loading before calling the callback
to be absolute sure, place all <script> tags at the bottom, just before the </body> end tag
recommend following setup...
<html>
<body>
<form name="metricsform" id="metricsform">
<input id="customListName" name="customListName" value="Projects" type="hidden"/>
</form>
<div>
<div id="displayDiv"></div>
<div id="BarChart" style="width: 300px; height: 200px;"></div>
<div id="LineChart" style="width: 300px; height: 200px;"></div>
</div>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<script src="https://code.jquery.com/jquery-3.0.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.SPServices/2014.02/jquery.SPServices.min.js"></script>
<script>
var returnedItems = null;
function visualizeData() {
var context = new SP.ClientContext();
var list = context.get_web().get_lists().getByTitle(document.getElementById('customListName').value);
var caml = new SP.CamlQuery();
caml.set_viewXml("<View></View>");
returnedItems = list.getItems(caml);
context.load(returnedItems);
context.executeQueryAsync(onSucceededCallback, onFailedCallback);
}
function onSucceededCallback(sender, args) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Part No');
data.addColumn('number', 'Volume');
var enumerator = returnedItems.getEnumerator();
var markup = '';
while (enumerator.moveNext()) {
var row = [];
var listItem = enumerator.get_current();
row.push(listItem.get_item('Part_x0020_No'));
row.push(listItem.get_item('Volume'));
data.addRow(row);
}
var options = {
chart: {
title: 'KPIs',
},
bars: 'vertical'
};
var barChart = new google.charts.Bar(document.getElementById('BarChart'));
barChart.draw(data, options);
var lineChart = new google.charts.Line(document.getElementById('LineChart'));
lineChart.draw(data, options);
}
function onFailedCallback(sender, args) {
var markup = '<p>The request failed: <br>';
markup += 'Message: ' + args.get_message() + '<br>';
displayDiv.innerHTML = markup;
}
google.charts.load('current', {
callback: visualizeData,
packages: ['bar', 'line']
});
</script>
</body>
</html>

How to make label always visible on DoughnutChart.js

I have already gone through this link
Chart.js - Doughnut show tooltips always?
I have implemented the code in the same way on my machine but the chart is not appearing.
The following is my code:
HTML:
<!doctype html>
<html>
<head>
<title>Doughnut Chart</title>
<script src="Chart.js"></script>
</head>
<body>
<div>
<canvas id="chart" width="200" height="200"/>
</div>
</body>
JS:
var data = [
{
value: 300,
color:"#F7464A",
highlight: "#FF5A5E"
},
{
value: 50,
color: "#46BFBD",
highlight: "#5AD3D1"
},
{
value: 100,
color: "#FDB45C",
highlight: "#FFC870"
}
]
var options =
{
tooltipTemplate: "<%= value %>",
onAnimationComplete: function()
{
this.showTooltip(this.segments, true);
},
tooltipEvents: [],
showTooltips: true
}
var context = $('#chart').get(0).getContext('2d');
var chart = new Chart(context).Pie(data, options);
Please can anybody help me out with this trouble?
Or you could forget about jquery leave the <head></head as was in the code you posted and substitute
var context = $('#chart').get(0).getContext('2d');
with
var context = document.getElementById("chart").getContext("2d");
You just have to include this line in your html file to include jquery
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
In the code above seems to miss the ref to jquery between <head></head> tags

Trouble parsing XML into JSON - Javascript

I am trying to parse some XML data into JSON using Javascript/Jquery for use in a Highcharts project. Unfortunately, I can't figure out what is wrong with my code as it will not even read the XML. So far I have:
xml:
<Row>
<Category>data</Category>
<actual>data</actual>
</row>
....
HTML:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>Document</title>
</head>
<body>
<h1>Hello</h1>
<div id="container" style="height: 400px; width: 500px"></div>
<script type = "text/javascript" src = "jquery-1.11.1.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script type = "text/javascript" src = "test.js"></script>
</body>
</html>
Javascript:
$(document).ready(function(){
var globalData = new Array();
// $("h1").click(function(){
// Load the data from the XML file
$.get('C:\\Users\\xxxxxx\\Desktop\\xmloutput.xml', function(xml) {
alert("it works");
// Split the lines
var $xml = $(xml);
// push series
$xml.find('Row').each(function(i, row) {
var seriesOptions = {
Category: $(series).find('Category').text(),
Actual: $(series).find('Actual').text(),
};
// add it to the options
globalData.push(seriesOptions);
});
});
// });
$(function() {
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'pie'
},
plotOptions: {
pie: {
borderColor: '#000000',
innerSize: '60%'
}
},
series: [{
data: globalData
}]
},
// using
function(chart) { // on complete
var xpos = '50%';
var ypos = '53%';
var circleradius = 102;
// Render the circle
chart.renderer.circle(xpos, ypos, circleradius).attr({
fill: '#ddd',
}).add();
// Render the text
chart.renderer.text('THIS TEXT <span style="color: red">should be in the center of the donut</span>', 155, 215).css({
width: circleradius*2,
color: '#4572A7',
fontSize: '16px',
textAlign: 'center'
}).attr({
// why doesn't zIndex get the text in front of the chart?
zIndex: 999
}).add();
});
});
});
I believe my actual problem may be that my xml-parsing syntax is incorrect but running this on the development console in Firefox reveals no errors. Hopefully the experts here can spot the issue(s)
Thanks for your time.
One imediate problem that I can see is using local path
$.get('C:\\Users\\xxxxxx\\Desktop\\xmloutput.xml',
$.get first parameter is url that is location on network it could be something like $.get('http://localhost/xmls/xmloutput.xml,...

Categories