I'm writing my first blog, hope this is informative.
Ever wondered how to save/download vizframe charts to PDF. Many times I have seen this question in UI5 forums and sometimes I used to reply like 'save chart as SVG using builtin method' and generate PDF.
Finally I got the same requirement from the client, and I tried to save chart as SVG. Now I have the SVG content ...from here on how to proceed. There were no concrete steps to create PDF from SAP UI5 charts. So I decided to dig further and found a solution(not sure if its the best one)
Steps to create PDF:
We need to use third party library
jsPDF to create PDF on the client side. There is an example on the first page which shows image in the PDF (this is exactly what we needed). Unfortunately
jsPDF library doesn't support for SVG content(AFAIK).
So the challenge is to convert UI5 Chart SVG content to Image(JPEG/PNG) on the client side and use the library
jsPDF.
For this solution we need to use below third party libraries:
- jsPDF - Used to generate client side PDF
- canvg - For placing SVG content on the canvas
- rgbcolor - required for canvg library
- StackBlur.js - required for canvg library
Lets assume that we have the below stacked bar chart with id as '
idVizFrame'
Convert chart content to SVG using UI5 method
exportToSVGString()
Use the below code:
var oVizframe = this.getView().byId("idVizFrame"); // access chart UI element
var sSVG = oVizFrame.exportToSVGString({ // UI5 predefined method
width: 800,
height: 600
});
Steps for converting SVG to PNG/JPEG on client side:
- Create a canvas HTML element
- Place SVG content into canvas element
- Create dataURI for canvas element in required format
Below is the code:
var oCanvasHTML = document.createElement("canvas"); // Create canvas element
canvg(oCanvasHTML, sSVG); // use library canvg to place SVG content on the canvas
var sImageData = oCanvasHTML.toDataURL("image/png"); // Get data URI in PNG or JPEG
Now we have SVG content in PNG format. Use
jsPDF library to create PDF and place the image.
// Create PDF using library jsPDF
var oPDF = new jsPDF()
oPDF.addImage(sImageData, 'PNG', 15, 40, 180, 160)
oPDF.save("test.pdf"); // PDF file name
You can refer the
sample code here.
Github repository
UI5 Sample code output:
PDF output:
Update:
Error:
If you see this error when executing the code, it is caused by UI5 library when genearting the SVG string for chart legend using method [exportToSVGString()]
One of the generated SVG attribute value has space, that is causing the issue
<g class="v-legend-element v-legend-item" transform="translate (-5,0)">
<!--attribute value "translate (-5,0)" should not contain spaces -->
This issue is fixed in App.controller.js where the space is removed.