How to convert and download chart to pdf? - javascript

I m using jsPdf plugin and did this
var data = google.visualization.arrayToDataTable(dataValues,true);
var chart = new google.visualization.CandlestickChart(document.getElementById(id));
google.visualization.events.addListener(chart, 'ready', function () {
var content = '<img src="' + chart.getImageURI() + '">';
$('#graph-images').append(content);
});
function generatePDF() {
var imageTags = $('#graph-images img');
var doc = new jsPDF();
doc.setFontSize(33);
doc.setFillColor(135, 124,45,0);
doc.addImage(imageTags[0], 'png', 10, 10, 150, 100);
doc.save('sample.pdf');
}
by using this i am able to download the pdf file while open that pdf file in adobe reader its saying 110 error.
Can Anybody Help in this, thanks.

You should pass image URI to addImage():
google.charts.setOnLoadCallback(function() {
var data = google.visualization.arrayToDataTable(dataValues, true)
var chart = new google.visualization.CandlestickChart(document.getElementById(id))
chart.draw(data)
imgData = chart.getImageURI()
})
function generatePDF() {
var doc = new jsPDF();
doc.setFontSize(33);
doc.setFillColor(135, 124,45,0);
doc.addImage(imgData, 'png', 10, 10, 150, 100);
doc.save('sample.pdf');
}
Please check this live demo for more details https://jsfiddle.net/p1frmxvp/1/
UPDATE
Turns out the error happens only when we use jspdf 1.3.2 and open the pdf using Adobe Reader as explained here. The only solution so far is either opening the pdf using other viewer (Chrome, Foxit Reader .etc) or downgrading jspdf to 1.2.61. I have updated the jsfiddle above to use the downgraded jspdf.

Related

HTML to PDF in JS using a variable

This is my first post because I am stuck and I didn't find the solution neither here or the web.
I want to convert HTML to PDF using JS. I was searching and the best option seems to be HTML2canvas and JSpdf. But the think is my HTML is storage in a variable:
var test = '<html><head><script type="text/javscript">var number = 123;</script></head><body>
<h1>"the value for number is: " + number</h1></body></html>'
My variable is much more complex and it contains CSS and styles but this is just to get the idea. Then when I try to convert this into canvas it doesn't convert.
const filename = 'ThisIsYourPDFFilename.pdf';
html2canvas(test).then(canvas => {
let pdf = new jsPDF('p', 'mm', 'a4');
pdf.addImage(canvas.toDataURL('image/png'), 'PNG', 0, 0, 211, 298);
pdf.save(filename);
});
Does anyone know why this happens? Maybe it is a really stupid question but I don't know how to avoid the errors.
Thank you in advance.
You use string as a parameter for html2canvas, but it takes HTML element:
html2canvas(document.body).then(function(canvas) {
document.body.appendChild(canvas);
});
Look at their documentation
I have modified your code:
const html2canvas = require("html2canvas");
const jsPDF = require("jspdf");
html2canvas(document.getElementById("screenshot"), { scale: 1 }).then(
(canvas) => {
document.body.appendChild(canvas);
const filename = "ThisIsYourPDFFilename.pdf";
let pdf = new jsPDF("p", "mm", "a4");
pdf.addImage(canvas.toDataURL("image/png"), "PNG", 0, 0);
pdf.save(filename);
document.body.removeChild(canvas);
}
);
body should contain element with id screenshot:
<div id="screenshot">
Content
</div>
UPDATE:
According to this resource jsPDF has method fromHTML, so you might not need html2canvas
var doc = new jsPDF();
var elementHTML = $('#contnet').html();
var specialElementHandlers = {
'#elementH': function (element, renderer) {
return true;
}
};
// note here that it uses html
doc.fromHTML(elementHTML, 15, 15, {
'width': 170,
'elementHandlers': specialElementHandlers
});
// Save the PDF
doc.save('sample-document.pdf');

html2canvas/jsPDF - images not showing when converting html to a pdf

I'm looking to convert some simple HTML into a PDF. It seems the easiest way to do this and keep the css styling is to use the 'html2canvas' js library to convert the html to canvas first, and then create the PDF using jsPDF.
The issue I'm getting is that I have both a background image and inline image in my HTML but neither are showing in the PDF once converted. I've created a Codepen here: https://codepen.io/adamboother/pen/NWGeqom
Here's my js that does the conversion:
function convertToPdf()
{
html2canvas(document.querySelector('#certificate')).then(canvas => {
let pdf = new jsPDF('landscape', 'mm', 'a4');
pdf.addImage(canvas.toDataURL('image/png'), 'PNG', 0, 0, pdf.internal.pageSize.width, pdf.internal.pageSize.height);
pdf.save('certificate.pdf');
});
}
Has anyone found a fix for this?
I am using useCORS: true to your code and it works, assuming your image is in the server. Besides you can follow below code:
function convertToPdf()
{
html2canvas(document.querySelector('#certificate'), {useCORS: true}).then(function(canvas) {
let img = new Image();
img.src = canvas.toDataURL('image/png');
img.onload = function () {
let pdf = new jsPDF('landscape', 'mm', 'a4');
pdf.addImage(img, 0, 0, pdf.internal.pageSize.width, pdf.internal.pageSize.height);
pdf.save('certificate.pdf');
};
});
}

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);
}
});
}

html2canvas and React to generate pdf doesn't work

I'm using html2canvas and jsPdf to generate Pdf from HTML for one react application.
onClick of my download button I call this function :
printDocument() {
const input = document.getElementById('divToOfferInfo');
const pdf = new jsPDF();
if (pdf) {
html2canvas(input, {
useCORS: true
})
.then(canvas => {
const imgData = canvas.toDataURL('image/png');
console.log(imgData); //Maybe blank, maybe full image, maybe half of image
pdf.addImage(imgData, 'PNG', 10, 10);
pdf.save('download.pdf');
});
}
}
The result is totally random. The result of canvas is full, half or blank but not right.
I think that issue is about rendering of React.
Thank you for your help.
I found an alternative solution. Instead to use html2canvas lib, we can use dom-to-image lib. It's working with it.
import domtoimage from 'dom-to-image';
...
printDocument() {
const input = document.getElementById('divToOfferInfo');
const pdf = new jsPDF();
if (pdf) {
domtoimage.toPng(input)
.then(imgData => {
pdf.addImage(imgData, 'PNG', 10, 10);
pdf.save('download.pdf');
});
}
}
You can use like this. I am using this code and it is working well.
savePDF() {
const printArea = document.getElementById("printWrapper");
html2canvas(printArea).then(canvas => {
const dataURL = canvas.toDataURL();
const pdf = new jsPDF();
pdf.addImage(dataURL, 'JPEG', 20, 20, 180, 160);
pdf.save('saved.pdf')
})
}

htmlCode to PDF (Save) only javascript

I am concerned for a few days... How save PDF for HTMLCode.
I find jsPDF!!
but I do not want to it because I was unable to use the CSS I want...T.T
so I think HTMLCode convert canvasImage(html2canvas and rasterizeHTML useing)
after canvasImage convert PDF!!
WOW starting is fantastic!! After a few moments later come trial it is CORS
HTML5 Canvas not suppot CORS image.
I want to use canvas render CORS image
help me please!!
example
html2canvas($("body")[0], {
onrendered: function(canvas) {
var img = canvas.toDataURL("image/png");
var pdf = new jsPDF();
//window.open(img);
pdf.addImage(img, 'png', 10, 10, 180, 160);
pdf.save('test.pdf');
}
});

Categories