-1
$.get("http://example.com/invoice.html", function( data ) {
                console.log(data); //work
                window.print(data); // doesn't
            });

How to correctly load an external html and print it? Above code doesn't work,

it print the webpage itself, not the external html which I wanted.

Any idea?

Meenesh Jain
  • 2,532
  • 2
  • 19
  • 29
Alice Xu
  • 533
  • 6
  • 20

2 Answers2

1

Print function does not take any parameter, it just print the window data.

As long as your data is html (to be properly formatted and viewed) you can open a new window where you set your data in, close it and use the print function with it since the object will still be available, you can also link any CSS specific to the printed data in the new window :

$.get("http://example.com/invoice.html", function( data ) {

       var printWindow = window.open('', '', 'height=400,width=800');
       printWindow.document.write('<html><head><title>DIV Contents</title>');
       printWindow.document.write('</head><body >');
       printWindow.document.write(data);
       printWindow.document.write('</body></html>');
       printWindow.document.close();
       printWindow.print();
});
KAD
  • 10,972
  • 4
  • 31
  • 73
  • open and close? ok let me try this – Alice Xu Aug 14 '15 at 07:01
  • it worked but it blocked by popup, I've seen someone can just print without opening any new window. – Alice Xu Aug 14 '15 at 07:03
  • `window.open` is blocked by most popup blockers. – Cerbrus Aug 14 '15 at 07:04
  • It does not need to open or to be seen by the user, the browser print view will show the content, this is just a workaround to print specific content. – KAD Aug 14 '15 at 07:07
  • You can also check this [trick](http://stackoverflow.com/questions/468881/print-div-id-printarea-div-only), you will need to create a printing div, and inside the get function set the html content of this div using jquery `html` then print the main window after setting ur `CSS` as stated in the question (using print media query), this will also do you the trick. – KAD Aug 14 '15 at 07:11
0

window.print() doesn't accept any parameters.

You'll need to open the gotten HTML in a new window, or load it into in a modal overlay, then call window.print.

Cerbrus
  • 70,800
  • 18
  • 132
  • 147