I am using a dom-to-image library for converting an HTML table to an SVG image and displaying that image in the pdf file using MPDF library later on.
HTML This table is an example
<table id="tableId">
<tr>
<td> 1row1column </td>
<td> 1row2column </td>
</tr>
<tr>
<td> 2row1column </td>
<td> 2row2column </td>
</tr>
</table>
Javascript Here I am using the dom-to-image library's toSvg function to convert the dom to SVG formatted image, sending the data URL to server-side with ajax:
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/dom-to-image/2.6.0/dom-to-image.min.js"></script>
var node = document.getElementById('tableId');
function filter (node) {
return (node.tagName !== 'i');
}
domtoimage.toSvg(node).then(dataUrl => {
domtoimage.toSvg(node, {
quality: 1.0,
bgcolor: "white",
filter: filter /* , width: "900px", */
}).then(
dataUrl2 => {
// var link = document.createElement('a');
// link.download = 'actual.svg';
// link.href = dataUrl2;
// link.click();
$.ajax(
'download.php',
{
data: {
image: dataUrl2,
imageName:"textContainer.svg"
},
type: "POST",
success: function (data) {
console.log(data.message);
},
error: function () {
console.log(data.message);
// alert('There was some error performing the AJAX call!');
},
beforeSend: function () {
// alert('There was some error performing the AJAX call!');
},
}
);
}
)
}).catch(function (error) {
console.error('oops, something went wrong!', error);
});
PHP
I am getting the data URL($data
) and the imageName($imageName
) from $_POST
global variable, removing everything before the <svg>
tag and removing the %0A
string which I had a problem with it in the beginning, putting the content to SVG file:
$data = $_POST['image'];
$imageName = $_POST['imageName'];
$svgData = str_replace('data:image/svg+xml;charset=utf-8,', '', $data);
$svgData = str_replace('%0A', '', $svgData);
file_put_contents("/tables/" . $imageName, $svgData);
The file is being downloaded and the SVG file is being displayed in Opera, Firefox, Microsoft Edge without any problem, but when it comes to adding this SVG file to pdf or to any other vector graphics editor like Inkscape the SVG image not working.
The question: Can be done without using any library? and If there is a library for doing this in the correct way, can we make the SVG works in pdf files too?