- How to set A4 page size for Print Using CSS
- Печать HTML страниц
- Подключение CSS
- Специальный CSS-файл:
- Правило @media print:
- Размер страницы
- Поля
- Удаление лишних стилей
- Размер шрифта
- Скрытие лишних элементов
- Показ элемента только при печати
- Печать фона background
- Разрывы страниц
- Отображение URL в ссылках
- Пример вставки URL:
- Вывод QR-кода при печати
- Запуск печати
- CSS to set A4 paper size
- 3 Answers 3
- DEMO
- CSS to specify full page width at printing?
- 2 Answers 2
- Linked
- Related
- Hot Network Questions
- Subscribe to RSS
How to set A4 page size for Print Using CSS
Dimension of A4 Page size is ( 210 mm X 297 mm ) or ( 21cm X 29.7cm ). The following example shows, how to set page size (A4) for print using CSS style.
body width: 230mm; height: 100%; margin: 0 auto; padding: 0; font-size: 12pt; background: rgb(204,204,204); > * box-sizing: border-box; -moz-box-sizing: border-box; > .main-page width: 210mm; min-height: 297mm; margin: 10mm auto; background: white; box-shadow: 0 0 0.5cm rgba(0,0,0,0.5); > .sub-page padding: 1cm; height: 297mm; > @page size: A4; margin: 0; > @media print html, body width: 210mm; height: 297mm; > .main-page margin: 0; border: initial; border-radius: initial; width: initial; min-height: initial; box-shadow: initial; background: initial; page-break-after: always; > >
html> head> title>A4 Page Using CSStitle> link rel="stylesheet" type="text/css" href="print.css"> head> body> div class="main-page"> div class="sub-page"> h3 align='center'>A4 Page in Portrait.(210mm X 297mm)h3> div> div> body> html>
Печать 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() . Возможны следующие варианты: Запуск печати по клику на ссылку:
Следующий вариант – пользователь переходит на следующую страницу, где сразу начинается печать, после пользователь возвращается на исходную.
И последний вариант – печать происходит в отдельной вкладке браузера, после печати она автоматически закрывается.
CSS to set A4 paper size
I need simulate an A4 paper in web and allow to print this page as it is show on browser (Chrome, specifically). I set the element size to 21cm x 29.7cm, but when I send to print (or print preview) it clip my page. See this Live example!
body < margin: 0; padding: 0; background-color: #FAFAFA; font: 12pt "Tahoma"; >* < box-sizing: border-box; -moz-box-sizing: border-box; >.page < width: 21cm; min-height: 29.7cm; padding: 2cm; margin: 1cm auto; border: 1px #D3D3D3 solid; border-radius: 5px; background: white; box-shadow: 0 0 5px rgba(0, 0, 0, 0.1); >.subpage < padding: 1cm; border: 5px red solid; height: 256mm; outline: 2cm #FFEAEA solid; >@page < size: A4; margin: 0; >@media print < .page < margin: 0; border: initial; border-radius: initial; width: initial; min-height: initial; box-shadow: initial; background: initial; page-break-after: always; >>
- Chrome: clipping page, double page (it’s just what I need it to work)
- Firefox: it works perfectly.
- IE10: believe it or not, it’s perfect!
- Opera: very buggy on print preview
3 Answers 3
I looked into this a bit more and the actual problem seems to be with assigning initial to page width under the print media rule. It seems like in Chrome width: initial on the .page element results in scaling of the page content if no specific length value is defined for width on any of the parent elements ( width: initial in this case resolves to width: auto . but actually any value smaller than the size defined under the @page rule causes the same issue).
So not only the content is now too long for the page (by about 2cm ), but also the page padding will be slightly more than the initial 2cm and so on (it seems to render the contents under width: auto to the width of ~196mm and then scale the whole content up to the width of 210mm ~ but strangely exactly the same scaling factor is applied to contents with any width smaller than 210mm ).
To fix this problem you can simply in the print media rule assign the A4 paper width and hight to html, body or directly to .page and in this case avoid the initial keyword.
DEMO
@page < size: A4; margin: 0; >@media print < html, body < width: 210mm; height: 297mm; >/* . the rest of the rules . */ >
This seems to keep everything else the way it is in your original CSS and fix the problem in Chrome (tested in different versions of Chrome under Windows, OS X and Ubuntu).
CSS to specify full page width at printing?
I have an html page that is printed pretty well thanks to print specific styling except for one thing : it does not use the full width of the page. In other words, I would like the page to be scaled to fill the page. Is it possible to obtain that result using css styles ?
2 Answers 2
actually you can, with the @page css rule, although it can change a bit between browser implementation.
You can set this in your css:
This will set the size of the page as A4 with no margins
I know in IE you cannot control things such as the default page margins that are set via the print dialog. These are usually 2cm and can only be overriden by the actual user in the print dialog. Other than that setting the main containers (html, body, etc.) to be width:100% and margin and padding to be 0 is the only other thing that you can do. Remember though that the margin set in CSS for html/body are within the print area of the page as defined in the print settings for the user.
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.24.43543
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.