“This article has participated in the good article call order activity, click to see: back end, big front end double track submission, 20,000 yuan prize pool for you to challenge!”
preface
A previous technology share, accidentally deleted, change to re-post.
First blog: Jun Jie’s learning base Welcome star, study together! Blog home has blown water group, scan code to join!
For many in the background business, the printing scene is very common. In view of the personal encounter, and some of the existing scheme comparison, summarize a wave of π (there is a PPT version at the end of the article, need to leave a message), hope to help the same headache you. Without further ado, start talking.
First, browser printing
1. Advantages and disadvantages
Window.print (), document.execCommand(‘print ‘) call the browser to print
Differences between browsers: Safari and Chrome both pop up a print preview window, while FireFox (older versions) and IE don’t preview and let you select a printer
However, although using the browser to print directly saves trouble, it has many problems and cannot meet our printing needs:
- 1, print is the whole page, can not print
Local content
; - 2. Print does not support customization
Paging behavior
Is not supported by defaultBatch print
; - 3. When printing
There's something wrong with the style
What you see is not what you get; - 4. Print can be accurately identified
Style unit
Are absolute units (such as PT, mm, cm), and identifying different printers with relative units may yield unexpected results;
2. Here comes the problem
How to achieve local printing? π€
(1) the innerHtml
If you don’t need to think about the experience and don’t use much in your project, try π
Function innerHtmlPrint () {/ / cache the page content const bodyHtml = window. The document. The body. The innerHTML; // GetDom const printContentHtml = document.getelementById ("print").innerHTML; // getDom const printContentHtml = document.getelementById ("print").innerHTML; / / replace page content window. The document. The body. The innerHTML = printContentHtml; Window.print (); window.print(); / / restore page content window. The document. The body. The innerHTML = bodyHtml; // The page event will be lost, need to refresh window.location.reload(); }Copy the code
(2) the iframe
A little more complicated is to add the printed content to the iframe, and then print the entire iframe. Note that some checkboxes and radios need special treatment when writing styles into the iframe.
Here I have extracted the local print of iframe used in the project. You can use the vue-iframe-printπππ plug-in to use demo directly
If you are a VUE project, just add v-print to the DOM that needs to be printed after installation. The main implementation principle is as follows (the style is omitted) :
- Create an iframe
- Example Build the iframe docTyp and head information
- Get the local DOM and insert the iframe
- window.print()
function onIframePrint(printId) { const printContentHtml = document.getElementById("printId").innerHTML; const iframe = document.createElement("iframe"); iframe.setAttribute( "style", "position:absolute; width:0px; height:0px; left:-500px; top:-500px;" ); document.body.appendChild(iframe); iframe.contentDocument.write(printContentHtml); iframe.contentDocument.close(); iframe.contentWindow.print(); document.body.removeChild(iframe); },Copy the code
(3) the canvas
Print content into a picture, twice the sharpness blur, you can use twice canvas. Disadvantages: PDF needs to be downloaded, and some product requirements require one-click printing. Html2canvas does not support IE, compatibility is also an issue
function print() { var target = document.getElementsByClassName("right-aside")[0]; target.style.background = "#FFFFFF"; html2canvas(target, { onrendered:function(canvas) { var contentWidth = canvas.width; var contentHeight = canvas.height; // A page of PDF displays the canvas height generated by the HTML page; Var pageHeight = contentWidth / 592.28 * 841.89; Var leftHeight = contentHeight; var leftHeight = contentHeight; Var position = 0; Var imgWidth = 595.28; var imgWidth = 595.28; var imgWidth = 595.28; Var imgHeight = 592.28/contentWidth * contentHeight; Var pageData = Canvas. ToDataURL ('image/jpeg', 1.0); var pdf = new jsPDF('', 'pt', 'a4'); // There are two heights to distinguish, one is the actual height of the HTML page, and the height of the generated PDF page (841.89) // When the content does not exceed the PDF page display range, If (leftHeight < pageHeight) {PDF. AddImage (pageData, 'JPEG', 0, 0, imgWidth, imgHeight); } else { while(leftHeight > 0) { pdf.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight) leftHeight -= pageHeight; The position - = 841.89; If (leftHeight > 0) {pdF.addpage (); } } } pdf.save("content.pdf"); }})}Copy the code
PDF turns into a picture, it’s distorted, it’s somewhat blurry, and if you’re using a needle printer, it’s almost unreadable. πΏ
Is also a long time to find the solution (perfect reduction) : π¬π¬π¬
< span style =" box-sizing: border-box; color: RGB (50, 50, 50); font-size: 13px! Important; word-break: inherit! Important; Type ="application/ PDF "SRC ="./" a.df "width="100%" height="700px" />Copy the code
Two, plug-in printing
This is usually done by embedding scripts within the project, or by installing local plug-ins, with obvious advantages and disadvantages
1, the advantages of
- Powerful, can call system low-level things, such as get the list of system printers, set the default printer, etc
- You can print without preview
2 and disadvantages
- Clients need to be installed, mostly for a fee
- Third-party plug-in, no technical support, difficult to solve problems (version problems, Chrome84 upgrade caused by certificate issues)
- Local plug-ins are available only for Windows
Our project is currently using the plug-in C-Lodop, fee, and the registration code is not known who made π there.
If it fails, it means that all printing for our project is basically useless. At present, it seems to be a purchase of permanent, do not panic π
3. Some plug-ins
Here are a few plugins for reference only:
- C-lodop: powerful, compatibility is not very good, you want to ensure the clarity of the case, no way to write CSS3, draw a rounded border is not good π€§π€§π€§, depending on the system IE version, IE9 below, the things out of the box… It is recommended that you carefully study the demo provided by the official website before using it. The principle of this plug-in is to embed a section of JS on the page and communicate with the local client through Websocket
- HttpPrinter: Similar to c-lodop
- HiPrint: no client installation required, but no NPM package, dependent on jQuery
4, make a mouth cannon πππ
In fact, if you have time, you can use nW-js and electron. Js themselves a wana, this big guy himself made a: how to use NW-JS pure front-end implementation call thermal printer to print receipts?
Three, print style
First, look at the basic page model
2, @ media print
Can control the print style, only in the print effect, can achieve some special needs.
3, @ page
Set the page size (A3, A4, A5), margin (margin), direction (auto, landscape, portrait), etc.
4, Page -break- XXX
Page -break-before(after) This parameter is used to set the paging behavior before or after an element. The value can be: * auto Default value. Insert a page break before the element if necessary. * always inserts a page break before an element. * Avoid inserting page breaks before elements. * left Enough page breaks before the element to reach a blank left page. * right Enough page breaks before the element to reach a blank right page. Inherit specifies that the page break-before property should be inherited from the parent. Page-break-inside Sets the paging behavior within an element. The values are as follows: * auto Default. Insert a page break inside the element if necessary. * Avoid inserting page breaks inside an element. Inherit: inherit the page break inside property from the parent element. Orphans sets the minimum number of rows that must be kept at the bottom of the page when paging occurs within an element. Widows Sets the minimum number of lines that must be reserved at the top of the page when paging occurs within an element.Copy the code
4. Cloud Printing (Node + IPP)
1. First explain the printer type π€π€π€
(1) Laser printer
A common office printer used to print common document materials. Using laser heating to fix toner on paper, so as to achieve the printing function. The usual supplies are toner, the paper used is ordinary paper, usually black and white printing. Printing speed is fast and supplies are cheap
(2) Pin printer
Generally used for printing tickets, or need to press printing paper. Print by pressing the ink from the ribbon onto the paper. The usual supplies are ribbons, the use of paper is multipaper, compared with the other two classification needle printer can be said to be the veteran level, it is the earlier type on the market. There are mainly 9 needle, 24 needle, 72 needle, 144 needle and other needle printers. It is characterized by simple structure, mature technology, good performance – price ratio and low consumption cost.
(3) Thermal printer
Use special paper to display the information to be printed at high temperature. Mainly used for printing receipts.
(4) inkjet printer
Generally used for printing color materials. To print by spraying ink on paper. The usual supplies are ink, the paper used is ordinary paper, can generally print color. (Another consumable is ink cartridge, some models do not need to be replaced frequently)
2. Node + IPP
First understand the two prefixes: π€π€π€
-
Internet Printing Protocol (IPP; The Internet Printing Protocol is a standard network Protocol for Printing over the Internet. It allows users to do remote Printing and manage Printing over the Internet. Users can control the type of paper, resolution and other parameters used by the printer through the relevant interface.
-
A headless browser is a browser in which we use scripts to perform the above process, simulating a real browser usage scenario.
If you don’t know about Puppeteer, check out this article: A First Look at Puppeteer, a Headless browser – Ant Financial
3. Flowchart of cloud printing
At present, our group’s cloud printing has been launched, but there are many limitations, and it has not been used much. If you are interested in it, please refer to another articleEgg + Puppeteer (Html to PDF)
Five, some thinking
Window.print (); window.print();
2. According to the business requirements, if the network printer needs non-trace printing, node+ IPP cloud printing can be adopted, which is not difficult to achieve. π΅
3, the back-end to the source file, the requirements are not high can use PDFJS to canvas, the requirements are high use
4, pdf2htmlEX plug-in, PDF to HTML, 4 years ago last maintenance, can try
Also looked up a lot of information, at present the web printing part of the feeling or window.print is more practical, also did not find any open source projects. Which big guy has it? Recommended it
Vi. Reference materials:
- In-depth study of network communication protocols caused by the printer TCP protocol: from TCP to universal printing, cloud printing
- A first look at The headless browser Puppeteer
- Browser printing project research
- Front end one click print solution
- Can PDF be converted to HTML? How to convert?
7. PPT, if necessary, can be sent to email
Eight, past review
- A good summary of TypeScript
- A vueCoder summary of React basics 180+ ππΏ
- Vue rereact is not entirely north 600+ ππΏ
- Job-hopping comes quickly, face classics & resources sharing 1100+ ππΏ
- A year and a half front end of the road 300+ ππΏ
- Vue2.x advanced question, how many can you answer 400+ ππΏ
- Talk about front-end performance optimization 1300+ ππΏ
- Egg + Puppeteer to achieve Html to PDF(open source) 50+ ππΏ