How to export the JavaScript Charts in PDF format by using base64 string?
Description
This article explains how to export the JavaScript Charts in PDF format by using base64 string.
Solution
The chart is an SVG-based component, so you can draw an SVG element in an HTML canvas element. This canvas element is then transformed into an image using the HTML image element. The resulting image is converted to a PNG or JPEG format and then converted into a base64 string.
The base64 string is then converted into a bitmap image, then a PDF document is opened. You can set the page orientation for the opened document. Then, add the page containing the chart image to the document. Finally, the document is saved, destroyed, and the canvas element is removed from the DOM.
Code Snippet
The following shows how to export the Chart in PDF format using the base64 string
document.getElementById('togglebtn').onclick = function () {
var svg = document.querySelector("#container_svg");
var svgData = new XMLSerializer().serializeToString(svg);
var canvas = document.createElement("canvas");
document.body.appendChild(canvas);
var svgSize = svg.getBoundingClientRect();
canvas.width = svgSize.width;
canvas.height = svgSize.height;
var ctx = canvas.getContext("2d");
var img = document.createElement("img");
img.setAttribute("src", "data:image/svg+xml;base64," + btoa(svgData));
img.onload = function () {
ctx.drawImage(img, 0, 0);
var imagedata = canvas.toDataURL("image/jpeg");
// PDF code
imagedata = imagedata.replace("data:image/jpeg;base64,", '');
var image = new ejs.pdfexport.PdfBitmap(imagedata);
var document = new ejs.pdfexport.PdfDocument();
document.pageSettings.orientation = ejs.pdfexport.PdfPageOrientation.Landscape;
//Add a page.
var page1 = document.pages.add();
page1.graphics.drawImage(image, 0, 0);
//Save the document.
document.save("Chart.pdf");
document.destroy();
canvas.remove();
};
};
The following image illustrates the output of the above code:
Refer to the working sample for additional details and implementation: View Sample in Stackblitz
Conclusion
We hope you enjoyed learning how to export the JavaScript Charts in PDF format by using base64 string.
You can refer to our JavaScript Charts feature tour page to learn about its other features and documentation, and how to quickly get started for configuration specifications. You can also explore our JavaScript Charts example to understand how to create and visualize data.
For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls.
If you have any queries or require clarifications, please let us know in the comment section below. You can also contact us through our support forums, support portal, BoldDesk Support, or feedback portal. We are always happy to assist you!