Generate pdf from html file without showing on browser - javascript

I want to generate a pdf file from html template which is not loaded in browser. The basic idea is to load html in some javascript variable and convert it to canvas/pdf without showing on browser.
Right now I am doing this by adding a frame on currently opened page and then removing frame after successfully generating it's pdf. But this is showing some fluctuation on the screen and scrollbar.
Current Code:
$http.get("static/templates/pdf-template.html")
.then(function (response) {
var html_string = response.data;
var iframe = document.createElement('iframe');
iframe.style.width = '100%';
document.body.appendChild(iframe);
setTimeout(function () {
var iframedoc = iframe.contentDocument || iframe.contentWindow.document;
iframedoc.body.innerHTML = html_string;
var divHeight = iframedoc.body.scrollHeight;
var divWidth = iframedoc.body.scrollWidth;
var ratio = divHeight / divWidth;
html2canvas(iframedoc.body, {
onrendered: function (canvas) {
var pdf = new jsPDF();
var width = pdf.internal.pageSize.width;
var height = pdf.internal.pageSize.height;
height = ratio * width;
var imgData = canvas.toDataURL('image/jpeg', 1.0);
pdf.addImage(imgData, 'JPEG', 0, 0, width, height);
pdf.save('pdf');
document.body.removeChild(iframe);
}
});
}, 10);
});
Please suggest solution without using iframe.

I face this issue just now. I didn't any proper way. Even though I get a solution maybe, it will work. you just make your non-wanted portion of html style z-index: -1; and wanted portion of html style z-index: 1;

Related

How to get the dimensions of the svg-file in an iframe?

Taking for example the iframe in
http://dahlström.net/svg/html/get-embedded-svg-document-script.html
How to get the dimensions of the svg in there?
I want to scale the svg to the dimensions of the iframe, if the svg is larger than the iframe dimensions.
I'm currently using this solution. Not optimal, but working for my needs.
iframe.onload = continueOnLoadOfSvgInStdIframe;
iframe.src = url;
function continueOnLoadOfSvgInStdIframe() {
var svg = iframe.contentDocument;
var docEl = svg.documentElement;
if (typeof docEl.width==='undefined') { return; }
var w = docEl.width.baseVal.value;
var h = docEl.height.baseVal.value;
docEl.setAttribute("viewBox", "0 0 "+w+ " "+h);
docEl.setAttribute("width",iframe.clientWidth);
docEl.setAttribute("height",iframe.clientHeight);
}

how to hide the divs in html2canvas

Hello all i am using jsPDF along with html2canvas. I have seen in the add.HTML that you can hide some divs. Is it possible to have this ability in html2canvas.
I am actually making a pdf but i want some divs of the main div to not to be printed in the pdf.
This is my html2canvas code.
html2canvas(quotes, {
onrendered: function(canvas) {
//! MAKE YOUR PDF
var pdf = new jsPDF('p', 'pt', 'A4');
for (var i = 0; i <= quotes.clientHeight/980; i++) {
//! This is all just html2canvas stuff
var srcImg = canvas;
var sX = 0;
var sY = 980*i; // start 980 pixels down for every new page
var sWidth = 900;
var sHeight = 980;
var dX = 0;
var dY = 0;
var dWidth = 900;
var dHeight = 980;
window.onePageCanvas = document.createElement("canvas");
onePageCanvas.setAttribute('width', 900);
onePageCanvas.setAttribute('height', 980);
var ctx = onePageCanvas.getContext('2d');
// details on this usage of this function:
// https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Using_images#Slicing
ctx.drawImage(srcImg,sX,sY,sWidth,sHeight,dX,dY,dWidth,dHeight);
// document.body.appendChild(canvas);
var canvasDataURL = onePageCanvas.toDataURL("image/png", 1.0);
var width = onePageCanvas.width;
var height = onePageCanvas.clientHeight;
//! If we're on anything other than the first page,
// add another page
if (i > 0) {
pdf.addPage(612, 791); //8.5" x 11" in pts (in*72)
}
//! now we declare that we're working on that page
pdf.setPage(i+1);
//! now we add content to that page!
pdf.addImage(canvasDataURL, 'PNG', 20, 40, (width*.62), (height*.62));
}
//! after the for loop is finished running, we save the pdf.
pdf.save('Test.pdf');
}
});
Any kind of help would be much appreciated. Thankx in advance.
I finally solved this with searching more about html2canvas.
You just need to add
data-html2canvas-ignore="true"
in your html element to hide that div from rendering.
like this
<div class="anyclass" data-html2canvas-ignore="true">any data</div>

html2canvas too many base64 image request in network

I'm using html2canvas to take screenshot in a section of my page. Why does it creates a lot of request?
Anyone knows what this request are? It's making my developers tool unresponsive due to having too many requests.
Here's the code.
html2canvas($('#itemList')).then(function(canvas) {
var main_canvas = document.createElement('canvas');
var element = $('#itemList').find('.list-item');
var width = parseInt(element.css('width'));
var height = parseInt(element.css('height'));
var margin = parseInt(element.css('marginTop'));
var box_shadow = element.css('box-shadow');
var radiusTopLeft = element.css('borderTopLeftRadius');
var radiusTopRight = element.css('borderTopRightRadius');
var radiusBottomLeft = element.css('borderBottomLeftRadius');
var radiusBottomRight = element.css('borderBottomRightRadius');
var border = 0;
main_canvas.width = width;
main_canvas.height = height;
var ctx = main_canvas.getContext('2d');
ctx.drawImage(canvas, margin, margin, width, height, 0, 0, width, height);
var dataURL = main_canvas.toDataURL('image/jpeg',0.5);
$('#screenshot').attr('src', dataURL);
});
Here's a sample fiddle that also generates a data uri and involved the network
http://jsfiddle.net/Lybrzztw/
Thanks.

Resize image before loading - jquery

I'm using this plugin to create image zoom and gallery, yet I want to scale all images to fit with the container (using ratio algorithm).
Here is ratio function :
function scaleSize(maxW, maxH, currW, currH){
var ratio = currH / currW;
if(currW >= maxW && ratio <= 1){
currW = maxW;
currH = currW * ratio;
} else if(currH >= maxH){
currH = maxH;
currW = currH / ratio;
}
return [currW, currH];
}
And this is how the gallery load images :
var img = $('<img>').load(function(){
img.appendTo(a);
image_container.html(a);
}).attr('src', src).addClass(opts.big_image_class);
What I've tried :
var newSize = scaleSize(300, 320, $(".simpleLens-big-image").width(), $(".simpleLens-big-image").height());
var img = $('<img>').load(function(){
img.appendTo(a);
image_container.html(a);
}).attr('src', src).addClass(opts.big_image_class).width(newSize[0]).height(newSize[1]);
But scaleSize is not working properly since the current width and height is not yet defined (image not yet exist in dom).
Thanks for any pointers.
I took a look into plugin code and think you call your scaleSize() too early. An image with class simpleLens-big-image exists first after var img is set up and addClass() is done.
Try following:
var img = $('<img>').load(function(){
img.appendTo(a);
image_container.html(a);
}).attr('src', src).addClass(opts.big_image_class);
// at this point img should contain $(".simpleLens-big-image") so we can refer to img
var newSize = scaleSize(300, 320, img[0].naturalWidth, img[0].naturalHeight());
img.width(newSize[0]).height(newSize[1]);
Try something like this and call the onload method. This will make sure that the image is loaded to the DOM before you resize
var img = $('<img>');
img.src = src ;
img.onload = function() {
// Run onload code.
} ;

IE 6,7,8 don't support onload event in image object or DOM

My application has a large size of images to present and which should be resized for uniformly presentation with fixed width and height, to do so I write a JavaScript method in image's onload image like this:
var autoResizeImage = function(targetWidth, targetHeight, objImg) {
if (0 >= targetWidth || 0 >= targetHeight) {
// Ilegal parameters, just return.
return;
}
var img = new Image();
img.src = objImg.src;
// Calculate the width and height immediately the image is loaded.
img.onload = function() {
var hRatio;
var wRatio;
var width = img.width;
var height = img.height;
var calcWidth = width;
var calcHeight = height;
wRatio = targetWidth / width;
hRatio = targetHeight / height;
if (wRatio < hRatio) {
calcHeight = targetHeight;
calcWidth = (targetHeight / height) * width;
} else {
calcWidth = targetWidth;
calcHeight = (targetWidth / width) * height;
}
objImg.width = calcWidth;
objImg.height = calcHeight;
};
};
HTML image:
<img src='PATH' onload='autoResizeImage(100, 100, this)'>
This way works well on Chrome and Firefox except IE 6,7,8. I'm suffering on this, how can I complete this task on IE 6,7,8.
Thanks so much.
I would start by saying that if you're serving images to be displayed at a particular size, you should send them from the server at the correct size in the first place. Sending excessively large images and having the browser resize them is poor practice because it means that you're using up a lot more bandwidth than you need to. Your users may have restricted bandwidth, and may not appreciate the extra load time on your page caused by this.
However, I don't really know why you need to do this resizing exersise at all? HTML will by default scale an image to the size of the <img> tag that contains it anyway, so all you need to do is specify height and width styles for your <img> tag, and the scaling will be done automatically. There should be absolutely no need for all that messing around with Javascript.
<img src='PATH' style='width:100px; height:100px;'>
That should work in all browsers; no JS required. The image should be scaled for you.
But ideally, as I said, please try to avoid sending excessively large images to the page if you're not going to use them at full size.
Change the order of assignments. First assign onload function and then src attribute. It works for IE 8 at least.
var div = document.getElementById('div');
var img = new Image();
img.onload = function() {
var text = document.createTextNode('loaded ' + img.src);
div.appendChild(text);
};
window.setTimeout(function() {
var random = Math.random();
img.src ="http://stackoverflow.com/users/flair/450989.png?random=" + random;
}, 1000);
div.appendChild(img);
<div id="div"/>

Categories

Resources