HTML2Canvas DOM (Angular) - javascript

I'm new to JS and development in general, but I was hoping I could get a little help resolving an issue I've been trying to figure out for a couple of days.
Basically, I'm trying to get HTML2Canvas to play with Angular. I have a div (ID is 'invoice') inside one of my partial HTML files, and I have the following in my controller:
sampleApp.controller('InvoiceController', function($scope) {
$(document).ready(function(){
var source = document.getElementById('invoice');
$( '.submit' ).click(function() {
html2canvas(source, {
logging: 'on',
allowTaint: 'true',
onrendered: function(canvas) {
var myImage = canvas.toDataURL("image/jpeg");
window.open(myImage);
}
});
});
});
I'm completely at a loss as to why this doesn't work. The script runs without any errors, but it just kicks out a blank page without an image on it. It looks like it's something with the DOM because this is what I'm getting in the console:
html2canvas: Preload starts: finding background-images html2canvas.js:21
html2canvas: Preload: Finding images html2canvas.js:21
html2canvas: Preload: Done. html2canvas.js:21
html2canvas: start: images: 0 / 0 (failed: 0) html2canvas.js:21
Finished loading images: # 0 (failed: 0) html2canvas.js:21
html2canvas: Renderer: Canvas renderer done - returning canvas obj
EDIT: Thought I'd add that another reason I know it's something with how the DOM loads in Angular is because using document.body as the var works. I'm just looking to make an image out of a single div, however.

Following is the exact directive i am using in my project, and it works for svg as well thus rendering the charts too:
(function () {
'use strict';
angular
.module('myModule')
.directive('camera', camera);
camera.$inject = ['$rootScope'];
/* #ngInject */
function camera($rootScope) {
var directive = {
link: link,
restrict: 'A'
};
return directive;
function link(scope, element, attrs) {
$rootScope.$on('capture', function (event, deferred) {
event.stopPropagation();
renderSvg(element);
//method to render the SVG's using canvg
function renderSvg(element) {
// First render all SVGs to canvases
var elements = element.find('svg').map(function () {
var svg = $(this);
var canvas = $('<canvas></canvas>');
svg.replaceWith(canvas);
// Get the raw SVG string and curate it
var content = svg.wrap('<p></p>').parent().html();
content = content.replace(/xlink:title="hide\/show"/g, "");
content = encodeURIComponent(content);
svg.unwrap();
// Create an image from the svg
var image = new Image();
image.src = 'data:image/svg+xml,' + content;
image.onload = function () {
canvas[0].width = image.width;
canvas[0].height = image.height;
// Render the image to the canvas
var context = canvas[0].getContext('2d');
context.drawImage(image, 0, 0);
};
return {
svg: svg,
canvas: canvas
};
});
// At this point the container has no SVG, it only has HTML and Canvases.
html2canvas(element[0], {
useCORS: true,
allowTaint: true,
onrendered: function (canvas) {
// Put the SVGs back in place
elements.each(function () {
this.canvas.replaceWith(this.svg);
});
var dataURL = null;
try {
dataURL = canvas.toDataURL("image/png", 0.9);
deferred.resolve(dataURL);
}
catch (e) {
deferred.reject(e);
}
}
});
}
});
}
}
})();
Reference the above directive and use the following code in your controller to invoke the functionality in the directive:
var deferred = $q.defer();
$scope.$emit('capture', deferred);
deferred.promise.then(function (screenshot) {
//do something with screenshot (Base64Url for .png type)
});

Related

rotate is not defined cropper.js

I am using the awesome jquery-cropper plugin from fengyuanchen.
I'm having the issue of when certain images get uploaded it rotates and it is not on the right side which I have to make the user rotate them. I will upload the image via ajax. I'm getting the error rotate is not defined which I have been stuck a couple of hours.
$('#profilePhoto').on( 'change', function(){
if (this.files && this.files[0]) {
if ( this.files[0].type.match(/^image\//) ) {
var reader = new FileReader();
reader.onload = function(evt) {
var img = new Image();
img.onload = function() {
$("#profileImageContainer").hide();
$("#rotateImg").show();
context.canvas.height = img.height;
context.canvas.width = img.width;
context.drawImage(img, 0, 0);
cropper = canvas.cropper({
aspectRatio: 1 / 1,
rotatable: true,
});
$('#btnCrop').click(function() {
// Get a string base 64 data url
var croppedImageDataURL = canvas.cropper('getCroppedCanvas').toDataURL("image/png");
});
$('#rotateImg').click(function () {
cropper.cropper.rotate(90);
});
};
img.src = evt.target.result;
};
reader.readAsDataURL(this.files[0]);
}
else {
alert("Invalid file type! Please select an image file.");
}
}
else {
alert('No file(s) selected.');
}
});
The main problem here is about scopes since it looks like it is not reconizing the cropper variable.
This problems surfaces because when the user upload a photo sometimes this photo rotate automatically. If I could solve this problem first without having to make the user rotate the image would be better
Really stupid mistake. Instead of:
cropper.cropper().rotate(90);
I should apply:
cropper.cropper('rotate', 90);

PDF.js document is presented upside down randomly

I'm using PDF.js addon to show pdfs in my polymerjs app. From time to time pdf content is rendered upside down. Here is how I'm using PDF.js:
downloadPdf: function(item) {
var pdfJsInitParams = {
url: app.baseURL + item.report_pdf,
httpHeaders: app.user.token
};
PDFJS.getDocument(pdfJsInitParams).promise.then(function(pdf) {
function renderPage(pageNumber, eltId) {
if(pdf.numPages < pageNumber) {
return;
}
pdf.getPage(pageNumber).then(function(page) {
var scale = 1.3;
var viewport = page.getViewport(scale);
// Prepare canvas using PDF page dimensions
var canvas = document.getElementById(eltId);
if(canvas) {
var context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;
// Render PDF page into canvas context
var renderContext = {
canvasContext: context,
viewport: viewport
};
page.render(renderContext);
}
}).catch(function(err) {
showToastWithText(err, 'error');
});
}
renderPage(1, 'report_1');
renderPage(2, 'report_2');
});
}
Any ideas what may causing this issue?
(Looks like downloadPdf is called multiple times in short period of time)
The render() operation is asynchronous and you need to wait for its completion before you start a new rendering on the same canvas, see https://github.com/mozilla/pdf.js/blob/master/examples/learning/prevnext.html example. If you don't want to wait, create a new canvas.

Double title of chart in html2canvas

Html2canvas is really cool but:
The function is "simple":
$scope.generateScreenshot = function () {
html2canvas($("#screen-shot"), {
onrendered: function(canvas) {
// canvas is the final rendered <canvas> element
var myImage = canvas.toDataURL("image/png");
window.open(myImage);
}
});
}
Any ideas why there is an issue with rendering title ?

How do you concatenate two or images in pdf using Html2Canvas & JsPDF?

I am trying to wrap my head around HTML2Canvas' API but the documentation is extremely limited. The situation is that I am putting 2 or more div's (thier content) into a single PDF where each div represents a different page. Sounds easy right ? Not really. I have tried everything to make this work, but the asynchournous nature of JS is making this way harder than it has to be.
Here is what I have
html2canvas($("#monthly_agg_report_container"), {
onrendered: function(canvas)
{
var doc = new jsPDF('landscape', 'pt','a2');
var imgData = canvas.toDataURL("image/png");
doc.addImage(imgData,'PNG',0,0,canvas.width*1.33,canvas.height*1.33);
doc.save('report.pdf') ;
}
}).then(function(){
//another html2canvas doesnt work. PDF comes with a empty page. Because `doc` is out of scope
alert('done')
})
This is the code that worked for me:
function generatePDF() {
var doc = new jsPDF('landscape', 'pt','a2');
console.log(doc);
html2canvas($("#monthly_agg_report_container"), {
onrendered: function(canvas)
{
var imgData = canvas.toDataURL("image/png");
doc.addImage(imgData,'PNG',0,0,canvas.width*1.33,canvas.height*1.33);
// doc.save('report.pdf') ;
}
}).then(function(){
html2canvas($("#descriptor_stats_container"), {
onrendered: function(canvas)
{
console.log('2nd doc '+doc);
doc.addPage();
var imgData = canvas.toDataURL("image/png", 1.0);
doc.addImage(imgData,'PNG',0,0,canvas.width*1.33,canvas.height*1.33);
//doc.save('report.pdf') ;
}
}).then(function(){
alert('done')
html2canvas($("#alerts_stats_container"), {
onrendered: function(canvas)
{
console.log('2nd doc '+doc);
doc.addPage();
var imgData = canvas.toDataURL("image/png");
doc.addImage(imgData,'PNG',0,0,canvas.width*1.33,canvas.height*1.33);
doc.save('report.pdf') ;
}
})
})
})
}

html2canvas not work in ie9

I want to convert div to canvas and in chrome it works good but in IE9 it convert it but not good- its cut the div content and change the order of div elements.
witch js should i download that work well in IE9 too?
Someone have any idea how can I resolve this resolution problem?
my js code:
$scope.canvastoimage = function () {
html2canvas($("#mytryapp"), {
proxy: "server.js",
useCORS: true,
onrendered: function(canvas) {
document.body.appendChild(canvas);
$("#img-out").append(canvas);
$("#mytryapp").hide();
printthispage();
}
});
}
The result is attached:
Thanks!
This code works well in all browsers
html2canvas([document.getElementById(mytryapp)], {
onrendered: function (canvas) {
var imageData = canvas.toDataURL('image/png',1.0);
document.getElementById('img-out')[0].innerHTML = imageData;
}
});
Test it and see how it goes. The index 0 is used with jQuery objects to get "real" document element so if you are not using jquery change to this:
html2canvas([document.getElementById(mytryapp)], {
onrendered: function (canvas) {
var imageData = canvas.toDataURL('image/png',1.0);
document.getElementById('img-out').innerHTML = imageData;
}
});

Categories

Resources