This is the 11th day of my participation in the Gwen Challenge in November. Check out the details: The last Gwen Challenge in 2021

Style printing in browsers has always been a tricky issue (especially in the IE era), but with the development of the modern Web, there are many new features for controlling page style when printing. Here’s how to control print styles in your browser. And, finally, several possible ways to disable user printing!

There is a big gap between actual browser printing and directly calling the printer driver through the local application, especially the printing clarity caused by fonts.

Another nice feature of browser printing is the ability to “save as PDF” when printing, especially if you want to save web content as A PDF format for use. This feature is not to be missed (printing as A PDF will not have too much deviation in style, so it is easy to save and browse).

For example, save the web page as PDF, make electronic file (Ctrl + P or right click the current web page -> menu and choose “Print”, you can open the print dialog box) :

CSS for printing

Most commonly, some content may be hidden when printing, such as footer, header, sidebar and advertising promotion content. You even need to set up completely different styles and fonts for printing.

The media property of the style application

For permitted styles, you can specify the media property of the style or link tag as “print”, indicating that the style is applied to the print style

As follows:

<link rel="stylesheet" src="print.css" type="text/css" media="print" />
Copy the code

CSS external files that specify media=”print” (link introduced) will only be downloaded and rendered by the browser at print time.

or

<style type="text/css" media="print">
    / *... * /
</style>
Copy the code

@media Print Media query

In CSS, use the media query @media Print to apply styles only to print.

@media print {
  / *... * /
}
Copy the code

The easiest way to keep your page style consistent with your print style

The easiest way to be consistent is to use the media=”all” attribute, which means that all devices use the current style

<link rel="stylesheet" src="print.css" type="text/css" media="all" />
Copy the code

or

<style type="text/css" media="all">
    / *... * /
</style>
Copy the code

Link processing during printing

Links are almost everywhere in HTML, and the A tag introduces a hyperlink. However,

If used for printing, only the text of the link is displayed by default and the actual content of the link, the URL path, is lost.

To keep the url of the link for printing, use the: After pseudo-class and add content to display the URL after the link.

As follows, an A tag applies the printed style:

@media print {
    a[href*='/ /']:after {
        content:"(" attr(href) ")";
        color: red; }}Copy the code

A [href*=’//’] only display external links (or url standard links) after the link text when printing (as shown in the figure above).

Internal links are usually used for navigation or internal indexing and generally do not need to be printed. If you want the URLS of all links to appear in print, you can change them to the following style:

@media print {
    a:after {
        content:"(" attr(href) ")"; }}Copy the code

Page break

If you want to break a page after or before an element, you can use the page-break-after and page-break-before attributes.

For example, to implement paging printing for every three div elements:

div:nth-child(3n){
    page-break-after: always;
}
Copy the code

page-break-before: always; Again, page in front of the element.

The values of page-break-before and page-break-after can be auto, always, avoid, left, or right.

Avoid breaking inside elements (especially images)

One of the most important problems is the element interruption, due to the height span of the element, is interrupted to display in two pages, especially pictures, part of the previous page, the other part of the next page. Obviously not (unless you want to).

page-break-inside: avoid; Prevents elements or images from breaking up internally and showing on two pages.

img {
  page-break-inside: avoid;
}

div {
  page-break-inside: avoid;
}
Copy the code

The @page rule applied to document printing

The @page rule is used to print documents, but can only modify attributes such as margin,orphans,widow, and page interrupts. You also need to consider whether your browser supports it.

Page model

@page corresponds to a page frame model as follows:

It maps from an HTML document.

Model with page margins:

Page margins

Page margin unit for paper printing. Cm or in is recommended.

@page {
    margin-top: 2cm;
    margin-bottom: 2cm;
    margin-left: 2cm;
    margin-right: 2cm;
}
Copy the code

@ page pseudo-classes

  • :firstThe home page style applied to printing
@page :first{
    margin-left: 5cm;
    margin-top: 8cm;
}
Copy the code
  • @page :left å’Œ @page: rightStyles in double-sided printing

@page :left all left pages in double-sided printing; @page: Right all right pages in double-sided printing.

@page :left {
  margin-left: 3cm;
  margin-right: 4cm;
}

@page :right {
  margin-left: 4cm;
  margin-right: 3cm;
}
Copy the code
  • :blankPrint blank pages in the document
@page :blank {
  @top-center { 
        content: "This page is intentionally left blank"; }}Copy the code

Page Box size

Size Specifies the size of the paper, as in:

@page {
  size: A4;
}
Copy the code
@page {
  size: A5;
}
Copy the code

Margin @ rules

The Margin at rule only applies to @page media and is currently defined by the CSS standard and may be removed in the future. Understand.

For example, specify margin@ to display content:

@page {
  size: A4;
  margin: 10%;

  @top-left {
    content: "My Story.";
  }
  @bottom-right {
    content: "Pages:" counter(page); }}Copy the code

All possible reference rules are as follows:

@top-left-corner
@top-left
@top-center
@top-right
@top-right-corner
@right-top
@right-middle
@right-bottom
@bottom-right-corner
@bottom-right
@bottom-center
@bottom-left
@bottom-left-corner
@left-bottom
@left-center
@left-top
Copy the code

Debug print rendering

In developer tools, a way to simulate a print layout is provided.

F12 Open the Developer tool and click on the thumbprint on the right side, and click on “More Tools” and “draw”.

In the panel that opens, under the analog media type, select print to debug the print style.

How to prevent the page from printing?

In one extreme case, we sometimes don’t want the user to print the current page (this should be addressed in conjunction with not allowing users to copy the page content, not allowing developers to open tools, etc., but discussed later).

Of course, none of this can completely eliminate the user from printing, and there are many ways to bypass these restrictions, get the page content, and do whatever you need to do.

A pure CSS implementation prevents pages from printing

The solution is to set the body tag to display: None in the printed CSS style; Print the document without displaying any content on the page.

@media print {
    body { display: none; }}Copy the code

When you open the print page, it will be blank. So you can’t print.

But this is obviously not very friendly, the user sees a blank, and do not understand is not able to print. So, we can add a hint.

<body>
    <p id="print">Current page is not allowed to print!</p>
    <div id="noprint">
        <! -- Real page content -->
    </div>
</body>
Copy the code

In the main style:

#print { display: none; }
#noprint { display: block; }
Copy the code

In the printed style

@media print {
    #print { display: block; }
    #noprint { display: none; }}Copy the code

You can also put it in print.css:

<link rel="stylesheet" src="print.css" type="text/css" media="print" />
Copy the code
/* print.css file */
#print { display: block; }
#noprint { display: none; }
Copy the code

The following information is displayed:

Use js to prevent the page from printing

stopCtrl + PButtons and browser right-click menu

Because the way to print in the browser is mainly through Ctrl + P, or, right menu click “print” to achieve.

Ctrl + P determines whether to press both keys in the keypress event, and if so, calls e.preventDefault() to block execution.

window.addEventListener("keydown".function (e) {
    if(e.ctrlKey && (e.key=="p" || e.key=="P")){ e.preventDefault(); }});Copy the code

Unopen the right menu, and place the same e.preventDefault() handler in the ContextMenu event handler.

Also, in the browser’s own menu bar, there is a “print” menu that we have no control over

beforeprint 和 afterprintPrint event [Prevent print implementation]

Beforeprint and AfterPrint are two events related to printing, but cancellation is not supported.

But it can still be done with a clever combination of Document.write ().

window.addEventListener("beforeprint".function (e) {
    document.write('
      
Current page is not allowed to print!
'
); }); Copy the code

The print preview window displays “Current page is not allowed to print!” The prompt.

However, since document.write() is implemented by writing to the document, when you cancel printing, the original content is lost on the return page.

Also, clicking “Cancel Print” does not trigger the AfterPrint event. That is, there is no way to know when the user unprints.

Another workaround is to refresh the current page in the beforePrint event, because the print dialog will not open because of the refresh.

Not very elegant!

The following is achieved by refreshing the current page with JS:

window.addEventListener("beforeprint".function (e) {
    confirm("Current page is not allowed to print!");      
   
    window.location.reload();
});
Copy the code

reference

  • The CSS @page at-rule can be used to apply certain properties and at-rules on paged media.

  • How to print your HTML with style

  • @page

  • Window: beforeprint event