諮詢專線 (04)2320-0760
資訊分享- ARTICLES -
2026 / 09 / 11

如何在網頁加入「一鍵列印圖片」按鈕?

如下圖, 當你有一張給瀏覽者列印填寫用的電子檔時, 如何讓瀏覽者直接在網頁裡快速列印
首先確認你的文章內容可以使用原始碼編輯
接下來把要列印的圖檔加到div裡, 結果如下
<div id="print-area"><img alt="" src="xxx.jpg" style="width: 1728px; height: auto;" /></div>
註:需自行注意圖片的寬高設定
接下來製作一個點擊後觸發裝置列印的按鈕, 以下方式擇一使用
效果1: 使用瀏覽器內建按鈕
<button onclick="
  var img = document.querySelector('#print-area img');
  if (!img) return;
  var f = document.createElement('iframe');
  f.style.cssText = 'position:fixed;right:0;bottom:0;width:0;height:0;border:0';
  document.body.appendChild(f);
  var d = f.contentWindow.document;
  var s = d.createElement('style');
  s.textContent = '@page{margin:1cm;}body{margin:0;text-align:center;}img{max-width:100%;height:auto;}';
  d.head.appendChild(s);
  var i = d.createElement('img');
  i.src = img.src;
  i.onload = function(){ f.contentWindow.focus(); f.contentWindow.print(); };
  d.body.appendChild(i);
  setTimeout(function(){ document.body.removeChild(f); }, 2000);
" type="button">列印報名表</button>
效果2: 自行設計按鈕 [ 列印報名表 ]
<a href="#" onclick="
  var img = document.querySelector('#print-area img');
  if (!img) return;
  var f = document.createElement('iframe');
  f.style.cssText = 'position:fixed;right:0;bottom:0;width:0;height:0;border:0';
  document.body.appendChild(f);
  var d = f.contentWindow.document;
  var s = d.createElement('style');
  s.textContent = '@page{margin:1cm;}body{margin:0;text-align:center;}img{max-width:100%;height:auto;}';
  d.head.appendChild(s);
  var i = d.createElement('img');
  i.src = img.src;
  i.onload = function(){ f.contentWindow.focus(); f.contentWindow.print(); };
  d.body.appendChild(i);
  setTimeout(function(){ document.body.removeChild(f); }, 2000);
" style="display: inline-flex; align-items: center; justify-content: center; padding: 12px 30px; color: #00f3ff; background-color: #0d1527; font-family: 'Consolas', 'Courier New', monospace, sans-serif; font-size: 16px; font-weight: bold; letter-spacing: 2px; text-decoration: none; border: 1px solid #00f3ff; border-radius: 2px; box-shadow: 0 0 12px rgba(0, 243, 255, 0.35), inset 0 0 8px rgba(0, 243, 255, 0.2); cursor: pointer;">[ 列印報名表 ] </a>
主要靠以下這段觸發列印div裡的圖片, 這裡把style與JavaScript直接混在一起, 方便使用
onclick="
  var img = document.querySelector('#print-area img');
  if (!img) return;
  var f = document.createElement('iframe');
  f.style.cssText = 'position:fixed;right:0;bottom:0;width:0;height:0;border:0';
  document.body.appendChild(f);
  var d = f.contentWindow.document;
  var s = d.createElement('style');
  s.textContent = '@page{margin:1cm;}body{margin:0;text-align:center;}img{max-width:100%;height:auto;}';
  d.head.appendChild(s);
  var i = d.createElement('img');
  i.src = img.src;
  i.onload = function(){ f.contentWindow.focus(); f.contentWindow.print(); };
  d.body.appendChild(i);
  setTimeout(function(){ document.body.removeChild(f); }, 2000);
"
CONTACT
  營業時間 W1-W5 09:00-16:00
  04-2320-0760
  台中市公益路349號7F-12