Wydrukuj zawartość DIV

Jaki jest najlepszy sposób na wydrukowanie zawartości DIV?

Author: Bill Paetzke, 2010-02-13

24 answers

Niewielkie zmiany w stosunku do wcześniejszej wersji-testowane na 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;
}
 412
Author: Bill Paetzke,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-06 14:48:54

Myślę, że jest lepsze rozwiązanie. Zrób div, aby wydrukować cały dokument, ale tylko wtedy, gdy jest wydrukowany:

@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;
    }
}
 139
Author: BC.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-08-23 20:54:07

Chociaż to zostało powiedziane przez @ gmcalab, Jeśli używasz jQuery, możesz użyć wtyczki my printElement.

Jest próbka tutaj , a więcej informacji o wtyczce tutaj .

Użycie jest raczej proste, po prostu chwyć element za pomocą selektora jQuery i wydrukuj go:

$("myDiv").printElement();
Mam nadzieję, że to pomoże!
 41
Author: Erik,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-09-26 14:57:54

Używając Jquery, po prostu użyj tej funkcji:

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

Twój przycisk drukowania będzie wyglądał tak:

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

Edit: jeśli masz dane formularza, które musisz zachować, clone nie skopiuje tego, więc musisz pobrać wszystkie dane formularza i zastąpić je po przywróceniu w następujący sposób:

<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>
 19
Author: Gary Hayes,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-12-22 15:46:14

Stąd 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>
 16
Author: huston007,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-07-19 08:09:06
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;
}

Wyświetli żądany obszar div I ustawi zawartość z powrotem na taką, jaka była. {[1] } jest div do wydrukowania.

 9
Author: Techie,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-12-04 06:23:00

Utwórz oddzielny arkusz stylów drukowania, który ukryje wszystkie inne elementy z wyjątkiem zawartości, którą chcesz wydrukować. Oznacz go za pomocą 'media="print" po załadowaniu:

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

Pozwala to na załadowanie zupełnie innego arkusza stylów dla wydruków.

Jeśli chcesz wymusić wyświetlenie okna drukowania przeglądarki dla strony, możesz to zrobić w ten sposób przy ładowaniu za pomocą JQuery:

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

Lub wyzwalane z dowolnego innego zdarzenia, które chcesz, np. przez użytkownika klikającego przycisk.

 8
Author: Carl Russmann,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-02-12 21:51:46

Użyłem Bill Paetzke answer aby wydrukować div zawierający obrazy ale nie działa z google chrome

Po prostu musiałem dodać tę linię myWindow.onload=function(){, aby to działało i oto Pełny kod

<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>

Również jeśli ktoś po prostu musi wydrukować div z id nie musi ładować jquery

Tutaj jest czysty kod javascript, aby to zrobić

<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>

Mam nadzieję, że to może komuś pomóc

 8
Author: Robert,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-12-06 19:19:10

Jestem autorem wtyczki do rozwiązania tego scenariusza. Byłem niezadowolony z wtyczek i postanowiłem zrobić coś bardziej rozbudowanego / konfigurowalnego.

Https://github.com/jasonday/printThis

 7
Author: Jason,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-03-10 23:39:57

Myślę, że proponowane dotychczas rozwiązania mają następujące wady:

  1. rozwiązania CSS media query zakładają, że istnieje tylko jeden div do wydrukowania.
  2. rozwiązania javascript działają tylko w niektórych przeglądarkach.
  3. zniszczenie zawartości okna nadrzędnego i odtworzenie, które powoduje bałagan.

Poprawiłem powyższe rozwiązania. Oto coś, co przetestowałem, co działa naprawdę dobrze z następującymi korzyściami.

  1. działa na wszystkich przeglądarkach w tym IE, Chrome, Safari i firefox.
  2. nie niszczy i nie przeładowuje okna nadrzędnego.
  3. może wydrukować dowolną liczbę DIV na stronie.
  4. używa szablonów html, aby uniknąć podatnych na błędy konkatenacji łańcuchów.

Najważniejsze punkty do Uwagi:

  1. trzeba mieć onload = " okno.print () " w nowo utworzonym oknie.
  2. Nie dzwoń do targetwindow.close() lub targetwindow.print () od rodzica.
  3. Upewnij się, że robisz targetwindow.dokument.close() i cel.focus ()
  4. używam jquery, ale możesz zrobić tę samą technikę używając zwykłego javascript, jak również.
  5. możesz zobaczyć to w akcji tutaj http://math.narzędzia/tabela / mnożenie . Możesz wydrukować każdą tabelę osobno, klikając przycisk Drukuj na nagłówku pudełka.

<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>
  
 6
Author: dors,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-10-20 15:57:18

Przyjęte rozwiązanie nie działało. Chrome drukował pustą stronę, ponieważ nie ładował obrazu na czas. To podejście działa:

Edit: wygląda na to, że zaakceptowane rozwiązanie zostało zmodyfikowane po moim poście. Skąd ta negatywna opinia? To rozwiązanie również działa.

    function printDiv(divName) {

        var printContents = document.getElementById(divName).innerHTML;
        w = window.open();

        w.document.write(printContents);
        w.document.write('<scr' + 'ipt type="text/javascript">' + 'window.onload = function() { window.print(); window.close(); };' + '</sc' + 'ript>');

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

        return true;
    }
 4
Author: live-love,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-01-30 14:35:53

Wiem, że to stare pytanie, ale rozwiązałem ten problem w jQuery.

function printContents(id)
{
    var contents = $("#"+id).html();

    if ($("#printDiv").length == 0)
    {
    var printDiv = null;
    printDiv = document.createElement('div');
    printDiv.setAttribute('id','printDiv');
    printDiv.setAttribute('class','printable');
    $(printDiv).appendTo('body');
    }

    $("#printDiv").html(contents);

    window.print();

    $("#printDiv").remove();


}

CSS

  @media print {
    .non-printable, .fancybox-outer { display: none; }
    .printable, #printDiv { 
        display: block; 
        font-size: 26pt;
    }
  }
 3
Author: Jazzy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-01-06 22:17:46

Chociaż @BC odpowiedź była najlepsza do wydrukowania jednej strony.

Ale aby wydrukować wiele stron formatu A4 w tym samym czasie za pomocą ctrl + P następujące rozwiązanie może pomóc.

@media print{
html *{
    height:0px!important;
    width:0px !important;
    margin: 0px !important;
    padding: 0px !important;
    min-height: 0px !important;
    line-height: 0px !important;
    overflow: visible !important;
    visibility: hidden ;


}


/*assing myPagesClass to every div you want to print on single separate A4 page*/

 body .myPagesClass {
    z-index: 100 !important;
    visibility: visible !important;
    position: relative !important;
    display: block !important;
    background-color: lightgray !important;
    height: 297mm !important;
    width: 211mm !important;
    position: relative !important;

    padding: 0px;
    top: 0 !important;
    left: 0 !important;
    margin: 0 !important;
    orphans: 0!important;
    widows: 0!important;
    overflow: visible !important;
    page-break-after: always;

}
@page{
    size: A4;
    margin: 0mm ;
    orphans: 0!important;
    widows: 0!important;
}}
 3
Author: arslan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-01-19 07:00:53
  • Otwórz nowe okno
  • Otwórz obiekt document w nowym oknie i zapisz do niego prosty dokument zawierający nic poza posiadanym div I niezbędnym nagłówkiem html itp. - Możesz również chcieć, aby dokument był pobierany w arkuszu stylów, w zależności od zawartości
  • Umieść skrypt w oknie nowa strona do wywołania.print ()
  • Uruchom skrypt
 2
Author: Pointy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-02-12 21:53:28

Oto mój jQuery print plugin

(function ($) {

$.fn.printme = function () {
    return this.each(function () {
        var container = $(this);

        var hidden_IFrame = $('<iframe></iframe>').attr({
            width: '1px',
            height: '1px',
            display: 'none'
        }).appendTo(container);

        var myIframe = hidden_IFrame.get(0);

        var script_tag = myIframe.contentWindow.document.createElement("script");
        script_tag.type = "text/javascript";
        script = myIframe.contentWindow.document.createTextNode('function Print(){ window.print(); }');
        script_tag.appendChild(script);

        myIframe.contentWindow.document.body.innerHTML = container.html();
        myIframe.contentWindow.document.body.appendChild(script_tag);

        myIframe.contentWindow.Print();
        hidden_IFrame.remove();

    });
};
})(jQuery);
 2
Author: karaxuna,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-07-27 10:56:48

W Operze spróbuj:

    print_win.document.write('</body></html>');
    print_win.document.close(); // This bit is important
    print_win.print();
    print_win.close();
 1
Author: mirk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-02-19 18:25:10

Oto rozwiązanie IFrame, które działa dla IE i Chrome:

function printHTML(htmlString) {
    var newIframe = document.createElement('iframe');
    newIframe.width = '1px';
    newIframe.height = '1px';
    newIframe.src = 'about:blank';

    // for IE wait for the IFrame to load so we can access contentWindow.document.body
    newIframe.onload = function() {
        var script_tag = newIframe.contentWindow.document.createElement("script");
        script_tag.type = "text/javascript";
        var script = newIframe.contentWindow.document.createTextNode('function Print(){ window.focus(); window.print(); }');
        script_tag.appendChild(script);

        newIframe.contentWindow.document.body.innerHTML = htmlString;
        newIframe.contentWindow.document.body.appendChild(script_tag);

        // for chrome, a timeout for loading large amounts of content
        setTimeout(function() {
            newIframe.contentWindow.Print();
            newIframe.contentWindow.document.body.removeChild(script_tag);
            newIframe.parentElement.removeChild(newIframe);
        }, 200);
    };
    document.body.appendChild(newIframe);
}
 1
Author: kofifus,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-06-24 01:06:05

Zmodyfikowałem odpowiedź @ BillPaetski, aby użyć queryselectora, dodać opcjonalny CSS, usunąć wymuszony znacznik H1 i uczynić tytuł opcjonalnie określonym lub pobranym z okna. Nie jest również już automatycznie drukowany i eksponuje wewnętrzne elementy, dzięki czemu można je przełączać w funkcji owijania lub jak chcesz.

Jedynymi prywatnymi var-ami są tmpWindow i tmpdoc chociaż uważam, że title, css i elem access mogą się różnić, należy założyć, że wszystkie argumenty funkcji są prywatne.

Kod:
function PrintElem(elem, title, css) {
    var tmpWindow = window.open('', 'PRINT', 'height=400,width=600');
    var tmpDoc = tmpWindow.document;

    title = title || document.title;
    css = css || "";

    this.setTitle = function(newTitle) {
        title = newTitle || document.title;
    };

    this.setCSS = function(newCSS) {
        css = newCSS || "";
    };

    this.basicHtml5 = function(innerHTML) {
        return '<!doctype html><html>'+(innerHTML || "")+'</html>';
    };

    this.htmlHead = function(innerHTML) {
        return '<head>'+(innerHTML || "")+'</head>';
    };

    this.htmlTitle = function(title) {
        return '<title>'+(title || "")+'</title>';
    };

    this.styleTag = function(innerHTML) {
        return '<style>'+(innerHTML || "")+'</style>';
    };

    this.htmlBody = function(innerHTML) {
        return '<body>'+(innerHTML || "")+'</body>';
    };

    this.build = function() {
        tmpDoc.write(
            this.basicHtml5(
                this.htmlHead(
                    this.htmlTitle(title) + this.styleTag(css)
                ) + this.htmlBody(
                    document.querySelector(elem).innerHTML
                )
            )
        );
        tmpDoc.close(); // necessary for IE >= 10
    };

    this.print = function() {
        tmpWindow.focus(); // necessary for IE >= 10*/
        tmpWindow.print();
        tmpWindow.close();
    };

    this.build();
    return this;
}
Użycie:
DOMPrinter = PrintElem('#app-container');
DOMPrinter.print();
 1
Author: MrMesees,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-02-15 10:17:09

Jeśli chcesz mieć wszystkie style z oryginalnego dokumentu (w tym Style inline), możesz użyć tego podejścia.

  1. skopiuj kompletny dokument
  2. Zastąp ciało elementem, który chcesz wydrukować.

Realizacja:

class PrintUtil {
  static printDiv(elementId) {
    let printElement = document.getElementById(elementId);
    var printWindow = window.open('', 'PRINT');
    printWindow.document.write(document.documentElement.innerHTML);
    setTimeout(() => { // Needed for large documents
      printWindow.document.body.style.margin = '0 0';
      printWindow.document.body.innerHTML = printElement.outerHTML;
      printWindow.document.close(); // necessary for IE >= 10
      printWindow.focus(); // necessary for IE >= 10*/
      printWindow.print();
      printWindow.close();
    }, 1000)
  }   
}
 1
Author: Stefan Norberg,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-15 14:36:52

Stworzył coś generycznego do użycia na dowolnym elemencie HTML

HTMLElement.prototype.printMe = printMe;
function printMe(query){             
     var myframe = document.createElement('IFRAME');
     myframe.domain = document.domain;
     myframe.style.position = "absolute";
     myframe.style.top = "-10000px";
     document.body.appendChild(myframe);
     myframe.contentDocument.write(this.innerHTML) ;
     setTimeout(function(){
        myframe.focus();
        myframe.contentWindow.print();
        myframe.parentNode.removeChild(myframe) ;// remove frame
     },3000); // wait for images to load inside iframe
     window.focus();
}
//usage
document.getElementById('xyz').printMe();
document.getElementsByClassName('xyz')[0].printMe();
Mam nadzieję, że to pomoże.
 0
Author: Gaurav,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-05-14 12:18:34

Uwaga: to działa tylko z włączonymi witrynami jQuery

To bardzo proste z tym fajnym trikiem. Działa mi to w Google Chrome browser. Firefox nie pozwala na drukowanie do PDF bez wtyczki.
  1. najpierw otwórz Inspektora używając (Ctrl + Shift + I) / (Cmd + Opcja + I).
  2. Wpisz ten kod w konsoli

var jq = document.createElement('script');

jq.src = "https://cdnjs.cloudflare.com/ajax/libs/jQuery.print/1.5.1/jQuery.print.min.js";

document.getElementsByTagName('body')[0].appendChild(jq)

$("#myDivWithStyles").print() // Replace ID with yours
  1. uruchamia okno drukowania. Weź fizyczny wydruk lub zapisz go w formacie PDF (w chrome). Zrobione!
Logika jest prosta. Tworzymy nowy znacznik skryptu i dołączamy go przed zamykającym znacznikiem body. Wprowadziliśmy rozszerzenie wydruku jQuery do HTML. Zmień myDivWithStyles z własnym identyfikatorem znacznika Div. Teraz zajmuje się przygotowaniem wirtualnego okna do druku.

Spróbuj na dowolnej stronie. Tylko zastrzeżenie jest czasami podstępnie napisany CSS może spowodować brak stylów. Ale dostajemy treści najczęściej.

 0
Author: Naren Yellavula,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-12-07 10:02:16

Poniższy kod kopiuje wszystkie odpowiednie węzły, które są kierowane przez selektor zapytań, kopiuje ich style, jak widać na ekranie, ponieważ wiele elementów nadrzędnych używanych do kierowania selektorów css będzie brakować. Powoduje to niewielkie opóźnienie, jeśli istnieje wiele węzłów potomnych z wieloma stylami.

Najlepiej mieć gotowy arkusz stylów wydruku, ale jest to dla przypadków użycia, w których nie ma arkusza stylów wydruku do wstawienia i chcesz wydrukować tak, jak widać na ekranie.

Jeśli skopiujesz poniżej elementy w konsoli przeglądarki na tej stronie wydrukuje wszystkie fragmenty kodu na tej stronie.

+function() {
    /**
     * copied from  https://stackoverflow.com/questions/19784064/set-javascript-computed-style-from-one-element-to-another
     * @author Adi Darachi https://stackoverflow.com/users/2318881/adi-darachi
     */
    var copyComputedStyle = function(from,to){
        var computed_style_object = false;
        //trying to figure out which style object we need to use depense on the browser support
        //so we try until we have one
        computed_style_object = from.currentStyle || document.defaultView.getComputedStyle(from,null);

        //if the browser dose not support both methods we will return null
        if(!computed_style_object) return null;

            var stylePropertyValid = function(name,value){
                        //checking that the value is not a undefined
                return typeof value !== 'undefined' &&
                        //checking that the value is not a object
                        typeof value !== 'object' &&
                        //checking that the value is not a function
                        typeof value !== 'function' &&
                        //checking that we dosent have empty string
                        value.length > 0 &&
                        //checking that the property is not int index ( happens on some browser
                        value != parseInt(value)

            };

        //we iterating the computed style object and compy the style props and the values
        for(property in computed_style_object)
        {
            //checking if the property and value we get are valid sinse browser have different implementations
                if(stylePropertyValid(property,computed_style_object[property]))
                {
                    //applying the style property to the target element
                        to.style[property] = computed_style_object[property];

                }   
        }   

    };


    // Copy over all relevant styles to preserve styling, work the way down the children tree.
    var buildChild = function(masterList, childList) {
        for(c=0; c<masterList.length; c++) {
           var master = masterList[c];
           var child = childList[c];
           copyComputedStyle(master, child);
           if(master.children && master.children.length > 0) {
               buildChild(master.children, child.children);
           }
        }
    }

    /** select elements to print with query selector **/
    var printSelection = function(querySelector) {
        // Create an iframe to make sure everything is clean and ordered.
        var iframe = document.createElement('iframe');
        // Give it enough dimension so you can visually check when modifying.
        iframe.width = document.width;
        iframe.height = document.height;
        // Add it to the current document to be sure it has the internal objects set up.
        document.body.append(iframe);

        var nodes = document.querySelectorAll(querySelector);
        if(!nodes || nodes.length == 0) {
           console.error('Printing Faillure: Nothing to print. Please check your querySelector');
           return;
        }

        for(i=0; i < nodes.length; i++) {

            // Get the node you wish to print.
            var origNode = nodes[i];

            // Clone it and all it's children
            var node = origNode.cloneNode(true);

            // Copy the base style.
            copyComputedStyle(origNode, node);

            if(origNode.children && origNode.children.length > 0) {
                buildChild(origNode.children, node.children);
            }

            // Add the styled clone to the iframe. using contentWindow.document since it seems the be the most widely supported version.

            iframe.contentWindow.document.body.append(node);
        }
        // Print the window
        iframe.contentWindow.print();

        // Give the browser a second to gather the data then remove the iframe.
        window.setTimeout(function() {iframe.parentNode.removeChild(iframe)}, 1000);
    }
window.printSelection = printSelection;
}();
printSelection('.default.prettyprint.prettyprinted')
 0
Author: Tschallacka,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-01 12:13:19

Tak samo jak najlepsza odpowiedź, na wszelki wypadek musisz wydrukować obrazek tak jak ja:

W przypadku, gdy chcesz wydrukować obrazek:

function printElem(elem)
    {
        Popup(jQuery(elem).attr('src'));
    }

    function Popup(data) 
    {
        var mywindow = window.open('', 'my div', 'height=400,width=600');
        mywindow.document.write('<html><head><title>my div</title>');
        mywindow.document.write('</head><body >');
        mywindow.document.write('<img src="'+data+'" />');
        mywindow.document.write('</body></html>');

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

        return true;
    }
 -1
Author: Goran Jakovljevic,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-10-17 19:38:26

Najlepszym sposobem na to byłoby przesłanie zawartości div do serwera i otwarcie nowego okna, w którym serwer mógłby umieścić tę zawartość w nowym oknie.

Jeśli to nie jest opcja, możesz spróbować użyć języka po stronie klienta, takiego jak javascript, aby ukryć wszystko na stronie z wyjątkiem tego div, a następnie wydrukować stronę...

 -3
Author: Sonny Boy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-02-12 21:45:48