Using js to realize local print page

Preface

The front-end development often meets the demand of printing local pages in the work. Today, I will introduce the method of using JS to realize the local printing of page printing in the next small editing work for your reference.

text

In the development of the project, click to print, part of the content in the page needs to be printed. The implementation method is as follows
 First, wrap the content that needs to be printed: for example

html

<p>I print it</p>
    <div id="printBox">
        <table width="400" border="1">
            <thead>
                <tr>
                    <th>1</th>
                    <th>2</th>
                    <th>3</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>1.1</td>
                    <td>2.1</td>
                    <td>3.1</td>
                </tr>
                <tr>
                    <td>1.2</td>
                    <td>2.2</td>
                    <td>3.2</td>
                </tr>
            </tbody>
        </table>
    </div>
    <p>I'm printing the following</p>
    <button onclick="printDeal()">Print button</button>

When clicking the print button, perform the following methods:
js

function printDeal(){
            var printBox = document.getElementById('printBox');
            //Get the printed area html content
            var newContent =printBox.innerHTML;
            //Save the old page and return it to the page after printing.
            var oldContent = document.body.innerHTML;
            //Assign to body
            document.body.innerHTML = newContent;
            //implementwindow.printPrinting function
            window.print();
            // Reload the page to refresh the data. In case that the page cannot be operated after printing
            window.location.reload();
            document.body.innerHTML = oldContent;
            return false;
        }

The effect is as follows:

Posted by croix on Fri, 03 Apr 2020 13:19:28 -0700