Невозможно вставить таблицу стилей/скрипт в window.open

Я уже довольно давно борюсь с этой проблемой и (до сих пор) не могу напечатать свой div с его стилем.

В настоящее время мой сценарий:

$('#printMeButton').click(function () {
    //alert("a");
    var data = document.getElementById('thisPrintableTable').outerHTML;

    var mywindow = window.open('', data);
    mywindow.document.write('<html><head><title>Print Me!!!</title>');
    // mywindow.document.write('<link rel="stylesheet" type="text/css" href="Site.css" media="screen">');
    mywindow.document.write('</head><body>');
    mywindow.document.write(data);
    mywindow.document.write('</body></html>');

    mywindow.document.close();
    mywindow.focus();
    mywindow.print();
    mywindow.close();
    return true;

});

который вложен в функцию $(document).ready.

Когда я включаю нужную таблицу стилей (в настоящее время закомментированную), в предварительном просмотре печати ничего не появляется.

У меня также есть некоторый скрипт, который влияет на внешний вид таблицы, и поэтому я считаю, что это может содержать ключ к их включению во всплывающее окно.

Как я могу включить это в новое всплывающее окно?

Может ли кто-нибудь предложить способ печати этого в том виде, в каком он есть?

Редактировать историю

  • удален пробел в конце </head><body>
  • Изменено var data на outerHTML вместо innerHTML
  • Измененный вопрос/детали для лучшего понимания проблемы

person jbutler483    schedule 03.12.2014    source источник


Ответы (4)


Попробуйте открыть локальный html-файл, используя window.open с привязкой к нему css. И установите содержимое html для печати в локальный html-файл с помощью js.

Вот страница для печати:

<html>
<head>
    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link href="test.css" rel="stylesheet" type="text/css" />
    <script src="jquery.js"></script>
</head>
<body>
    <div id="print">
        <div class="red">TODO write content</div>
    </div>
    <button id="print_btn">Print</button>
    <script>
        $('#print_btn').click(function(){
            var newWindow = window.open('print.html','_blank');
            $(newWindow).load(function(){
               $(newWindow.document).find('body').html($('#print').html());
            });
        })
    </script>
</body>
</html>

Файл css test.css связан здесь, и я открываю print.html во время window.open, test.css также связан с print.html

Теперь в print.html я напишу: -

<html>
<head>
    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
     <link href="test.css" rel="stylesheet" type="text/css" />
</head>
<body>

</body>
</html>
person Indranil Mondal    schedule 03.12.2014
comment
не могли бы вы расширить / уточнить это? Я вроде понимаю эту возможность, но не реализацию - person jbutler483; 03.12.2014

Поскольку вы предоставляете пустую строку в качестве URL-адреса нового окна (первый параметр функции open), страница внутри него, скорее всего, не сможет определить, где находится ваша таблица стилей (поскольку ее адрес «относительно ничего»). Попробуйте указать абсолютный URL-адрес вашей таблицы стилей.

Кроме того, есть атрибут media="screen", который следует изменить на media="print".

mywindow.document.write('<link rel="stylesheet" type="text/css" href="http://my.site/Site.css" media="print"')
person Michał Dudak    schedule 03.12.2014
comment
Боюсь, это не сработало. По-прежнему печатает так же четко, как и раньше. - person jbutler483; 03.12.2014
comment
Я только что отредактировал ответ - также есть проблема с медиа-атрибутом. - person Michał Dudak; 03.12.2014
comment
Вы пробовали не закрывать окно сразу и проверять, нет ли ошибок в консоли разработчика? - person Michał Dudak; 03.12.2014

Проблему можно решить, введя некоторую задержку перед выполнением метода mywindow.close();. Кажется, что для применения (загрузки) CSS требуется некоторое время, например:

$('#printMeButton').click(function () {
    var content = document.getElementById(id).innerHTML;
    var mywindow = window.open('', 'Print', 'height=600,width=800');
    mywindow.document.write('<!DOCTYPE html><html dir="rtl"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Print</title>');
    mywindow.document.write('<link rel="stylesheet" type="text/css" href="/static/css/styles.css" />');
    mywindow.document.write('</head><body >');
    mywindow.document.write(content);
    mywindow.document.write('</body></html>');
    mywindow.document.close();
    mywindow.focus()
    mywindow.print();

    // this is needed for CSS to load before printing..
    setTimeout(function () {
        mywindow.close();
    }, 250);

    return true;
});
person W.M.    schedule 31.05.2018

Мы можем использовать этот встроенный стиль.

var divToPrint = document.getElementById('DivIdToPrint');

var newWin=window.open('','Print-Window');

newWin.document.open();

newWin.document.write('<html>' +
    '<style>' +
    ".btn-petty-cash-split{display: none}"+
    ".btn-petty-cash-split{display: none}"+
    '</style>' +
    '<body onload="window.print()">'+divToPrint.innerHTML+'</body></html>');

newWin.document.close();

setTimeout(function(){
    newWin.close();
    window.location.reload();
},10);
person Vin    schedule 14.02.2020