Generate pdf from html file without showing on browser

1.4k views Asked by At

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.

1

There are 1 answers

0
sidhique kerala On

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;