はじめに
Copy a setup prompt with the install steps and the full markdown guide for this plugin.
Set up this Capacitor plugin in the project.
Use the package manager already used by the project.
Install these package(s): `@capgo/capacitor-printer`
Run the required Capacitor sync/update step after installation.
Read this markdown guide for the full setup steps: https://raw.githubusercontent.com/Cap-go/website/refs/heads/main/apps/docs/src/content/docs/ja/docs/plugins/printer/getting-started.mdx
Use that guide for platform-specific steps, native file edits, permissions, config changes, imports, and usage setup.
If that guide references other docs pages, read them too.
-
パッケージをインストールする
Terminal window npm i @capgo/capacitor-printerTerminal window pnpm add @capgo/capacitor-printerTerminal window yarn add @capgo/capacitor-printerTerminal window bun add @capgo/capacitor-printer -
ネイティブプロジェクトと同期する
Terminal window npx cap syncTerminal window pnpm cap syncTerminal window yarn cap syncTerminal window bunx cap sync
プラグインをインポートして、さまざまな種類のコンテンツを印刷します:
import { Printer } from '@capgo/capacitor-printer';
// Print HTML contentconst printHTML = async () => { await Printer.print({ content: '<h1>Hello World</h1><p>This is a test print.</p>', name: 'test-print' });};
// Print a PDF fileconst printPDF = async () => { await Printer.print({ content: 'file:///path/to/document.pdf', name: 'my-document' });};
// Print an imageconst printImage = async () => { await Printer.print({ content: 'file:///path/to/image.jpg', name: 'my-image' });};APIリファレンス
Section titled “APIリファレンス”print(options)
Section titled “print(options)”指定されたコンテンツでネイティブの印刷ダイアログを開きます。
interface PrintOptions { content: string; // HTML string, file URI, or base64 data name?: string; // Print job name orientation?: 'portrait' | 'landscape'; grayscale?: boolean; // Print in grayscale (default: false)}
await Printer.print(options);canPrint()
Section titled “canPrint()”デバイスで印刷が利用可能かどうかを確認します。
const { value } = await Printer.canPrint();console.log('Printing available:', value);import { Printer } from '@capgo/capacitor-printer';import { Filesystem, Directory } from '@capacitor/filesystem';
export class PrintService { async checkPrintAvailability(): Promise<boolean> { const { value } = await Printer.canPrint(); return value; }
async printHTML(htmlContent: string, jobName: string = 'Document') { try { const canPrint = await this.checkPrintAvailability(); if (!canPrint) { throw new Error('Printing not available on this device'); }
await Printer.print({ content: htmlContent, name: jobName, orientation: 'portrait' }); } catch (error) { console.error('Print failed:', error); throw error; } }
async printDocument(filePath: string, jobName?: string) { await Printer.print({ content: filePath, name: jobName || 'Document' }); }
async printReceipt(receiptData: any) { const html = ` <!DOCTYPE html> <html> <head> <style> body { font-family: Arial, sans-serif; padding: 20px; } .header { text-align: center; margin-bottom: 20px; } .item { display: flex; justify-content: space-between; margin: 10px 0; } .total { font-weight: bold; font-size: 1.2em; margin-top: 20px; padding-top: 10px; border-top: 2px solid #000; } </style> </head> <body> <div class="header"> <h2>Receipt</h2> <p>Date: ${new Date().toLocaleDateString()}</p> </div> ${receiptData.items.map((item: any) => ` <div class="item"> <span>${item.name}</span> <span>$${item.price.toFixed(2)}</span> </div> `).join('')} <div class="total"> <div class="item"> <span>Total:</span> <span>$${receiptData.total.toFixed(2)}</span> </div> </div> </body> </html> `;
await this.printHTML(html, 'Receipt'); }
async printFromURL(url: string) { // Download the file first const response = await fetch(url); const blob = await response.blob(); const reader = new FileReader();
return new Promise((resolve, reject) => { reader.onloadend = async () => { try { await Printer.print({ content: reader.result as string, name: 'Downloaded Document' }); resolve(true); } catch (error) { reject(error); } }; reader.onerror = reject; reader.readAsDataURL(blob); }); }}高度な使用方法
Section titled “高度な使用方法”カスタムスタイリングでの印刷
Section titled “カスタムスタイリングでの印刷”const printStyledDocument = async () => { const html = ` <!DOCTYPE html> <html> <head> <style> @page { size: A4; margin: 2cm; } body { font-family: 'Times New Roman', serif; line-height: 1.6; } h1 { color: #333; border-bottom: 2px solid #333; padding-bottom: 10px; } .content { margin-top: 20px; } </style> </head> <body> <h1>Professional Document</h1> <div class="content"> <p>This is a professionally styled document ready for printing.</p> </div> </body> </html> `;
await Printer.print({ content: html, name: 'Styled Document', orientation: 'portrait' });};テーブルの印刷
Section titled “テーブルの印刷”const printTable = async (data: any[]) => { const tableRows = data.map(row => ` <tr> <td>${row.id}</td> <td>${row.name}</td> <td>${row.value}</td> </tr> `).join('');
const html = ` <!DOCTYPE html> <html> <head> <style> table { width: 100%; border-collapse: collapse; } th, td { border: 1px solid #ddd; padding: 8px; text-align: left; } th { background-color: #f2f2f2; font-weight: bold; } </style> </head> <body> <table> <thead> <tr> <th>ID</th> <th>Name</th> <th>Value</th> </tr> </thead> <tbody> ${tableRows} </tbody> </table> </body> </html> `;
await Printer.print({ content: html, name: 'Data Table' });};const printImageWithDetails = async (imagePath: string, title: string) => { const html = ` <!DOCTYPE html> <html> <head> <style> body { text-align: center; padding: 20px; } h2 { margin-bottom: 20px; } img { max-width: 100%; height: auto; } </style> </head> <body> <h2>${title}</h2> <img src="${imagePath}" alt="${title}" /> </body> </html> `;
await Printer.print({ content: html, name: title });};ベストプラクティス
Section titled “ベストプラクティス”- 利用可能性の確認: 印刷を試みる前に、常に印刷が利用可能かどうかを確認してください
- 有効なコンテンツ: HTMLが適切に形成されており、ファイルパスが有効であることを確認してください
- ジョブ名: ユーザーが識別しやすいように、印刷ジョブには説明的な名前を使用してください
- スタイリング: 一貫した印刷出力のために、インラインCSSまたは埋め込みスタイルを使用してください
- エラー処理: ユーザーフィードバックのために、印刷呼び出しをtry-catchブロックでラップしてください
トラブルシューティング
Section titled “トラブルシューティング”よくある問題
Section titled “よくある問題”印刷ダイアログが表示されない: canPrint()で印刷が利用可能かどうかを確認してください コンテンツが印刷されない: HTMLが有効であり、ファイルパスが正しいことを確認してください 画像が表示されない: 画像パスが絶対パスであり、ファイルがアクセス可能であることを確認してください スタイリングの問題: @page CSSルールを使用して、印刷出力をテストしてください