ใช้ javascript สั่ง print เว็บเพจออกทางเครื่องพิมพ์

print button by javascript
print button by javascript

เพื่อนต้องการสั่งพิมพ์ (print) ข้อมูลออกทางเครื่องพิมพ์
ไปทางกระดาษ A4 แต่ข้อมูลชุดเต็มมีจำนวนเขตข้อมูลมาก
จึงต้องตัดเขตข้อมูลที่ไม่ใช่สาระสำคัญออก
แล้วนำเสนอผ่านเว็บเพจใหม่อีกรอบ แทนข้อมูลชุดเต็ม

การนำออกกระดาษ A4 ก็ทำโดยเพิ่มปุ่ม print ทางเว็บเพจ
เมื่อกดปุ่ม print ก็จะสั่งพิมพ์ออกทางเครื่องพิมพ์ (printer)
เลือกขนาดกระดาษตามสะดวก
น่าจะเป็นทางออกที่ง่าย สำหรับผม และผู้สืบค้น
ที่มองเห็นปุ่มกด แล้วสั่งพิมพ์ผลทางเครื่องพิมพ์

button to print
button to print

[อธิบายตัวอย่าง code]
1. กำหนดส่วนของ div ให้มีปุ่มสำหรับสั่งพิมพ์
2. เหตุการณ์ onclick จะเรียกใช้ myFunction()
3. ใน Script จะสั่งพิมพ์ด้วย window.print() ก็จะเรียกบริการ print ของ window ขึ้นมา
4. ก่อนพิมพ์ก็สั่งซ่อนส่วนของ div
5. หลังพิมพ์ก็สั่งแสดงส่วนของ div อีกครั้ง

<div id=”prt”>
<button onclick=”myFunction()”>Print this page</button>
</div>
<script>
function myFunction() {
document.getElementById(“prt”).style.visibility=’hidden’;
window.print();
document.getElementById(“prt”).style.visibility=’visible’;
}
</script>

Author: บุรินทร์ รุจจนพันธุ์

I am Lecturer, Developer, Researcher, Columnist, Writer, Photographer, and Webmaster - L@mpang man

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.