Is it possible to store the document created from jspdf in the HTML5 webstorage? I want to save it so I can keep adding stuff from other pages until the user presses the download button. The code below gives me no errors but the document always consists only of the last page.
let doc = new jsPDF('p', 'mm', 'a4');
const width = doc.internal.pageSize.getWidth();
const height = doc.internal.pageSize.getHeight();
window.sessionStorage.setItem('pdf', doc);
document.getElementById('report').onclick = function () {
doc = window.sessionStorage.getItem('pdf');
console.log(doc);
html2canvas(document.getElementById('dataTable'), {
onrendered: function (canvas) {
var table = canvas.toDataURL("image/png");
doc.addImage(table, 'JPEG', 0, 0, width, height);
window.sessionStorage.setItem('pdf', doc);
}
});
}
document.getElementById('download').onclick = function () {
doc = window.sessionStorage.getItem('pdf');
doc.save('test.pdf');
}
Is it even possible to store the document in the store or do I maybe have to convert it to a string?
Here is how I solved it if anyone is interested. I save all generated pictures from html2canvas in the local storage as dataURL. When I want to create my pdf I retrieve them and add them all to the page. This is fine since I never reach the limit of the local storage.
Storage.prototype.setObject = function (key, value) {
this.setItem(key, JSON.stringify(value));
}
Storage.prototype.getObject = function (key) {
var value = this.getItem(key);
return value && JSON.parse(value);
}
/*
* Save all pictures in local storage
*/
document.getElementById('report').onclick = function () {
html2canvas(document.body, {
onrendered: function (canvas) {
const image = canvas.toDataURL("image/png");
window.sessionStorage.setObject(new Date().getTime(), image);
}
});
}
document.getElementById('download').onclick = function () {
// Create new document
let doc = new jsPDF('p', 'mm', 'a4');
const width = doc.internal.pageSize.getWidth();
const height = doc.internal.pageSize.getHeight();
// Get all images from local storage and add them to the pdf
for (let key in sessionStorage) {
if (!isNaN(key)) {
const image = window.sessionStorage.getObject(key);
doc.addImage(image, 'JPEG', 0, 0, width, height);
}
}
// And download it
doc.save('test.pdf');
}