html 2 pdf use html2canvas and jspdf
(function () {
'use strict';
function PDFService(jsPDF, html2canvas, $document, $window) {
var docu = $document[0];
/**
* Takes image url and convert into base64 string
* @param url Image URL
* @param callback function
*/
function convertImgToDataURL(url, callback) {
var img = new Image();
img.crossOrigin = 'Anonymous'; //solve CORS issue
img.onload = function () {
var canvas = docu.createElement('canvas');
var ctx = canvas.getContext('2d');
var dataURL;
canvas.height = this.height;
canvas.width = this.width;
ctx.drawImage(this, 0, 0);
dataURL = canvas.toDataURL('image/png', 1.0);
callback(dataURL);
canvas = null;
};
img.onerror = function () {
callback(false);
};
img.src = url;
}
/**
* Take a html element, convert into image, add into pdf doc, output a pdf file
* @param div Html element context
*/
function exportToPDF(div) {
/**
*@source https://html2canvas.hertzen.com/documentation.html
*/
html2canvas(div, {
useCORS: true, //try to load images from other domains as well
logging: false, //enable it if u want see log messages in console
onrendered: function (canvas) {
var imgData = canvas.toDataURL('image/jpeg', 1.0);
//window.open(imgData); //use this for testing only
var pdf = new jsPDF('l', 'mm');
pdf.setProperties({
title: 'Custom Rug Design',
author: 'surya.com'
});
//don't use name alias name again
var alias = Math.random().toString(35);
pdf.addImage(imgData, 'JPEG', 10, 30, void 0, void 0, alias, true);
pdf.setFontSize(14);
pdf.text(10, 10, 'Exported from Surya.com -' + new Date().toDateString());
pdf.save('dyo-export-' + +new Date() + '.pdf');
}
});
}
return {
//todo try to use $q style promise
save: function (callback) {
var div = docu.querySelector('#sr-canvas'), // container id which u want to include in pdf
img = docu.querySelector('#sr-preview');//image id that will be convert into base64
convertImgToDataURL(img.src, function (result) {
if (result) {
$window.scrollTo(0, 150);
img.src = result;
exportToPDF(div);
callback(true);
} else {
callback(false);
}
});
}
};
}
angular.module('rugApp').factory('PDFService', PDFService);
})();