How to make a HTML Page in A4 paper size page(s)?
Asked Answered
T

16

527

Is it possible to make a HTML page behave, for example, like a A4-sized page in MS Word?

Essentially, I want to be able to show the HTML page in the browser, and outline the content in the dimensions of an A4 size page.

For the sake of simplicity, I'm assuming that the HTML page will only contain text (no images etc.) and there will be no <br> tags for example.

Also, when the HTML page is printed, it would come out as A4-sized paper pages.

Toenail answered 27/7, 2010 at 7:26 Comment(4)
You can: github.com/delight-im/HTML-Sheets-of-PaperPlashy
Possible dupe of: https://mcmap.net/q/74956/-css-to-set-a4-paper-sizeRaveaux
The real "HTML for print" is comig! See all history at https://mcmap.net/q/45951/-use-of-xsl-fo-css3-instead-of-css2-to-create-paginated-documents-like-pdf/287948 and W3C's CSS level 3 fragmentation module, that is coming!Thrasher
What was the intention to do that? Are leaving MS Office for web technologies? At least that what I'm trying but still need some input how. Answering that would finish the story what was begun by this question.Frenum
C
443

Ages ago, in November 2005, AlistApart.com published an article on how they published a book using nothing but HTML and CSS. See: http://alistapart.com/article/boom

Here's an excerpt of that article:

CSS2 has a notion of paged media (think sheets of paper), as opposed to continuous media (think scrollbars). Style sheets can set the size of pages and their margins. Page templates can be given names and elements can state which named page they want to be printed on. Also, elements in the source document can force page breaks. Here is a snippet from the style sheet we used:

@page {
    size: 7in 9.25in;
    margin: 27mm 16mm 27mm 16mm;
}

Having a US-based publisher, we were given the page size in inches. We, being Europeans, continued with metric measurements. CSS accepts both.

After setting the up the page size and margin, we needed to make sure there are page breaks in the right places. The following excerpt shows how page breaks are generated after chapters and appendices:

div.chapter, div.appendix {
    page-break-after: always;
}

Also, we used CSS2 to declare named pages:

div.titlepage {
    page: blank;
}

That is, the title page is to be printed on pages with the name “blank.” CSS2 described the concept of named pages, but their value only becomes apparent when headers and footers are available.

Anyway…

Since you want to print A4, you'll need different dimensions of course:

@page {
    size: 21cm 29.7cm;
    margin: 30mm 45mm 30mm 45mm;
     /* change the margins as you want them to be. */
}

The article dives into things like setting page-breaks, etc. so you might want to read that completely.

In your case, the trick is to create the print CSS first. Most modern browsers (>2005) support zooming and will already be able to display a website based on the print CSS.

Now, you'll want to make the web display look a bit different and adapt the whole design to fit most browsers too (including the old, pre 2005 ones). For that, you'll have to create a web CSS file or override some parts of your print CSS. When creating CSS for web display, remember that a browser can have ANY size (think: “mobile” up to “big-screen TVs”). Meaning: for the web CSS your page-width and image-width is best set using a variable width (%) to support as many display devices and web-browsing clients as possible.

EDIT (26-02-2015)

Today, I happened to stumble upon another, more recent article at SmashingMagazine which also dives into designing for print with HTML and CSS… just in case you could use yet-another-tutorial.

EDIT (30-10-2018)

It has been brought to my attention in that size is not valid CSS3, which is indeed correct — I merely repeated the code quoted in the article which (as noted) was good old CSS2 (which makes sense when you look at the year the article and this answer were first published). Anyway, here's the valid CSS3 code for your copy-and-paste convenience:

@media print {
    body{
        width: 21cm;
        height: 29.7cm;
        margin: 30mm 45mm 30mm 45mm; 
        /* change the margins as you want them to be. */
   } 
}

In case you think you really need pixels (you should actually avoid using pixels), you will have to take care of choosing the correct DPI for printing:

  • 72 dpi (web) = 595 X 842 pixels
  • 300 dpi (print) = 2480 X 3508 pixels
  • 600 dpi (high quality print) = 4960 X 7016 pixels

Yet, I would avoid the hassle and simply use cm (centimeters) or mm (millimeters) for sizing as that avoids rendering glitches that can arise depending on which client you use.

Calumny answered 15/2, 2014 at 8:24 Comment(2)
@A.com There is no px as that would depend on DPI... which is why CSS supports these obvious measurement units called cm et al. I advise you to read the linked articles and/or at least my answer. Doing so you will quickly notice your question actually does not really make sense. Also, you might want to post your question as a new question if things are still unclear. This is a Q&A site, not a forum. \o/Calumny
You can just add size: A4; to the page size as described here.Springy
K
74

It would be fairly easy to force the web browser to display the page with the same pixel dimensions as A4. However, there may be a few quirks when things are rendered.

Assuming your monitors display 72 dpi, you could add something like this:

<!DOCTYPE html>
<html>
  <head>
    <style>
    body {
        height: 842px;
        width: 595px;
        /* to centre page on screen*/
        margin-left: auto;
        margin-right: auto;
    }
    </style>
  </head>
  <body>
  </body>
</html>
Krakau answered 27/7, 2010 at 7:44 Comment(4)
Following Will Dean's suggestion (which makes a lot of sense) using millimeters, you can force the browser to calculate the pixel width/height: body { height: 420mm; width: 297mm; ... }Krakau
A4 is actually 210x297 mm.Darryl
So, finally a portrait DINA4: body { height:297mm; width:210mm; margin-left:auto; margin-right:auto; }Overture
Done a fair bit of work on this now and while the 210x297 dimensions are good, they should not be considered an absolute fit for an A4 page. A good test is to print->PDF directly from Chrome and scroll through the preview page thumbs; even with no margins set, the full height must be reduced to avoid overflow -> that causes all even-numbered pages to be blank.Muezzin
P
49

A4 size is 210x297mm

So you can set the HTML page to fit those sizes with CSS:

html,body{
    height:297mm;
    width:210mm;
}
Pentha answered 1/3, 2014 at 12:49 Comment(3)
What if we have dynamic content which may be unto 3-4 or more pages?Cultivate
Perfect for styling one page.Usual
@Cultivate I think you will need to set the html, body to fit 100% of height and width, then create a custom tag or div, and define this above sizesDeleterious
F
25

Create section with each page, and use the below code to adjust margins, height and width.

If you are printing A4 size.

Then user

Size : 8.27in and 11.69 inches

@page Section1 {
    size: 8.27in 11.69in; 
    margin: .5in .5in .5in .5in; 
    mso-header-margin: .5in; 
    mso-footer-margin: .5in; 
    mso-paper-source: 0;
}

div.Section1 {
    page: Section1;
} 

then create a div with all your content in it.

<div class="Section1"> 
    type your content here... 
</div>

or

@media print {
    .page-break { 
        height: 0; 
        page-break-before: always; 
        margin: 0; 
        border-top: none; 
    }
}

body, p, a,
span, td { 
    font-size: 9pt;
    font-family: Arial, Helvetica, sans-serif;
}

body {
    margin-left: 2em; 
    margin-right: 2em;
}

.page {
    height: 947px;
    padding-top: 5px;
    page-break-after: always;   
    font-family: Arial, Helvetica, sans-serif;
    position: relative;
    border-bottom: 1px solid #000;
}
Fortuitism answered 31/1, 2013 at 8:28 Comment(4)
Are you sure it's working? I could not reproduce this in the latest Firefox and Chrome.Kierkegaardian
yes, mostly I am doing development for chrome... working fine with me.Fortuitism
I cannot get @page Section1 to work with Chrome 41.0.2272.77. Are you really sure that your answer works? Try e.g. to visit data:text/html,<style>@page x{size:100pt 200pt}</style><div style="page:x">x</div> and open a print preview. I see no difference between that and data:text/html,x. When I replace @page x with @page, then it works, but that is not a page-specific selector.Trimming
For those not used to putting CSS in documents (as myself at the time of the writing), you put this code in <style></style> tags and then call the div (e.g. <div class=page> Stuff </div><div class=page> More stuff</div>) where "Stuff" and "more stuff" are content that is to be contained in a single page.Shock
M
19

I saw this solution after searching at google, search for "A4 CSS page template" (codepen.io). It shows an A4 (A3,A5, also portrait) sized area in the browser, using the <page> tag. Inside this tag the content is shown, but absolute position is still with respect to browser area.

body {
  background: rgb(204,204,204); 
}
page {
  background: white;
  display: block;
  margin: 0 auto;
  margin-bottom: 0.5cm;
  box-shadow: 0 0 0.5cm rgba(0,0,0,0.5);
}
page[size="A4"] {  
  width: 21cm;
  height: 29.7cm; 
}
page[size="A4"][layout="portrait"] {
  width: 29.7cm;
  height: 21cm;  
}
@media print {
  body, page {
    margin: 0;
    box-shadow: 0;
  }
}
<page size="A4">A4</page>
<page size="A4" layout="portrait">A4 portrait</page>

This works for me without any other css/js-library to be included. Works for current browsers (IE, FF, Chrome).

Musette answered 26/3, 2017 at 9:4 Comment(6)
Using this example with FF 53.0.3 and putting two landscape pages after one another doesn't work. Looks fine in the regular view, but when selecting Print preview, it expands to 3 pages.Cytochemistry
Don't mean to drag old cows out of the trench, but I believe box-shadow should be box-shadow: none; and not 0Mood
its works for me and I have to change the the heightBarbel
What if we have dynamic content which may be unto 3-4 or more pages?Cultivate
And how do you print (save as pdf) this mixed landscape and portrait orientation?Vena
@Cultivate For dynamic content, eg formatting a long list of data into HTML, I'm using Python and Jinja2. I got a for loop which chops the list into chunks and renders 1 page <div> per chunk. I believe Nunjucks could do the same thing but uses JS instead of PythonVena
F
18

Many ways to do:

Using millimeters mm:

html, body {
    width:  210mm;
    height: 297mm;
}

Using centimeters cm:

html, body {
    width:  21.0cm;
    height: 29.7cm;
}

Using points pt:

html, body {
    width:  595pt;
    height: 842pt;
}
Feat answered 20/9, 2017 at 3:4 Comment(1)
Adding here the correction for last rules: It should be in pt(point) not px(pixel). html,body{ height: 842pt; width: 595pt; }Fimbria
S
17

I've used HTML to generate reports which print-out correctly at real sizes on real paper.

If you carefully use mm as your units in the CSS file you should be OK, at least for single pages. People can screw you up by changing the print zoom in their browser, though.

I seem to remember everything I was doing was single page, so I didn't have to worry about pagination - that might be much harder.

Schooling answered 27/7, 2010 at 7:49 Comment(0)
B
11

PPI and DPI make absolutely no difference to how a document will print off a browser. the printer takes no information on screen dot pitch or the DPI of the images etc. if you are printing images they would print at a size similar in proportion to how they are displayed on screen. the print processor of the browser would increase the DPI of the images from something rather low like 72dpi to whatever DPI the rest of the document is. say the image displays as half a page wide, then its about 4" wide physically. the pixel width of the image would be approx 300px to display correctly in the browser. by the time it prints at a nominal 300DPI, the processor has added pixels and the image will grow to around 1200px which at 300 DPI is 4".

when it comes to vector or non pixel based elements like text, the printer chooses its own DPI from the driver which doesnt relate to screen dot pitch or browser width etc. if the browser is 3000px wide, the print processor will wrap text as appropriate.

heres what makes it hard about creating print displays: each browser and printer will interpret text sizes (pt, em, px) and spacing in its own way. depending on what printer, browser and maybe even OS you use, you will get a different amount of lines and characters per page. so even if you test on your computer using your browser and printer and figure out that you can display the text in a box at 640x900px and its perfect on print, the next guy who tries to print will possibly get it printing differently. there really is no way to force each printer and browser to get it identical each time.

forget pixels and moreso forget DPI, the only thing you could use pixels for is setting a table width that simulates the width of a printable area on your printer. in that case i found that 640px wide is close.

Busse answered 3/6, 2011 at 23:3 Comment(1)
Read many pages and they all suggest that increasing DPI will result in a smaller size when printing ( 3000px / 300dpi = 10 inch). But when printing from my chrome browser, 600 DPI and 1200 DPI leads to exactly the same size on paper. Was really confused until I read this!Genuine
D
11
<link rel="stylesheet" href="/css/style.css" type="text/css">
<link rel="stylesheet" href="/css/print.css" type="text/css" media="print">

In your normal style.css:

table.tableclassname {
  width: 400px;
}

In your print.css:

table.tableclassname {
  width: 16 cm;
}
Disrobe answered 16/6, 2011 at 15:57 Comment(0)
S
11

Looking for similar problem I found this - http://www.indigorose.com/forums/archive/index.php/t-13334.html

A4 is a document format, as a screen image that's going to depend on the image resolution, for example an A4 document resized to:

  • 72 dpi (web) = 595 X 842 pixels
  • 300 dpi (print) = 2480 X 3508 pixels (This is "A4" as I know it, i.e. "210mm X 297mm @ 300 dpi")
  • 600 dpi (print) = 4960 X 7016 pixels
Sama answered 3/2, 2012 at 22:36 Comment(0)
M
8

I know that this subject is quite old but I want to share my experience about that topic. Actually, I was searching a module that can help me with my daily reports. I'm writting some documentations and some reports in HTML + CSS (instead of Word, Latex, OO, ...). The objectif would be to print them on A4 paper to share it with friends, ... Instead of searching, I decided to have a small funny coding session to implement a simple lib that can handle "pages", page number, summary, header, footer, .... Finally, I did it in ~~2h and I know that's not the best tool ever but it's almost ok for my purpose. You can take a look at this project on my repo and don't hesitate to share your ideas. It's maybe not what you are searching for at 100% but I think that this module can help you.

Basically I create a page of body "width: 200mm;" and container of height: 290mm (smaller than A4). Then I used page-break-after: always; so the "print" option of the browser know when to split pages.

repo: https://github.com/kursion/jsprint

Mammilla answered 24/9, 2013 at 16:55 Comment(0)
L
5

Technically, you could, but it would take a lot of work to get all browsers to print out the page exactly as it is displayed on screen. Also, most browsers force the URL, print date and page numbering on the print-out, which is not always desired. This cannot be altered or disabled.

Instead, I would advise to create a PDF based on the contents on screen and serve the PDF for downloading and/or printing. Although most available PDF libraries are paid, there are a few free alternatives available for creating basic PDFs.

Likeness answered 27/7, 2010 at 7:40 Comment(0)
I
5

I have used 680px in commercial reports to print on A4 pages since 1998. The 700px could not fit correctly depend of size of margins. Modern browsers can shrink page to fit page on printer, but if you use 680 pixels you will print correctly in almost any browsers.

That is HTML to you Run code snippet and see de result:

window.print();
<table width=680 border=1 cellpadding=20 cellspacing=0>
<tr><th>#</th><th>name</th></tr>
<tr align=center><td>1</td><td>DONALD TRUMP</td></tr>
<tr align=center><td>2</td><td>BARACK OBAMA</td></tr>
</table>

JSFiddle:

https://jsfiddle.net/ajofmm7r/

Interjoin answered 1/6, 2017 at 13:25 Comment(1)
what's the height for a full page in px?Faradmeter
H
3

It's entirely possible to set your layout to assume the proportions of an a4 page. You would only have to set width and height accordingly (possibly check with window.innerHeight and window.innerWidth although I'm not sure if that is reliable).

The tricky part is with printing A4. Javascript for example only supports printing pages rudimentarily with the window.print method. As @Prutswonder suggested creating a PDF from the webpage probably is the most sophisticated way of doing this (other than supplying PDF documentation in the first place). However, this is not as trivial as one might think. Here's a link that has a description of an all open source Java class to create PDFs from HTML: http://www.javaworld.com/javaworld/jw-04-2006/jw-0410-html.html .

Obviously once you have created a PDF with A4 proportions printing it will result in a clean A4 print of your page. Whether that's worth the time investment is another question.

Handedness answered 27/7, 2010 at 8:21 Comment(0)
R
1
<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=windows-1252"/>
    <title>DIN A4 Page</title>
    <style type="text/css">
        @page { size: 21cm 29.7cm; margin: 2cm }
        p { line-height: 120%; text-align: justify; background: transparent }
    </style>
</head>
<body>
<p>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>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. 
</p>
</body>
</html>
Raffin answered 26/6, 2020 at 13:44 Comment(1)
I think this is missing a couple semicolons.Beseem
A
1

I know, it's been a whil, but maybe this will help. wi can use directly

@page {
    size: A4 landscape;
}

please visit this link

Auriol answered 10/7, 2023 at 8:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.