Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
300 views
in Technique[技术] by (71.8m points)

javascript - Custom page margins using print.js

I am attempting to print payment receipt using thermal POS printer using Print.js library. I can successfully print the page using the printjs. But the print comes with extra margins as per A4 page.
Is there any way to print it to fit to 58mm with to page margins?
Also it would be very helpful if any alternatives to print using JavaScript are given. Following is my work.

HTML & JS

<button id="print-receipt">print to pos</button>
<div id="invoice-print-div" class="hidden">
    <div class="text-center" style="width:58mm;background-color:red;">
        <h4>alpha</h4>
        <table border="0">
            <tr>
                <th>Item</th>
                <th>Qty</th>
                <th>Price</th>
            </tr>
            <tr>
                <td>abc</td>
                <td>1</td>
                <td>120</td>
            </tr>
            <tr>
                <td>pqr</td>
                <td>2</td>
                <td>240</td>
            </tr>
            <tr>
                <td>xyz</td>
                <td>4</td>
            <td>360</td>
            </tr>
        </table>
    </div>
</div>
<script>
$("#print-receipt").on("click", function() {
    printJS("invoice-print-div", "html");
});
</script>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

1- Instead of using printJS() with the default two arguments, you can pass an object as argument so:

printJS('invoice-print-div', 'html'); should be replaced with:

printJS({printable: 'invoice-print-div', type: 'html',style: ['@page { size: A4; margin: 0mm;} body {margin: 0;} h4 {margin:0}'], targetStyles: ['*']});

Please note that when it comes to actual printing, the property style in the argument object is where you can pass your custom style that should be applied to the html being printed.

I have made a demo in stackblitz Please do check it out.

For more information you can check PrintJS configuration options

2- As you ask for some alternatives of PrintJS, You can checkout jsPDF Library and here some explanations about it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...