1

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.

umair151
  • 553
  • 5
  • 21
  • 1
    Welcome to SO. Please visit the [help] to see what and how to ask. HINT: Post effort and code. Since you already tagged this JSPDF, why not start there? [Look here for more](http://stackoverflow.com/questions/742271/generating-pdf-files-with-javascript) – mplungjan Dec 29 '16 at 07:37
  • @mplungjan Thanks for mentioning. Done – umair151 Dec 29 '16 at 07:44

1 Answers1

0

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;