Matei
Matei

Reputation: 327

Print page from HTML template

I have an HTML page that displays a data summary at the top and a grid at the bottom. I have a button at the top, which has to print the information on the page in a certain format. In order to showcase this specific format and get it approved by business, I created an additional HTML page which consists of divs and a table. When the print button in page 1 is clicked, the following code executes:

function print() {   
    $.get('PrintLayout.html', function (data) {
        var $data = $(data);
        $data.find('#field1').text($('#field1').text() + ' (' + $('#field2').text() + ')');
        $data.find('#field3').text($('#field3').text());
        $data.find('#field4').text($('#field4').text());
        $data.find('#field5').text(kendo.toString(field5, 'dd MMMM yyyy'));
        $data.find('#field6').text($('#field6').text());
        $data.find('#grid').append($('#grid').html());
        var html = $('<div>').append($data.clone()).remove().html(),
            width = 1120,
            height = 600,
            left = (screen.width / 2) - (width / 2),
            top = (screen.height / 2) - (height / 2),
            printPage = window.open('', 'Print', 'scrollbars=yes, width=' + width + ', height=' + height + ', left=' + left + ', top=' + top);
        printPage.document.open();
        printPage.document.write(html);
        printPage.document.close();
        printPage.focus();
        printPage.print();
        printPage.close();
        return false;
    });
}

What this code does is get the HTML of the print layout page and add the field values into the specific elements on that page.

When I look at the markup of the popup window and view source I notice that there aren't even html or head elements present. The window that pops up contains all the information in all the right places but on paper my grid's headings and columns come up misaligned. I know that if the markup of the page is corrected, the printout will look correct as well.

How can I fix this? Note that the PrintLayout.html page does have proper markup, it's just that somehow the $data JQuery doesn't extract this.

All I want is to get the HTML of the PrintLayout.html page, insert values into the placeholders on that page, display the resulting markup in a popup window and print it. I think I'm over-complicating it but can't find an easier way to do it.

Upvotes: 0

Views: 3494

Answers (1)

ced-b
ced-b

Reputation: 4065

I am not quite sure how your HTML works, but a simpler way of doing this would be to add a separate media to your CSS. Then you would only need your original page, no need for opening a pop-up and moving data around:

@media print {
   /*Put the way you want to format your page on printing here*/
}

See the W3C reference here.

Upvotes: 1

Related Questions