Print Me

Printing

There may be times in which your website or application would like to improve the user’s experience when printing content. There are a number of possible scenarios:

  • You wish to adjust layout to take advantage of the size and shape of the paper.
  • You wish to use different styles to enhance the appearance of your content on paper.
  • You wish to use higher resolution images for a better result.
  • You want to adjust the user experience of printing, such as presenting a specially-formatted version of your content before printing begins.

There may be other cases in which you want to manage the printing process, but these are some of the most common scenarios. This article provides tips and techniques for helping your web content print better.

Using a print style sheet

Add the following to your tag.

link href="/path/to/print.css" media="print" rel="stylesheet" /> 

Using media queries to improve layout

You can use the CSS @media at-rule to set a different appearance for your webpage when it is printed on paper and when it is displayed on the screen. The print option sets the styles that will be used when the content is printed.

Читайте также:  Exception in thread main java lang unsupportedclassversionerror org bukkit craftbukkit main

Add this at the end of your stylesheet. Note that specificity and precedence rules still apply:

@media print  /* All your print styles go here */ #header, #footer, #nav  display: none !important; > > 

Detecting print requests

Browsers send beforeprint and afterprint events to let content determine when printing may have occurred. You can use this to adjust the user interface presented during printing (such as by displaying or hiding user interface elements during the print process).

Examples

Here are some common examples.

Open and automatically close a popup window when finished

If you want to be able to automatically close a popup window (for example, the printer-friendly version of a document) after the user prints its contents, you can use code like this:

doctype html> html lang="en-US"> head> meta charset="utf-8" /> meta name="viewport" content="width=device-width" /> title>JavaScript Window Close Exampletitle> script> function popuponclick()  const my_window = window.open( "", "mywindow", "status=1,width=350,height=150", ); my_window.document.write(""); my_window.document.write(''); my_window.document.write( "

When you print this window, it will close afterward.

"
, ); my_window.document.write(""); >
script> head> body> p> To try out the code>afterprintcode> event, click the link below to open the window to print. You can also try changing the code to use code>beforeprintcode> to see the difference. p> p>a href="javascript: popuponclick()">Open Popup Windowa>p> body> html>

If you want to be able to print an external page without opening it, you can utilize a hidden (see: HTMLIFrameElement), automatically removing it after the user prints its contents. The following is a possible example which will print a file named externalPage.html :

doctype html> html lang="en-US"> head> meta charset="utf-8" /> meta name="viewport" content="width=device-width" /> title>MDN Exampletitle> script> function closePrint()  document.body.removeChild(this.__container__); > function setPrint()  this.contentWindow.__container__ = this; this.contentWindow.onbeforeunload = closePrint; this.contentWindow.onafterprint = closePrint; this.contentWindow.focus(); // Required for IE this.contentWindow.print(); > function printPage(sURL)  const hideFrame = document.createElement("iframe"); hideFrame.onload = setPrint; hideFrame.style.position = "fixed"; hideFrame.style.right = "0"; hideFrame.style.bottom = "0"; hideFrame.style.width = "0"; hideFrame.style.height = "0"; hideFrame.style.border = "0"; hideFrame.src = sURL; document.body.appendChild(hideFrame); > script> head> body> p> span onclick="printPage('externalPage.html');" style="cursor:pointer;text-decoration:underline;color:#0000ff;"> Print external page! span> p> body> html> 

See also

Found a content problem with this page?

This page was last modified on Jul 7, 2023 by MDN contributors.

Источник

Версия страницы для печати или печать отдельного блока на сайте

Версия страницы для печати или печать отдельного блока на сайте

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

Вызвать печать на странице

Печать документа на странице можно вызвать JavaScript функцией print() .

Оформление страницы печати

Оформить вид страницы сайта при печати очень просто. Делается это с помощью медиа-запросов. Для этого в стили сайта добавляем @media print и внутри него пишем стили, которые будут вызваны при печати страницы Типография Печатник. В примере ниже на распечатываемой странице сайта отключаем блок с рекламой:

Печать отдельного блока со страницы

Код HTML

Заголовок

Текст
Печать

Код JavaScript

  

При нажатии кнопки «Печать» происходит вызов функции callPrint() . Если будете модернизировать код, то тут функции можно передавать к примеру ID блока, который нужно распечатать. В примере мы ничего не передаем и не используем библиотеку jQuery, хотя при более сложной вариации с ней будет проще.

Далее вызывается всплывающее окно, в которое добавляются наши блоки, после чего окно закрывается и открывается окно браузера для печати. Все это делается практически незаметно. И для пользователя это будет выглядеть так, как будто окно печати открылось сразу.

Подборка бесплатных IT-курсов и вебинаров от Skillbox.

Бесплатные IT-курсы, нужно только пройти онлайн-тест здесь

Если вам понравилась статья, вы можете отблагодарить автора любой суммой, какую сочтете для себя приемлемой:

Источник

window . print ( )

Вызов метода print ( ) объекта window открывает стандартный диалог печати текущей страницы.

Как пишется

Скопировать ссылку «Как пишется» Скопировано

 window.print() window.print()      

Как понять

Скопировать ссылку «Как понять» Скопировано

При создании приложения мы можем предложить пользователю распечатать текущую страницу. Например, если показываем ему номер оформленного заказа, подтверждение бронирования и так далее.

Для этого достаточно написать несколько строк кода. Например, открывать системный диалог печати при нажатии на кнопку:

 const printButton = document.getElementById('print-button') printButton.addEventListener('click', function()  window.print()>) const printButton = document.getElementById('print-button') printButton.addEventListener('click', function()  window.print() >)      

Такой код делает то же самое, что и системное меню File → Print.

По умолчанию страница печатается в том виде, какой её видно на экране — цветная, с шапкой, футером, меню. Печатную версию сайта можно настроить с помощью CSS-директивы @media print и скрыть ненужные блоки.

Источник

window . print ( )

Вызов метода print ( ) объекта window открывает стандартный диалог печати текущей страницы.

Как пишется

Скопировать ссылку «Как пишется» Скопировано

 window.print() window.print()      

Как понять

Скопировать ссылку «Как понять» Скопировано

При создании приложения мы можем предложить пользователю распечатать текущую страницу. Например, если показываем ему номер оформленного заказа, подтверждение бронирования и так далее.

Для этого достаточно написать несколько строк кода. Например, открывать системный диалог печати при нажатии на кнопку:

 const printButton = document.getElementById('print-button') printButton.addEventListener('click', function()  window.print()>) const printButton = document.getElementById('print-button') printButton.addEventListener('click', function()  window.print() >)      

Такой код делает то же самое, что и системное меню File → Print.

По умолчанию страница печатается в том виде, какой её видно на экране — цветная, с шапкой, футером, меню. Печатную версию сайта можно настроить с помощью CSS-директивы @media print и скрыть ненужные блоки.

Источник

Оцените статью