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.

Читайте также:  Python check int in range

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-курсы, нужно только пройти онлайн-тест здесь

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

Источник

Javascript печать блока с HTML страницы

При создании очередного сайта столкнулся с задачей печати HTML-страницы. На странице была информация о проекте (коттеджи) и ее нужно было по клику распечатать. Для решения идеально подходит Javascript. Итак, создаем такую структуру:

Обязательно задаем идентификатор. Содержимое может быть любым. Далее напишем небольшую функцию для печати веб-страницы:

  

И немного поясню. Эта функция откроет новое popup-окно, вызовет функцию печати. После печати автоматически закроет окно. В новое окно передается содержимое блока print-content. Также вызываем стили CSS, чтобы отформатировать содержимое. И, конечно, надо вызывать функцию. Делаем через Javascript функцию onClick:

Ну вот и все. Просто и с душой.

Если браузер не видит CSS стили

Если браузер по той или иной причине не хочет видить CSS, то можно упростить код, удалив пару строк:

Материалы:

Источник

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 и скрыть ненужные блоки.

Источник

How to print in JavaScript — with code examples

Posted on Apr 25, 2022

Depending on what you want to print and where you run JavaScript code, there are several ways to print in JavaScript.

When you want to print the current webpage of your browser, you can use the window.print() method.

The window.print() method will print the content of the currently active tab in your browser.

You can run the method from the browser console to print the webpage with your printer.

  • Print to the console using console.log()
  • Print to the browser interface using document.write()
  • Print to the alert box using window.alert() method
  • Print to the HTML tag by changing innerHTML property value

Let’s see how to do each one of these methods next.

The console.log() method allows you to print JavaScript data and values to the console.

This is useful when you want to check the value of variables you have in your JavaScript code as shown below:

The console.log() method instructs the JavaScript console to log the value passed as its parameter.

The console is available both on the browser and the Node.js server.

The document.write() method is used to write data to the tag of your HTML document.

This method will erase all data stored inside the tag of your webpage.

For example, suppose you have the following HTML document rendered in your browser:

When you run a document.write() command from the browser’s console, the HTML document above will be overwritten.

Running the following command:

Will produce the following output:
 As you can see, all attributes and elements previously written in the document have been erased.

The document object model is not available in the Node.js server, so you can only use this method from the browser.

The window.alert() method is used to create an alert box that’s available in the browser where you run the code.

For example, running the code below:

Will produce the following output:

How to print JavaScript with window.alert()

Using window.alert() method, you can check on your JavaScript variables and values with the browser’s alert box.

You can print to a specific HTML element available on your webpage by changing the innerHTML property of that element.

For example, suppose you have the following HTML document:


The HTML document will have the following changes:

Once you get the element, change the innerHTML property value, and that change will be reflected on your browser page.

Now you’ve learned how to print data and values in JavaScript. Good job! 👍

Learn JavaScript for Beginners 🔥

Get the JS Basics Handbook, understand how JavaScript works and be a confident software developer.

A practical and fun way to learn JavaScript and build an application using Node.js.

About

Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials.
Learn statistics, JavaScript and other programming languages using clear examples written for people.

Type the keyword below and hit enter

Tags

Click to see all tutorials tagged with:

Источник

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