JavaScript printメソッド - ブラウザから印刷する方法

JavaScriptのwindow.print()メソッドを使ってWebページを印刷する方法を詳しく解説。基本的な使い方から印刷前の調整、CSSでの印刷レイアウト制御まで初心者向けに説明します。

Learning Next 運営
26 分で読めます

みなさん、Webサイトに印刷機能を付けたいと思ったことはありませんか?

「ボタンを押したら印刷できるようにしたい」「レポートや帳票を印刷できるようにしたい」

こんな要求は、Web開発でとてもよくあることですよね。 実は、JavaScriptを使うことで簡単に印刷機能を実装できるんです。

この記事では、JavaScriptのprint()メソッドを使った印刷機能の実装方法を初心者向けに分かりやすく解説します。 基本的な使い方から実践的な活用例まで、一緒に学んでいきましょう!

print()メソッドって何?基本を知ろう

print()メソッドの正体

**window.print()**は、現在のページの印刷ダイアログを表示するJavaScriptメソッドです。

簡単に言うと、「印刷する?」という画面を出してくれる便利な機能なんです。 ボタンひとつで印刷ができるようになります。

// 最もシンプルなprint()の使用例
function printPage() {
window.print();
}
console.log('print()メソッドの特徴:');
console.log('- ブラウザの印刷ダイアログを開く');
console.log('- ユーザーが印刷設定を調整できる');
console.log('- 印刷またはキャンセルを選択可能');
console.log('- 全ブラウザでサポートされている');

このメソッドは非常にシンプルで、1行のコードで印刷機能を実装できます。

実際に使ってみよう

HTMLボタンと組み合わせた基本的な例を見てみましょう。

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>印刷機能の実装例</title>
</head>
<body>
<div class="content">
<h1>印刷したいコンテンツ</h1>
<p>このページは印刷機能のデモです。</p>
<p>印刷ボタンを押すと、印刷ダイアログが表示されます。</p>
<!-- 印刷ボタン -->
<button onclick="printPage()" class="print-button">
📄 このページを印刷
</button>
</div>
<script>
function printPage() {
// 印刷ダイアログを表示
window.print();
}
console.log('印刷機能が利用可能です');
</script>
</body>
</html>

このように、window.print()を呼び出すだけで印刷機能が動作します。 とても簡単ですね。

より親切な印刷機能を作ろう

印刷前に確認を取る

ユーザーに印刷の確認を求める機能を追加してみましょう。

// 印刷前の確認機能
function printWithConfirmation() {
const userConfirmed = confirm('このページを印刷しますか?');
if (userConfirmed) {
console.log('ユーザーが印刷を承認しました');
window.print();
} else {
console.log('印刷がキャンセルされました');
}
}
// より丁寧な確認ダイアログ
function printWithDetailedConfirmation() {
const confirmation = confirm(
'印刷を実行します。
' +
'印刷設定を確認してから印刷してください。
' +
'続行しますか?'
);
if (confirmation) {
try {
window.print();
console.log('印刷ダイアログを表示しました');
} catch (error) {
console.error('印刷でエラーが発生しました:', error);
alert('印刷でエラーが発生しました。ブラウザの印刷機能をお試しください。');
}
}
}

この方法で、意図しない印刷を防げます。

より見た目の良い確認画面も作れます。

// カスタム確認モーダル(より高度な実装)
function showPrintModal() {
const modal = document.createElement('div');
modal.innerHTML = `
<div style="
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0,0,0,0.5);
display: flex;
justify-content: center;
align-items: center;
z-index: 9999;
">
<div style="
background: white;
padding: 20px;
border-radius: 8px;
text-align: center;
max-width: 400px;
">
<h3>印刷の確認</h3>
<p>このページを印刷しますか?</p>
<button id="confirmPrint" style="margin: 5px; padding: 10px 20px;">
印刷する
</button>
<button id="cancelPrint" style="margin: 5px; padding: 10px 20px;">
キャンセル
</button>
</div>
</div>
`;
document.body.appendChild(modal);
document.getElementById('confirmPrint').onclick = () => {
document.body.removeChild(modal);
window.print();
};
document.getElementById('cancelPrint').onclick = () => {
document.body.removeChild(modal);
};
}

印刷の状態を検知しよう

印刷の開始や終了を検知する機能を実装してみましょう。

// 印刷イベントの監視
window.addEventListener('beforeprint', function() {
console.log('印刷準備が開始されました');
// 印刷前の処理
showPrintPreparation();
});
window.addEventListener('afterprint', function() {
console.log('印刷処理が完了しました');
// 印刷後の処理
hidePrintPreparation();
trackPrintAction();
});
function showPrintPreparation() {
// 印刷準備中のメッセージを表示
const message = document.createElement('div');
message.id = 'print-message';
message.innerHTML = '印刷準備中...';
message.style.cssText = `
position: fixed;
top: 20px;
right: 20px;
background: #4CAF50;
color: white;
padding: 10px 20px;
border-radius: 4px;
z-index: 10000;
`;
document.body.appendChild(message);
}
function hidePrintPreparation() {
// 印刷準備メッセージを削除
const message = document.getElementById('print-message');
if (message) {
document.body.removeChild(message);
}
}
function trackPrintAction() {
// 印刷アクションの追跡(アナリティクス等)
console.log('印刷アクションを記録しました');
}

印刷の各段階でユーザーにフィードバックを提供できます。

特定の部分だけ印刷する方法

部分印刷を実装しよう

ページ全体ではなく、特定の部分だけを印刷する機能です。

// 特定の要素だけを印刷する関数
function printElement(elementId) {
// 印刷したい要素を取得
const element = document.getElementById(elementId);
if (!element) {
alert('印刷対象の要素が見つかりません');
return;
}
// 元のページ内容を保存
const originalContents = document.body.innerHTML;
// ページ内容を印刷対象の要素のみに置き換え
document.body.innerHTML = element.outerHTML;
// 印刷実行
window.print();
// 元のページ内容を復元
document.body.innerHTML = originalContents;
}

このコードは少し乱暴なので、より安全な方法もあります。

// より安全な部分印刷の実装
function printElementSafely(elementId) {
const element = document.getElementById(elementId);
if (!element) {
console.error(`要素 "${elementId}" が見つかりません`);
return;
}
// 新しいウィンドウを開いて印刷
const printWindow = window.open('', '_blank');
printWindow.document.write(`
<!DOCTYPE html>
<html>
<head>
<title>印刷</title>
<style>
body { font-family: Arial, sans-serif; margin: 20px; }
@media print {
body { margin: 0; }
}
</style>
</head>
<body>
${element.outerHTML}
</body>
</html>
`);
printWindow.document.close();
// ページ読み込み完了後に印刷
printWindow.onload = function() {
printWindow.print();
printWindow.close();
};
}

この方法の方が、元のページに影響を与えません。

テーブルを美しく印刷しよう

表形式のデータを美しく印刷する機能です。

// テーブル専用の印刷機能
function printTable(tableId, title = 'データ一覧') {
const table = document.getElementById(tableId);
if (!table) {
alert('テーブルが見つかりません');
return;
}
const printWindow = window.open('', '_blank');
printWindow.document.write(`
<!DOCTYPE html>
<html>
<head>
<title>${title}</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
}
h1 {
text-align: center;
color: #333;
margin-bottom: 30px;
}
table {
width: 100%;
border-collapse: collapse;
margin-bottom: 20px;
}
th, td {
border: 1px solid #ddd;
padding: 8px;
text-align: left;
}
th {
background-color: #f2f2f2;
font-weight: bold;
}
.print-info {
font-size: 12px;
color: #666;
text-align: center;
margin-top: 30px;
}
</style>
</head>
<body>
<h1>${title}</h1>
${table.outerHTML}
<div class="print-info">
印刷日時: ${new Date().toLocaleString('ja-JP')}
</div>
</body>
</html>
`);
printWindow.document.close();
printWindow.onload = function() {
printWindow.print();
printWindow.close();
};
}

データの種類に応じた最適な印刷レイアウトを提供できます。

CSSで印刷を美しくしよう

印刷専用のスタイルを設定

@media printを使用して、印刷時のレイアウトを制御しましょう。

/* 印刷専用のCSS設定 */
@media print {
/* 不要な要素を非表示 */
.no-print,
.print-button,
.navigation,
.sidebar,
.footer {
display: none !important;
}
/* ページ設定 */
@page {
margin: 2cm;
size: A4;
}
/* 文字色を黒に統一(インク節約) */
body {
color: black !important;
background: white !important;
}
/* リンクの装飾を削除 */
a {
color: black !important;
text-decoration: none !important;
}
/* 画像のサイズ調整 */
img {
max-width: 100% !important;
height: auto !important;
}
/* 印刷時のみ表示する要素 */
.print-only {
display: block !important;
}
}
/* 通常時は非表示、印刷時のみ表示 */
.print-only {
display: none;
}

このスタイルにより、印刷時の見た目を最適化できます。

JavaScriptで動的にスタイル調整

印刷前にスタイルを動的に調整する機能です。

// 印刷前の動的スタイル調整
function enhancedPrint() {
// 印刷前の処理
preparePrintStyles();
// 印刷実行
window.print();
// 印刷後の処理(少し遅延させて実行)
setTimeout(() => {
restoreOriginalStyles();
}, 1000);
}
let originalStyles = {};
function preparePrintStyles() {
console.log('印刷用スタイルを適用中...');
// ナビゲーションを一時的に非表示
const navigation = document.querySelector('.navigation');
if (navigation) {
originalStyles.navigation = navigation.style.display;
navigation.style.display = 'none';
}
// コンテンツエリアの幅を調整
const content = document.querySelector('.content');
if (content) {
originalStyles.contentWidth = content.style.width;
content.style.width = '100%';
}
// 印刷用の情報を追加
addPrintInfo();
}
function restoreOriginalStyles() {
console.log('元のスタイルを復元中...');
// ナビゲーションの表示を復元
const navigation = document.querySelector('.navigation');
if (navigation && originalStyles.navigation !== undefined) {
navigation.style.display = originalStyles.navigation;
}
// コンテンツエリアの幅を復元
const content = document.querySelector('.content');
if (content && originalStyles.contentWidth !== undefined) {
content.style.width = originalStyles.contentWidth;
}
// 印刷用情報を削除
removePrintInfo();
// スタイル記録をクリア
originalStyles = {};
}
function addPrintInfo() {
// 印刷日時の情報を追加
const printInfo = document.createElement('div');
printInfo.id = 'print-timestamp';
printInfo.innerHTML = `
<div style="
position: fixed;
bottom: 10px;
right: 10px;
font-size: 10px;
color: #666;
">
印刷日時: ${new Date().toLocaleString('ja-JP')}
</div>
`;
document.body.appendChild(printInfo);
}
function removePrintInfo() {
const printInfo = document.getElementById('print-timestamp');
if (printInfo) {
document.body.removeChild(printInfo);
}
}

印刷時の見た目を動的に最適化できます。

実際に使える印刷機能を作ろう

レシート印刷機能

実際のWebアプリケーションでよく使われるレシート印刷です。

// レシート印刷機能
function printReceipt(orderData) {
const receiptHTML = `
<!DOCTYPE html>
<html>
<head>
<title>レシート</title>
<style>
body { font-family: monospace; width: 300px; margin: 0; }
.header { text-align: center; border-bottom: 1px dashed #000; padding-bottom: 10px; }
.item { display: flex; justify-content: space-between; margin: 5px 0; }
.total { border-top: 1px dashed #000; padding-top: 10px; font-weight: bold; }
@media print { body { width: auto; } }
</style>
</head>
<body>
<div class="header">
<h3>お買い上げレシート</h3>
<p>${new Date().toLocaleString('ja-JP')}</p>
</div>
${orderData.items.map(item => `
<div class="item">
<span>${item.name}</span>
<span>¥${item.price.toLocaleString()}</span>
</div>
`).join('')}
<div class="total">
<div class="item">
<span>合計</span>
<span>¥${orderData.total.toLocaleString()}</span>
</div>
</div>
</body>
</html>
`;
const printWindow = window.open('', '_blank', 'width=400,height=600');
printWindow.document.write(receiptHTML);
printWindow.document.close();
printWindow.print();
}

この関数を呼び出すことで、レシート風の印刷ができます。

印刷プレビュー機能

印刷前に内容を確認できるプレビュー機能です。

// 印刷プレビュー機能
function showPrintPreview(elementId) {
const element = document.getElementById(elementId);
if (!element) return;
// プレビューモーダルを作成
const modal = document.createElement('div');
modal.innerHTML = `
<div style="
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0,0,0,0.8);
z-index: 10000;
display: flex;
justify-content: center;
align-items: center;
">
<div style="
background: white;
width: 80%;
max-width: 800px;
height: 80%;
border-radius: 8px;
display: flex;
flex-direction: column;
">
<div style="
padding: 20px;
border-bottom: 1px solid #ddd;
display: flex;
justify-content: space-between;
align-items: center;
">
<h3>印刷プレビュー</h3>
<div>
<button id="printBtn" style="margin-right: 10px; padding: 8px 16px;">
印刷実行
</button>
<button id="closeBtn" style="padding: 8px 16px;">
閉じる
</button>
</div>
</div>
<div style="
flex: 1;
overflow: auto;
padding: 20px;
background: #f5f5f5;
">
<div style="
background: white;
padding: 20px;
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
max-width: 210mm;
margin: 0 auto;
">
${element.outerHTML}
</div>
</div>
</div>
</div>
`;
document.body.appendChild(modal);
// イベントリスナー設定
modal.querySelector('#printBtn').onclick = () => {
document.body.removeChild(modal);
printElement(elementId);
};
modal.querySelector('#closeBtn').onclick = () => {
document.body.removeChild(modal);
};
}

この機能により、印刷前に内容を確認できます。

まとめ

JavaScriptのprint()メソッドを使った印刷機能について学んできました。

重要なポイントをおさらいしましょう。

  • window.print(): シンプルで確実な印刷ダイアログ表示
  • 部分印刷: 特定の要素だけを印刷する柔軟性
  • CSS制御: @media printでの印刷レイアウト最適化
  • ユーザビリティ: 確認ダイアログや状態表示での親切な設計

実践で役立つテクニックも身につきました。

  • 印刷前の確認機能
  • 印刷状態の検知とフィードバック
  • レシートや帳票の印刷機能
  • 印刷プレビューの実装

重要なのは、ユーザーのことを考えた印刷機能を提供することです。 単に印刷ダイアログを表示するだけでなく、印刷に適したレイアウトへの調整や、不要な要素の非表示化など、使いやすさを追求することが大切です。

印刷機能は地味に見えますが、業務効率化に大きく貢献する重要な機能です。 ぜひこれらの知識を活用して、ユーザーにとって価値のある印刷機能を実装してみてくださいね!

関連記事