快速入门
复制包含安装步骤和该插件完整 Markdown 指南的配置 prompt。
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/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.
安装
“安装”章节你可以使用我们的 AI 辅助设置来安装插件。使用以下命令将 Capgo skills 添加到你的 AI 工具中:
npx skills add https://github.com/Cap-go/capgo-skills --skill capacitor-plugins然后使用以下 prompt:
Use the `capacitor-plugins` skill from `Cap-go/capgo-skills` to install the `@capgo/capacitor-printer` plugin in my project.如果你更想手动设置,请运行以下命令安装插件,并按照下方各平台的说明操作:
bun add @capgo/capacitor-printerbunx cap sync导入
“导入”章节import { Printer } from '@capgo/capacitor-printer';快速入门
章节标题为“快速入门”打印磁盘上已有的 PDF(大文件推荐此方式)。
import { Printer } from '@capgo/capacitor-printer';
await Printer.printFile({ path: 'file:///data/user/0/.../invoice.pdf', name: 'Invoice #1042',});示例:HTML 小票
章节标题为“示例:HTML 收据”await Printer.printHtml({ html: '<h1>Thank you</h1><p>Total: $42.00</p>', name: 'Receipt',});示例:避免过大的 base64 负载
章节标题为“示例:避免超大的 base64 负载”printBase64 会在内存中解码整个文件。对于约 5 MB 以上的资源,请写入临时文件并调用 printFile 请改用这种方式。
常见坑点
章节标题为“常见陷阱”- 内存:在低内存设备上,过大的 base64 字符串可能会导致应用崩溃。
- Web 端:打印时会调用浏览器对话框,其布局与原生打印控制器不同。
- 路径:在 Android 上,请传入可访问的
file://URI、绝对文件系统路径或content://URI。应用相对路径不会被自动解析。
API 概览
章节标题:“API 概览”printBase64
标题为“printBase64”的章节展示用于打印 base64 编码文件的打印 UI。
平台行为:
- iOS: 使用 UIPrintInteractionController 处理 base64 解码数据
- Android: 使用 PrintManager 处理 base64 解码数据
- Web 端: 从 base64 数据创建 blob 并打开打印对话框
性能警告: 解码 base64 时,大文件可能会因内存限制导致 App 崩溃。 对于大于 5MB 的文件,建议改用 printFile()。
import { Printer } from '@capgo/capacitor-printer';
// Print a base64 encoded PDFawait Printer.printBase64({ name: 'Invoice #12345', data: 'base64-encoded-pdf-data', mimeType: 'application/pdf',});
// Print a base64 encoded imageawait Printer.printBase64({ name: 'Product Photo', data: '/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDA...', mimeType: 'image/jpeg',});printFile
“printFile”章节展示打印 UI 以打印设备本地文件。
平台行为:
- iOS: 使用 UIPrintInteractionController 并配合文件 URL。支持 file:// 路径或相对于应用 documents 目录的路径。
- Android: 使用 PrintManager 并配合文件路径。同时支持 content:// URI 和 file:// 路径。
- Web 端: 读取文件并打开打印对话框
支持的文件类型:
- PDF 文档 (application/pdf)
- 图片:JPEG, PNG, GIF, HEIC, HEIF
import { Printer } from '@capgo/capacitor-printer';
// iOS: Print from app documents directoryawait Printer.printFile({ name: 'Contract', path: 'file:///var/mobile/Containers/Data/Application/.../Documents/contract.pdf',});
// Android: Print from content URIawait Printer.printFile({ name: 'Receipt', path: 'content://com.android.providers.downloads.documents/document/123', mimeType: 'application/pdf',});
// Android: Print from file pathawait Printer.printFile({ name: 'Photo', path: 'file:///storage/emulated/0/Download/photo.jpg', mimeType: 'image/jpeg',});printHtml
“printHtml” 章节展示打印 UI 以打印 HTML 文档。
平台行为:
- iOS: 在 WKWebView 中渲染 HTML,然后使用 UIPrintInteractionController 打印
- Android: 在 WebView 中渲染 HTML,然后使用 PrintManager 打印
- Web 端: 创建包含 HTML 内容的 iframe 并触发打印对话框
HTML 要求:
- 应为结构完整的 HTML 文档
- 可以包含内联 CSS 样式或 style 标签
- 外部资源(图片、样式表)应使用绝对 URL
- 可使用以下方式添加打印专用 CSS
import { Printer } from '@capgo/capacitor-printer';
// Simple HTML documentawait Printer.printHtml({name: 'Sales Report',html: '<html><body><h1>Q4 Sales Report</h1><p>Revenue: $125,000</p></body></html>',});
// HTML with print-specific CSSawait Printer.printHtml({name: 'Styled Invoice',html: `<html><head><style>printPdf
“printPdf” 章节展示打印 UI 以打印 PDF 文档。
平台行为:
- iOS: 使用带有 PDF 文件 URL 的 UIPrintInteractionController
- Android: 使用带有 PdfDocument 的 PrintManager
- Web 端: 创建对象 URL 并打开打印对话框
文件路径要求:
- iOS:必须是 file:// 路径,或相对于应用 documents 目录的路径
- Android:支持 content:// URI(来自下载、媒体库)或 file:// 路径
- Web 端:必须是可访问的文件路径
import { Printer } from '@capgo/capacitor-printer';
// Print PDF from app storageawait Printer.printPdf({ name: 'Annual Report 2024', path: 'file:///var/mobile/Containers/Data/Application/.../Documents/report.pdf',});
// Print PDF from Android downloadsawait Printer.printPdf({ name: 'Downloaded Document', path: 'content://com.android.providers.downloads.documents/document/123',});printWebView
标题为 “printWebView” 的部分显示打印 UI,用于打印 web view 内容。
打印当前在应用 web view 中显示的内容。
平台行为:
- iOS:使用 UIPrintInteractionController 配合 WKWebView 的 view printable
- Android: 使用 PrintManager 配合 WebView.createPrintDocumentAdapter()
- Web 端: 触发当前页面的 window.print()
打印样式: 支持通过 CSS 打印媒体查询自定义。将应用 web view 当前的样式,包括任何
import { Printer } from '@capgo/capacitor-printer';
// Print current web view with default nameawait Printer.printWebView();
// Print with custom job nameawait Printer.printWebView({name: 'Dashboard Screenshot',});
// Use with print-specific CSS in your HTML// Add this to your app's CSS://类型参考
“类型参考” 章节PrintBase64Options
标题为“PrintBase64Options”的章节打印 base64 编码数据的选项。
export interface PrintBase64Options extends PrintOptions { /** * Valid base64 encoded string representing the file content. * * The base64 string should NOT include the data URL prefix (e.g., "data:application/pdf;base64,"). * Only provide the raw base64 encoded content. * * **Performance Considerations:** * - Base64 encoding increases data size by approximately 33% * - Large files (>5MB) may cause memory issues when decoding * - Consider using printFile() for large documents * * **Platform Notes:** * - **iOS**: Decoded to NSData and passed to UIPrintInteractionController * - **Android**: Decoded to byte array and written to temporary file * - **Web**: Converted to Blob for printing * * @since 7.0.0 * @example 'base64-encoded-pdf-data' */ data: string;
/** * MIME type of the base64 encoded data. * * **Supported types:** * - `application/pdf` - PDF documents * - `image/jpeg` - JPEG images * - `image/.png` - PNG images * - `image/.gif` - GIF images (iOS/Android only) * - `image/heic` - HEIC images (iOS only) * - `image/heif` - HEIF images (iOS only) * * **Platform Support:** * - All platforms support PDF, JPEG, and PNG * - GIF support varies by platform * - HEIC/HEIF are iOS-specific formats * * @since 7.0.0 * @example 'application/pdf' * @example 'image/jpeg' */ mimeType: string;}PrintFileOptions
“PrintFileOptions” 章节用于打印设备存储中文件的配置项。
export interface PrintFileOptions extends PrintOptions { /** * Path to the file to print. * * **iOS Path Formats:** * - `file://` URL: Full file URL path * - Relative path: Path relative to app's documents directory * - Must be within app's accessible directories (documents, temporary, cache) * * **Android Path Formats:** * - `content://` URI: Content provider URI (recommended for external files) * - `file://` path: Direct file system path * - Must have read permission for the file * * **Common Use Cases:** * - App documents: Files saved in app's document directory * - Downloads: Files from system downloads folder (use content:// on Android) * - Temporary files: Files in app's temporary/cache directory * - Shared storage: Files from external storage (Android, requires permissions) * * @since 7.0.0 * @platform ios Supports file:// paths and relative paths * @platform android Supports content:// URIs and file:// paths * @example 'content://com.android.providers.downloads.documents/document/123' * @example 'file:///var/mobile/Containers/Data/Application/.../Documents/document.pdf' * @example 'file:///storage/emulated/0/Download/receipt.pdf' */ path: string;
/** * MIME type of the file. * * **Platform Behavior:** * - **Android**: REQUIRED for content:// URIs. Helps the system determine how to handle the file. * Optional for file:// paths (auto-detected from extension). * - **iOS**: Ignored. File type is auto-detected from file extension. * - **Web**: Optional. Auto-detected if not provided. * * **Common MIME Types:** * - `application/pdf` - PDF documents * - `image/jpeg` - JPEG images * - `image/.png` - PNG images * - `image/.gif` - GIF images * * @since 7.0.0 * @default Undefined (auto-detected from file extension) * @platform android Used for content:// URIs and file type detection * @platform ios Ignored (auto-detected) * @example 'application/pdf' * @example 'image/jpeg' */ mimeType?: string;}PrintHtmlOptions
“PrintHtmlOptions” 章节用于打印 HTML 内容的配置项。
export interface PrintHtmlOptions extends PrintOptions { /** * HTML content to print. * * **Content Requirements:** * - Should be a complete HTML document with `<html>`, `<head>`, and `<body>` tags * - Can include inline CSS styles or `<style>` tags * - External resources (images, fonts) should use absolute URLs * - JavaScript is not executed during print rendering * * **Print Optimization Tips:** * - Use `@media print` CSS rules for print-specific styling * - Control page breaks with `page-break-before`, `page-break-after`, `page-break-inside` * - Hide UI elements using `.no-print { display: none; }` class * - Adjust font sizes for readability (12pt is standard for print) * - Use print-friendly colors (avoid dark backgrounds) * * **Platform Rendering:** * - **iOS**: Rendered in WKWebView before printing * - **Android**: Rendered in WebView before printing * - **Web**: Rendered in hidden iframe before printing * * **Character Encoding:** * - UTF-8 is recommended and default * - Include charset in HTML: `<meta charset="UTF-8">` * * @since 7.0.0 * @example '<html><body><h1>Hello World</h1><p>This is a test document.</p></body></html>' * @example * ```typescript * const htmlWithStyles = ` * <html> * <head> * <meta charset="UTF-8"> * <style> * @media print { * body { font-family: Arial, sans-serif; font-size: 12pt; } * .no-print { display: none; } * h1 { color: #333; page-break-before: always; } * } * </style> * </head> * <body> * <h1>Invoice #12345</h1> * <p>Amount: $299.99</p> * </body> * </html> * `; * ``` */ html: string;}PrintPdfOptions
“PrintPdfOptions” 章节用于打印 PDF 文档的配置项。
export interface PrintPdfOptions extends PrintOptions { /** * Path to the PDF document. * * **iOS Path Formats:** * - `file://` URL: Full file URL path to PDF document * - Relative path: Path relative to app's documents directory * - Must be within app's accessible directories (documents, temporary, cache) * - PDF must be valid and not password-protected * * **Android Path Formats:** * - `content://` URI: Content provider URI (recommended for external PDFs) * - `file://` path: Direct file system path to PDF * - Must have read permission for the file * - Supports both single-page and multi-page PDFs * * **Web Path Formats:** * - Relative or absolute path accessible from web context * - Must be a valid PDF file * * **Validation:** * - File must exist at the specified path * - File must be a valid PDF (checked by magic number/header) * - File must be readable by the app * * **Common Sources:** * - App documents: PDFs saved in app's document directory * - Downloads: PDFs from system downloads (use content:// on Android) * - Generated PDFs: Temporary PDFs created by the app * - Network downloads: PDFs downloaded and saved locally * * @since 7.0.0 * @platform ios Supports file:// paths and relative paths * @platform android Supports content:// URIs and file:// paths * @platform web Supports accessible file paths * @example 'content://com.android.providers.downloads.documents/document/123' * @example 'file:///var/mobile/Containers/Data/Application/.../Documents/document.pdf' * @example 'file:///storage/emulated/0/Download/report.pdf' * @example 'Documents/invoice-2024.pdf' */ path: string;}PrintOptions
“PrintOptions” 章节所有打印操作的基础配置项。
export interface PrintOptions { /** * Name of the print job. * * **Usage:** * - Displayed in the system print queue * - Shown in print history/logs * - May appear in printer status displays * - Used as default filename for "Save as PDF" option * * **Platform Behavior:** * - **iOS**: Shown in print preview header and activity view * - **Android**: Displayed in print job notification and print queue * - **Web**: Used as document title in print dialog * * **Best Practices:** * - Use descriptive names (e.g., "Invoice #12345", "Q4 Report") * - Keep under 50 characters for better display * - Avoid special characters that may cause issues in filenames * - Include relevant identifiers (order numbers, dates, etc.) * * **Examples:** * - "Invoice #12345" * - "Sales Report - 2024 Q4" * - "Customer Receipt - John Doe" * - "Product Photo - SKU-ABC123" * * @since 7.0.0 * @default 'Document' * @platform ios Shown in print preview and activity view * @platform android Shown in print queue and notifications * @platform web Used as document title in print dialog * @example 'Invoice #12345' * @example 'Annual Report 2024' * @example 'Receipt - Order #789' */ name?: string;}单一事实来源
标题为“单一事实来源”的部分本页面由插件的 src/definitions.ts生成。当上游的公共 API 发生变化时,请重新运行 sync。
从入门指南继续
“从入门指南继续”章节如果你正在使用 快速入门 要规划 dashboard 和 API 操作,请将其连接到 使用 @capgo/capacitor-printer 在“使用 @capgo/capacitor-printer”中实现原生能力, API 概览 关于 API Overview 中的实现细节, 简介 关于 Introduction 中的实现细节, API 密钥 有关 API Keys 的实现细节,以及 设备 有关 Devices 的实现细节。