- Print.js
- PDF Printing
- Example
- HTML Printing
- Example
- Image Printing
- Example
- Печать HTML страниц
- Подключение CSS
- Специальный CSS-файл:
- Правило @media print:
- Размер страницы
- Поля
- Удаление лишних стилей
- Размер шрифта
- Скрытие лишних элементов
- Показ элемента только при печати
- Печать фона background
- Разрывы страниц
- Отображение URL в ссылках
- Пример вставки URL:
- Вывод QR-кода при печати
- Запуск печати
- How to print in JavaScript — with code examples
- Print with console.log() method
- Print with document.write() method
- Print using window.alert() method
- Print by changing the innerHTML property of your element
- Learn JavaScript for Beginners 🔥
- About
- Search
- Tags
- Javascript печать блока с HTML страницы
- Если браузер не видит CSS стили
- Материалы:
Print.js
A tiny javascript library to help printing from the web.
PDF Printing
Print.js was primarily written to help us print PDF files directly within our apps, without leaving the interface, and no use of embeds. For unique situations where there is no need for users to open or download the PDF files, and instead, they just need to print them.
One scenario where this is useful, for example, is when users request to print reports that are generated on the server side. These reports are sent back as PDF files. There is no need to open these files before printing them. Print.js offers a quick way to print these files within our apps.
PDF files must be served from the same domain as your app is hosted under. Print.js uses iframe to load files before printing them, therefore, it is limited by the Same Origin Policy. This helps preventing Cross-site scripting (XSS) attacks.
Example
Add a button to print a PDF file located on your hosting server:
For large files, you can show a message to the user when loading files.
Print Large PDF ( 5mb file ) Print Extra Large PDF ( 16mb file )
The library supports base64 PDF printing:
HTML Printing
Sometimes we just want to print selected parts of a HTML page, and that can be tricky. With Print.js, we can easily pass the id of the element that we want to print. The element can be of any tag, as long it has a unique id. The library will try to print it very close to how it looks on screen, and at the same time, it will create a printer friendly format for it.
Example
Add a print button to a HTML form:
Print.js accepts an object with arguments. Let’s print the form again, but now we will add a header to the page:
Image Printing
Print.js can be used to quickly print any image on your page, by passing the image url. This can be useful when you have multiple images on the screen, using a low resolution version of the images. When users try to print the selected image, you can pass the high resolution url to Print.js.
Example
Load images on your page with just the necessary resolution you need on screen:
In your javascript, pass the highest resolution image url to Print.js for a better print quality:
printJS('images/print-01-highres.jpg', 'image')
Печать HTML страниц
Очень часто разработчики забывают про печатную версию сайта, поэтому можно встретить такой результат на бумаге:
Подключение CSS
Специальный CSS-файл:
Правило @media print:
Третий метод – отдельная страница или шаблон, свёрстанные чисто под печать (без @media print ), например так сделана печать писем в Яндекс.Почте. Такой метод существенно облегчает отладку.
Размер страницы
- при dpi=75, А4 имеет 877×620 px
- при dpi=150, А4 имеет 1754×1240 px
- при dpi=300, А4 имеет 3508×2480 px
Поля
В целях экономии бумаги лучше использовать минимальные поля – 10 мм по краям и 20 мм слева для возможности брушеровки.
Поля по ГОСТ Р 6.30-2003 (оформление документов):
По ГОСТ 7.32-2017 (научные работы, рефераты):
Удаление лишних стилей
Тени и другие эффекты дизайна лучше убрать, также следует установить черный цвет шрифта.
Размер шрифта
Если на сайте размер шрифтов указан в пикселях, то при печати размер будет больше чем на экране. Поэтому нужно выставить новые значения:
Скрытие лишних элементов
Т.к. на бумаге элементы навигации, баннеры, шапка, подвал, и другие элементы не несут какой либо пользы, то лучше их скрыть или оставить в них только самое важное.
Другой вариант скрытия не нужного контента – в HTML-коде, добавить к скрываемым элементам класс noprint .
Не стоить забывать о , обычно для сайтов с фиксированным размером ему задана ширина, отступы и центрирование, поэтому при печати возможна обрезка контента с правого края, такие стили стоит обнулить.
Показ элемента только при печати
@media screen < .element < display: none; >> @media print < .element < display: block; >>
Печать фона background
По умолчанию браузеры не печатают background у элементов, но его можно пустить на печать принудительно c помощью свойства -webkit-print-color-adjust: exact; и нового color-adjust: exact; .
Уточнение: свойство не будет работать если цвет фона и шрифта слабоконтрастные.
Разрывы страниц
В CSS доступно управление переносами, соответственно для списков и таблиц нужно запретить переносы:
Если требуется принудительно сделать перенос после элемента:
Отображение URL в ссылках
Печать ссылок бесполезна т.к. будет не известно, куда они ведут. Можно добавить приписку URL рядом с анкором (исключая якорные ссылки).
Пример вставки URL:
Вывод QR-кода при печати
Будет очень удобно если на печатаной странице будет QR-код с ссылкой на сайт. Сгенерировать код можно с помощью сервиса «Google QR Codes» и вставить его с помощью JQuery.
Запуск печати
В JS, печать запускается методом window.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.
Print with console.log() method
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.
Print with document.write() method
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.
Print using window.alert() method
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:
Using window.alert() method, you can check on your JavaScript variables and values with the browser’s alert box.
Print by changing the innerHTML property of your element
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.
Search
Type the keyword below and hit enter
Tags
Click to see all tutorials tagged with:
Javascript печать блока с HTML страницы
При создании очередного сайта столкнулся с задачей печати HTML-страницы. На странице была информация о проекте (коттеджи) и ее нужно было по клику распечатать. Для решения идеально подходит Javascript. Итак, создаем такую структуру:
Обязательно задаем идентификатор. Содержимое может быть любым. Далее напишем небольшую функцию для печати веб-страницы:
И немного поясню. Эта функция откроет новое popup-окно, вызовет функцию печати. После печати автоматически закроет окно. В новое окно передается содержимое блока print-content. Также вызываем стили CSS, чтобы отформатировать содержимое. И, конечно, надо вызывать функцию. Делаем через Javascript функцию onClick:
Ну вот и все. Просто и с душой.
Если браузер не видит CSS стили
Если браузер по той или иной причине не хочет видить CSS, то можно упростить код, удалив пару строк:
Материалы: