JSFiddle - React, Tailwind, and code Playground
by mamounothman
HTML
<!DOCTYPE html>
<meta charset="utf-8">
<head>
</head>
<body>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/js/pdfkit.standalone.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/source.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js"></script>
<button id="download">Donwload SVG as PDF</button>
</body>
CSS
.axis {
font: 10px sans-serif;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
JavaScript
const svgToPdfExample = (svg) => {
const doc = new window.PDFDocument();
const chunks = [];
const stream = doc.pipe({
// writable stream implementation
write: (chunk) => chunks.push(chunk),
end: () => {
const pdfBlob = new Blob(chunks, {
type: 'application/octet-stream'
});
var blobUrl = URL.createObjectURL(pdfBlob);
window.open(blobUrl);
},
// readable streaaam stub iplementation
on: (event, action) => {},
once: (...args) => {},
emit: (...args) => {},
});
window.SVGtoPDF(doc, svg, 0, 0);
doc.end();
};
document.getElementById('download').addEventListener('click', function() {
const svgElement = document.getElementById('svg');
svgToPdfExample(svgElement.innerHTML);
})
var margin = {top: 20, right: 20, bottom: 70, left: 40},
width = 900 - margin.left - margin.right,
height = 300 - margin.top - margin.bottom;
// Parse the date / time
var parseDate = d3.time.format("%Y-%m").parse;
var x = d3.scale.ordinal().rangeRoundBands([0, width], .05);
var y = d3.scale.linear().range([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.tickFormat(d3.time.format("%Y-%m"));
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.ticks(10);
var svg = d3.select("body").append("svg")
.attr('id', 'svg')
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform",
"translate(" + margin.left + "," + margin.top + ")");
d3.csv("https://gist.githubusercontent.com/d3noob/8952219/raw/5017886e4fe22af2a7e06e20cf381bcf09cdc6db/bar-data.csv", function(error, data) {
data.forEach(function(d) {
d.date = parseDate(d.date);
d.value = +d.value;
});
x.domain(data.map(function(d) { return d.date; }));
y.domain([0, d3.max(data, function(d) { return d.value; })]);
svg.append("g")
.attr("class", "x axis")
...