Распечатать содержимое DIV - PullRequest
301 голосов
/ 13 февраля 2010

Как лучше всего распечатать содержимое DIV?

Ответы [ 25 ]

455 голосов
/ 13 февраля 2010

Небольшие изменения по сравнению с более ранней версией - проверено на CHROME

function PrintElem(elem)
{
    var mywindow = window.open('', 'PRINT', 'height=400,width=600');

    mywindow.document.write('<html><head><title>' + document.title  + '</title>');
    mywindow.document.write('</head><body >');
    mywindow.document.write('<h1>' + document.title  + '</h1>');
    mywindow.document.write(document.getElementById(elem).innerHTML);
    mywindow.document.write('</body></html>');

    mywindow.document.close(); // necessary for IE >= 10
    mywindow.focus(); // necessary for IE >= 10*/

    mywindow.print();
    mywindow.close();

    return true;
}
150 голосов
/ 24 августа 2011

Я думаю, что есть лучшее решение. Сделайте так, чтобы ваш div печатал на весь документ, но только когда он напечатан:

@media print {
    .myDivToPrint {
        background-color: white;
        height: 100%;
        width: 100%;
        position: fixed;
        top: 0;
        left: 0;
        margin: 0;
        padding: 15px;
        font-size: 14px;
        line-height: 18px;
    }
}
42 голосов
/ 26 сентября 2010

Хотя это было сказано @gmcalab, Если вы используете jQuery, вы можете использовать мой плагин printElement.

Здесь есть образец здесь и более подробная информация о плагине здесь .

Использование довольно простое, просто возьмите элемент с селектором jQuery и напечатайте его:

$("myDiv").printElement();

Надеюсь, это поможет!

21 голосов
/ 11 февраля 2015

Используя Jquery, просто используйте эту функцию:

<script>
function printContent(el){
var restorepage = $('body').html();
var printcontent = $('#' + el).clone();
$('body').empty().html(printcontent);
window.print();
$('body').html(restorepage);
}
</script>

Ваша кнопка печати будет выглядеть так:

<button id="print" onclick="printContent('id name of your div');" >Print</button>

Редактировать: если у вас есть данные формы, которые вам нужно сохранить, клон не скопирует их, поэтому вам просто нужно будет собрать все данные формы и заменить их после восстановления следующим образом:

<script>
function printContent(el){
var restorepage = $('body').html();
var printcontent = $('#' + el).clone();
var enteredtext = $('#text').val();
$('body').empty().html(printcontent);
window.print();
$('body').html(restorepage);
$('#text').html(enteredtext);
}
</script>
<textarea id="text"></textarea>
16 голосов
/ 19 июля 2012

Отсюда http://forums.asp.net/t/1261525.aspx

<html>
<head>
<script language="javascript">
function printdiv(printpage)
{
var headstr = "<html><head><title></title></head><body>";
var footstr = "</body>";
var newstr = document.all.item(printpage).innerHTML;
var oldstr = document.body.innerHTML;
document.body.innerHTML = headstr+newstr+footstr;
window.print();
document.body.innerHTML = oldstr;
return false;
}
</script>
<title>div print</title>
</head>


<body>
//HTML Page
//Other content you wouldn't like to print
<input name="b_print" type="button" class="ipt"   onClick="printdiv('div_print');" value=" Print ">


<div id="div_print">


<h1 style="Color:Red">The Div content which you want to print</h1>


</div>
//Other content you wouldn't like to print
//Other content you wouldn't like to print
</body>


</html>
11 голосов
/ 05 декабря 2015

я использовал Bill Paetzke ответ, чтобы напечатать div, содержащий изображения, но он не работал с Google Chrome

Мне просто нужно добавить эту строку myWindow.onload=function(){, чтобы она заработала, и вот полный код

<html>
<head>
    <script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.1.min.js"> </script>
    <script type="text/javascript">
        function PrintElem(elem) {
            Popup($(elem).html());
        }

        function Popup(data) {
            var myWindow = window.open('', 'my div', 'height=400,width=600');
            myWindow.document.write('<html><head><title>my div</title>');
            /*optional stylesheet*/ //myWindow.document.write('<link rel="stylesheet" href="main.css" type="text/css" />');
            myWindow.document.write('</head><body >');
            myWindow.document.write(data);
            myWindow.document.write('</body></html>');
            myWindow.document.close(); // necessary for IE >= 10

            myWindow.onload=function(){ // necessary if the div contain images

                myWindow.focus(); // necessary for IE >= 10
                myWindow.print();
                myWindow.close();
            };
        }
    </script>
</head>
<body>
    <div id="myDiv">
        This will be printed.
        <img src="image.jpg"/>
    </div>
    <div>
        This will not be printed.
    </div>
    <div id="anotherDiv">
        Nor will this.
    </div>
    <input type="button" value="Print Div" onclick="PrintElem('#myDiv')" />
</body>
</html>

также, если кому-то просто нужно напечатать div с идентификатором, ему не нужно загружать jquery

вот чистый код JavaScript, чтобы сделать это

<html>
<head>
    <script type="text/javascript">
        function PrintDiv(id) {
            var data=document.getElementById(id).innerHTML;
            var myWindow = window.open('', 'my div', 'height=400,width=600');
            myWindow.document.write('<html><head><title>my div</title>');
            /*optional stylesheet*/ //myWindow.document.write('<link rel="stylesheet" href="main.css" type="text/css" />');
            myWindow.document.write('</head><body >');
            myWindow.document.write(data);
            myWindow.document.write('</body></html>');
            myWindow.document.close(); // necessary for IE >= 10

            myWindow.onload=function(){ // necessary if the div contain images

                myWindow.focus(); // necessary for IE >= 10
                myWindow.print();
                myWindow.close();
            };
        }
    </script>
</head>
<body>
    <div id="myDiv">
        This will be printed.
        <img src="image.jpg"/>
    </div>
    <div>
        This will not be printed.
    </div>
    <div id="anotherDiv">
        Nor will this.
    </div>
    <input type="button" value="Print Div" onclick="PrintDiv('myDiv')" />
</body>
</html>

Я надеюсь, что это может кому-то помочь

9 голосов
/ 04 декабря 2012
function printdiv(printdivname)
{
var headstr = "<html><head><title>Booking Details</title></head><body>";
var footstr = "</body>";
var newstr = document.getElementById(printdivname).innerHTML;
var oldstr = document.body.innerHTML;
document.body.innerHTML = headstr+newstr+footstr;
window.print();
document.body.innerHTML = oldstr;
return false;
}

Это распечатает область div, которую вы хотите, и вернет содержимое в прежнее состояние. printdivname - это div для печати. ​​

8 голосов
/ 11 марта 2013

Я создал плагин для решения этого сценария. Я был недоволен плагинами и решил сделать что-то более обширное / настраиваемое.

https://github.com/jasonday/printThis

8 голосов
/ 13 февраля 2010

Создайте отдельную таблицу стилей печати, которая скрывает все другие элементы, кроме содержимого, которое вы хотите распечатать. Отметьте его, используя 'media="print" при загрузке:

<link rel="stylesheet" type="text/css" media="print" href="print.css" />

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

Если вы хотите, чтобы диалоговое окно печати браузера отображалось для страницы, вы можете сделать это при загрузке с помощью JQuery:

$(function() { window.print(); });

или вызвано любым другим желаемым событием, например, нажатием кнопки пользователем.

6 голосов
/ 20 октября 2015

Я думаю, что предложенные решения имеют следующие недостатки:

  1. Решения CSS для медиа-запросов предполагают, что для печати требуется только один div.
  2. Решения javascript работают только в определенных браузерах.
  3. Уничтожение содержимого родительского окна и воссоздание, которое создает беспорядок.

Я улучшил решения выше. Вот кое-что, что я протестировал, которое действительно хорошо работает со следующими преимуществами.

  1. Работает во всех браузерах, включая IE, Chrome, Safari и Firefox.
  2. Не разрушает и не перезагружает родительское окно.
  3. Может печатать любое количество DIV на странице.
  4. Использует HTML-шаблоны, чтобы избежать склонной к ошибкам конкатенации строк.

Ключевые моменты для заметки:

  1. Должен иметь onload = "window.print ()" во вновь созданном окне.
  2. Не вызывайте targetwindow.close () или targetwindow.print () из родительского элемента.
  3. Убедитесь, что вы используете targetwindow.document.close () и target.focus ()
  4. Я использую jquery, но вы можете сделать ту же технику, используя обычный javascript.
  5. Вы можете увидеть это в действии здесь http://math.tools/table/multiplication. Вы можете распечатать каждую таблицу отдельно, нажав на кнопку печати в заголовке окна.

<script id="print-header" type="text/x-jquery-tmpl">
   <html>
   <header>
       <title>Printing Para {num}</title>
       <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
       <style>
          body {
            max-width: 300px;
          }
       </style>
   </header>
   <body onload="window.print()">
   <h2>Printing Para {num} </h2>
   <h4>http://math.tools</h4>
</script>
<script id="print-footer" type="text/x-jquery-tmpl">
    </body>
    </html>
</script>
<script>
$('.printthis').click(function() {
   num = $(this).attr("data-id");
   w = window.open();
   w.document.write(
                   $("#print-header").html().replace("{num}",num)  +
                   $("#para-" + num).html() +
                   $("#print-footer").html() 
                   );
   w.document.close();
   w.focus();
   //w.print(); Don't do this otherwise chrome won't work. Look at the onload on the body of the newly created window.
   ///w.close(); Don't do this otherwise chrome won't work
});
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<a class="btn printthis" data-id="1" href="#" title="Print Para 1"><i class="fa fa-print"></i> Print Para 1</a>
<a class="btn printthis" data-id="2" href="#" title="Print Para 2"><i class="fa fa-print"></i> Print Para 2</a>
  
<p class="para" id="para-1">
  Para 1 : Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
  

<p class="para" id="para-2">
  Para 2 : Lorem 2 ipsum 2 dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
  
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...