@capgo/capacitor-printer 8.0.17 → 8.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -94,6 +94,7 @@ await Printer.printWebView({
94
94
  * [`printFile(...)`](#printfile)
95
95
  * [`printHtml(...)`](#printhtml)
96
96
  * [`printPdf(...)`](#printpdf)
97
+ * [`printIframe(...)`](#printiframe)
97
98
  * [`printWebView(...)`](#printwebview)
98
99
  * [`getPluginVersion()`](#getpluginversion)
99
100
  * [Interfaces](#interfaces)
@@ -216,35 +217,39 @@ Presents the printing UI to print PDF documents.
216
217
  --------------------
217
218
 
218
219
 
219
- ### printWebView(...)
220
+ ### printIframe(...)
220
221
 
221
222
  ```typescript
222
- printWebView(options?: PrintOptions | undefined) => Promise<void>
223
+ printIframe(options: PrintIframeOptions) => Promise<void>
223
224
  ```
224
225
 
225
- Presents the printing UI to print web view content.
226
+ Presents the printing UI for content inside an iframe element.
226
227
 
227
- Prints the current content displayed in your app's web view.
228
+ Useful when the full HTML document is too large to pass to printHtml().
228
229
 
229
230
  **Platform Behavior:**
230
- - **iOS**: Uses UIPrintInteractionController with WKWebView's view printable
231
- - **Android**: Uses WebView.createPrintDocumentAdapter() with PrintManager
232
- - **Web**: Triggers window.print() for current page
231
+ - **iOS**: Evaluates JavaScript in the WebView to print the iframe content
232
+ - **Android**: Evaluates JavaScript in the WebView to print the iframe content
233
+ - **Web**: Finds the iframe and triggers its print dialog
233
234
 
234
- **Print Styling:**
235
- Supports CSS print media queries for customization. The web view's current
236
- styles will be applied, including any @media print rules.
235
+ | Param | Type | Description |
236
+ | ------------- | ----------------------------------------------------------------- | ------------------------------------------ |
237
+ | **`options`** | <code><a href="#printiframeoptions">PrintIframeOptions</a></code> | - CSS selector and optional print job name |
237
238
 
238
- **Use Cases:**
239
- - Print the current app screen/page
240
- - Print web-based reports or dashboards
241
- - Print user-generated content displayed in web view
239
+ **Since:** 8.0.19
242
240
 
243
- | Param | Type | Description |
244
- | ------------- | ----------------------------------------------------- | ------------------------------------------------- |
245
- | **`options`** | <code><a href="#printoptions">PrintOptions</a></code> | - Optional configuration for printing (name only) |
241
+ --------------------
246
242
 
247
- **Since:** 7.0.0
243
+
244
+ ### printWebView(...)
245
+
246
+ ```typescript
247
+ printWebView(options?: PrintOptions | undefined) => Promise<void>
248
+ ```
249
+
250
+ | Param | Type |
251
+ | ------------- | ----------------------------------------------------- |
252
+ | **`options`** | <code><a href="#printoptions">PrintOptions</a></code> |
248
253
 
249
254
  --------------------
250
255
 
@@ -309,6 +314,15 @@ Options for printing PDF documents.
309
314
  | **`path`** | <code>string</code> | 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 | 7.0.0 |
310
315
 
311
316
 
317
+ #### PrintIframeOptions
318
+
319
+ Options for printing iframe content.
320
+
321
+ | Prop | Type | Description | Since |
322
+ | -------------- | ------------------- | -------------------------------------------------------------------------------------------------------------- | ------ |
323
+ | **`selector`** | <code>string</code> | CSS selector for the iframe element to print. The selector must match a single iframe in the current document. | 8.0.19 |
324
+
325
+
312
326
  #### PrintOptions
313
327
 
314
328
  Base options for all print operations.
@@ -141,11 +141,44 @@ public class Printer {
141
141
  }
142
142
  }
143
143
 
144
+ public void printIframe(WebView webView, String selector, String name) throws Exception {
145
+ if (webView == null) {
146
+ throw new Exception("WebView not available");
147
+ }
148
+
149
+ String escapedSelector = org.json.JSONObject.quote(selector);
150
+ String escapedName = org.json.JSONObject.quote(name);
151
+ final String script =
152
+ "(function(){var frame=document.querySelector(" +
153
+ escapedSelector +
154
+ ");if(!frame||!frame.contentWindow){throw new Error('iframe not found');}if(" +
155
+ escapedName +
156
+ "){document.title=" +
157
+ escapedName +
158
+ ";}frame.contentWindow.focus();frame.contentWindow.print();})()";
159
+
160
+ activity.runOnUiThread(
161
+ new Runnable() {
162
+ @Override
163
+ public void run() {
164
+ webView.evaluateJavascript(script, null);
165
+ }
166
+ }
167
+ );
168
+ }
169
+
144
170
  public void printWebView(WebView webView, String name) throws Exception {
145
171
  if (webView == null) {
146
172
  throw new Exception("WebView not available");
147
173
  }
148
- createWebPrintJob(webView, name);
174
+ activity.runOnUiThread(
175
+ new Runnable() {
176
+ @Override
177
+ public void run() {
178
+ createWebPrintJob(webView, name);
179
+ }
180
+ }
181
+ );
149
182
  }
150
183
 
151
184
  // MARK: - Private Helper Methods
@@ -286,6 +319,7 @@ public class Printer {
286
319
  WriteResultCallback callback
287
320
  ) {
288
321
  try (
322
+ // Read from the temp file path directly (cache dir), not openFileInput().
289
323
  InputStream input = new java.io.FileInputStream(file);
290
324
  OutputStream output = new FileOutputStream(destination.getFileDescriptor())
291
325
  ) {
@@ -9,7 +9,7 @@ import com.getcapacitor.annotation.CapacitorPlugin;
9
9
  @CapacitorPlugin(name = "Printer")
10
10
  public class PrinterPlugin extends Plugin {
11
11
 
12
- private final String pluginVersion = "8.0.17";
12
+ private final String pluginVersion = "8.1.0";
13
13
 
14
14
  private Printer implementation;
15
15
 
@@ -97,6 +97,24 @@ public class PrinterPlugin extends Plugin {
97
97
  }
98
98
  }
99
99
 
100
+ @PluginMethod
101
+ public void printIframe(PluginCall call) {
102
+ String selector = call.getString("selector");
103
+ String name = call.getString("name", "Document");
104
+
105
+ if (selector == null) {
106
+ call.reject("selector is required");
107
+ return;
108
+ }
109
+
110
+ try {
111
+ implementation.printIframe(getBridge().getWebView(), selector, name);
112
+ call.resolve();
113
+ } catch (Exception e) {
114
+ call.reject("Failed to print iframe: " + e.getMessage(), e);
115
+ }
116
+ }
117
+
100
118
  @PluginMethod
101
119
  public void printWebView(PluginCall call) {
102
120
  String name = call.getString("name", "Document");
package/dist/docs.json CHANGED
@@ -166,20 +166,20 @@
166
166
  "slug": "printpdf"
167
167
  },
168
168
  {
169
- "name": "printWebView",
170
- "signature": "(options?: PrintOptions | undefined) => Promise<void>",
169
+ "name": "printIframe",
170
+ "signature": "(options: PrintIframeOptions) => Promise<void>",
171
171
  "parameters": [
172
172
  {
173
173
  "name": "options",
174
- "docs": "- Optional configuration for printing (name only)",
175
- "type": "PrintOptions | undefined"
174
+ "docs": "- CSS selector and optional print job name",
175
+ "type": "PrintIframeOptions"
176
176
  }
177
177
  ],
178
178
  "returns": "Promise<void>",
179
179
  "tags": [
180
180
  {
181
181
  "name": "param",
182
- "text": "options - Optional configuration for printing (name only)"
182
+ "text": "options - CSS selector and optional print job name"
183
183
  },
184
184
  {
185
185
  "name": "returns",
@@ -187,22 +187,36 @@
187
187
  },
188
188
  {
189
189
  "name": "throws",
190
- "text": "Error if web view is not available or printing fails"
190
+ "text": "Error if the iframe is not found or printing fails"
191
191
  },
192
192
  {
193
193
  "name": "since",
194
- "text": "7.0.0"
194
+ "text": "8.0.19"
195
195
  },
196
196
  {
197
197
  "name": "example",
198
- "text": "```typescript\n// Print current web view with default name\nawait Printer.printWebView();\n\n// Print with custom job name\nawait Printer.printWebView({\n name: 'Dashboard Screenshot',\n});\n\n// Use with print-specific CSS in your HTML\n// Add this to your app's CSS:\n//"
199
- },
198
+ "text": "```typescript\nawait Printer.printIframe({\n selector: '#report-frame',\n name: 'Monthly Report',\n});\n```"
199
+ }
200
+ ],
201
+ "docs": "Presents the printing UI for content inside an iframe element.\n\nUseful when the full HTML document is too large to pass to printHtml().\n\n**Platform Behavior:**\n- **iOS**: Evaluates JavaScript in the WebView to print the iframe content\n- **Android**: Evaluates JavaScript in the WebView to print the iframe content\n- **Web**: Finds the iframe and triggers its print dialog",
202
+ "complexTypes": [
203
+ "PrintIframeOptions"
204
+ ],
205
+ "slug": "printiframe"
206
+ },
207
+ {
208
+ "name": "printWebView",
209
+ "signature": "(options?: PrintOptions | undefined) => Promise<void>",
210
+ "parameters": [
200
211
  {
201
- "name": "media",
202
- "text": "print {\n// .no-print { display: none; }\n// body { font-size: 12pt; }\n// }\nawait Printer.printWebView({\nname: 'User Profile',\n});\n```"
212
+ "name": "options",
213
+ "docs": "",
214
+ "type": "PrintOptions | undefined"
203
215
  }
204
216
  ],
205
- "docs": "Presents the printing UI to print web view content.\n\nPrints the current content displayed in your app's web view.\n\n**Platform Behavior:**\n- **iOS**: Uses UIPrintInteractionController with WKWebView's view printable\n- **Android**: Uses WebView.createPrintDocumentAdapter() with PrintManager\n- **Web**: Triggers window.print() for current page\n\n**Print Styling:**\nSupports CSS print media queries for customization. The web view's current\nstyles will be applied, including any @media print rules.\n\n**Use Cases:**\n- Print the current app screen/page\n- Print web-based reports or dashboards\n- Print user-generated content displayed in web view",
217
+ "returns": "Promise<void>",
218
+ "tags": [],
219
+ "docs": "",
206
220
  "complexTypes": [
207
221
  "PrintOptions"
208
222
  ],
@@ -459,6 +473,40 @@
459
473
  }
460
474
  ]
461
475
  },
476
+ {
477
+ "name": "PrintIframeOptions",
478
+ "slug": "printiframeoptions",
479
+ "docs": "Options for printing iframe content.",
480
+ "tags": [
481
+ {
482
+ "text": "8.0.19",
483
+ "name": "since"
484
+ }
485
+ ],
486
+ "methods": [],
487
+ "properties": [
488
+ {
489
+ "name": "selector",
490
+ "tags": [
491
+ {
492
+ "text": "8.0.19",
493
+ "name": "since"
494
+ },
495
+ {
496
+ "text": "'#report-frame'",
497
+ "name": "example"
498
+ },
499
+ {
500
+ "text": "'iframe[name=\"invoice\"]'",
501
+ "name": "example"
502
+ }
503
+ ],
504
+ "docs": "CSS selector for the iframe element to print.\n\nThe selector must match a single iframe in the current document.",
505
+ "complexTypes": [],
506
+ "type": "string"
507
+ }
508
+ ]
509
+ },
462
510
  {
463
511
  "name": "PrintOptions",
464
512
  "slug": "printoptions",
@@ -207,6 +207,29 @@ export interface PrinterPlugin {
207
207
  * });
208
208
  * ```
209
209
  */
210
+ /**
211
+ * Presents the printing UI for content inside an iframe element.
212
+ *
213
+ * Useful when the full HTML document is too large to pass to printHtml().
214
+ *
215
+ * **Platform Behavior:**
216
+ * - **iOS**: Evaluates JavaScript in the WebView to print the iframe content
217
+ * - **Android**: Evaluates JavaScript in the WebView to print the iframe content
218
+ * - **Web**: Finds the iframe and triggers its print dialog
219
+ *
220
+ * @param options - CSS selector and optional print job name
221
+ * @returns Promise that resolves when print dialog is dismissed
222
+ * @throws Error if the iframe is not found or printing fails
223
+ * @since 8.0.19
224
+ * @example
225
+ * ```typescript
226
+ * await Printer.printIframe({
227
+ * selector: '#report-frame',
228
+ * name: 'Monthly Report',
229
+ * });
230
+ * ```
231
+ */
232
+ printIframe(options: PrintIframeOptions): Promise<void>;
210
233
  printWebView(options?: PrintOptions): Promise<void>;
211
234
  /**
212
235
  * Get the native Capacitor plugin version.
@@ -486,4 +509,21 @@ export interface PrintOptions {
486
509
  *
487
510
  * @since 7.0.0
488
511
  */
512
+ /**
513
+ * Options for printing iframe content.
514
+ *
515
+ * @since 8.0.19
516
+ */
517
+ export interface PrintIframeOptions extends PrintOptions {
518
+ /**
519
+ * CSS selector for the iframe element to print.
520
+ *
521
+ * The selector must match a single iframe in the current document.
522
+ *
523
+ * @since 8.0.19
524
+ * @example '#report-frame'
525
+ * @example 'iframe[name="invoice"]'
526
+ */
527
+ selector: string;
528
+ }
489
529
  export type PrintWebViewOptions = PrintOptions;
@@ -1 +1 @@
1
- {"version":3,"file":"definitions.js","sourceRoot":"","sources":["../../src/definitions.ts"],"names":[],"mappings":"","sourcesContent":["export interface PrinterPlugin {\n /**\n * Presents the printing UI to print files encoded as base64 strings.\n *\n * **Platform Behavior:**\n * - **iOS**: Uses UIPrintInteractionController with base64 decoded data\n * - **Android**: Uses PrintManager with base64 decoded data\n * - **Web**: Creates a blob from base64 data and opens print dialog\n *\n * **Performance Warning:**\n * Large files can lead to app crashes due to memory constraints when decoding base64.\n * For files larger than 5MB, it's recommended to use printFile() instead.\n *\n * @param options - The base64 data and configuration for printing\n * @returns Promise that resolves when print dialog is dismissed\n * @throws Error if base64 data is invalid or printing fails\n * @since 7.0.0\n * @example\n * ```typescript\n * // Print a base64 encoded PDF\n * await Printer.printBase64({\n * name: 'Invoice #12345',\n * data: 'JVBERi0xLjQKJeLjz9MKMyAwIG9iago8PC9UeXBlL...',\n * mimeType: 'application/pdf',\n * });\n *\n * // Print a base64 encoded image\n * await Printer.printBase64({\n * name: 'Product Photo',\n * data: '/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDA...',\n * mimeType: 'image/jpeg',\n * });\n * ```\n */\n printBase64(options: PrintBase64Options): Promise<void>;\n\n /**\n * Presents the printing UI to print device files.\n *\n * **Platform Behavior:**\n * - **iOS**: Uses UIPrintInteractionController with file URL. Supports file:// paths or paths relative to app's documents directory.\n * - **Android**: Uses PrintManager with file path. Supports both content:// URIs and file:// paths.\n * - **Web**: Reads file and opens print dialog\n *\n * **Supported File Types:**\n * - PDF documents (application/pdf)\n * - Images: JPEG, PNG, GIF, HEIC, HEIF\n *\n * @param options - The file path and configuration for printing\n * @returns Promise that resolves when print dialog is dismissed\n * @throws Error if file path is invalid, file not found, or unsupported file type\n * @since 7.0.0\n * @example\n * ```typescript\n * // iOS: Print from app documents directory\n * await Printer.printFile({\n * name: 'Contract',\n * path: 'file:///var/mobile/Containers/Data/Application/.../Documents/contract.pdf',\n * });\n *\n * // Android: Print from content URI\n * await Printer.printFile({\n * name: 'Receipt',\n * path: 'content://com.android.providers.downloads.documents/document/123',\n * mimeType: 'application/pdf',\n * });\n *\n * // Android: Print from file path\n * await Printer.printFile({\n * name: 'Photo',\n * path: 'file:///storage/emulated/0/Download/photo.jpg',\n * mimeType: 'image/jpeg',\n * });\n * ```\n */\n printFile(options: PrintFileOptions): Promise<void>;\n\n /**\n * Presents the printing UI to print HTML documents.\n *\n * **Platform Behavior:**\n * - **iOS**: Renders HTML in WKWebView, then prints using UIPrintInteractionController\n * - **Android**: Renders HTML in WebView, then prints using PrintManager\n * - **Web**: Creates iframe with HTML content and triggers print dialog\n *\n * **HTML Requirements:**\n * - Should be a complete HTML document with proper structure\n * - Can include inline CSS styles or style tags\n * - External resources (images, stylesheets) should use absolute URLs\n * - Print-specific CSS can be added using @media print rules\n *\n * **CSS Print Styling:**\n * Use CSS media queries to customize print output:\n * - Control page breaks: page-break-before, page-break-after, page-break-inside\n * - Hide elements: display: none for no-print classes\n * - Adjust font sizes and colors for print\n *\n * @param options - The HTML content and configuration for printing\n * @returns Promise that resolves when print dialog is dismissed\n * @throws Error if HTML is invalid or printing fails\n * @since 7.0.0\n * @example\n * ```typescript\n * // Simple HTML document\n * await Printer.printHtml({\n * name: 'Sales Report',\n * html: '<html><body><h1>Q4 Sales Report</h1><p>Revenue: $125,000</p></body></html>',\n * });\n *\n * // HTML with print-specific CSS\n * await Printer.printHtml({\n * name: 'Styled Invoice',\n * html: `\n * <html>\n * <head>\n * <style>\n * @media print {\n * body { font-size: 12pt; }\n * .no-print { display: none; }\n * h1 { page-break-before: always; }\n * }\n * </style>\n * </head>\n * <body>\n * <h1>Invoice #12345</h1>\n * <p>Amount due: $299.99</p>\n * <button class=\"no-print\">Don't print this button</button>\n * </body>\n * </html>\n * `,\n * });\n * ```\n */\n printHtml(options: PrintHtmlOptions): Promise<void>;\n\n /**\n * Presents the printing UI to print PDF documents.\n *\n * **Platform Behavior:**\n * - **iOS**: Uses UIPrintInteractionController with PDF file URL\n * - **Android**: Uses PrintManager with PdfDocument\n * - **Web**: Creates object URL and opens print dialog\n *\n * **File Path Requirements:**\n * - **iOS**: Must be file:// path or relative to app's documents directory\n * - **Android**: Supports content:// URIs (from downloads, media store) or file:// paths\n * - **Web**: Must be accessible file path\n *\n * @param options - The PDF file path and configuration for printing\n * @returns Promise that resolves when print dialog is dismissed\n * @throws Error if PDF path is invalid, file not found, or not a valid PDF\n * @since 7.0.0\n * @example\n * ```typescript\n * // Print PDF from app storage\n * await Printer.printPdf({\n * name: 'Annual Report 2024',\n * path: 'file:///var/mobile/Containers/Data/Application/.../Documents/report.pdf',\n * });\n *\n * // Print PDF from Android downloads\n * await Printer.printPdf({\n * name: 'Downloaded Document',\n * path: 'content://com.android.providers.downloads.documents/document/123',\n * });\n * ```\n */\n printPdf(options: PrintPdfOptions): Promise<void>;\n\n /**\n * Presents the printing UI to print web view content.\n *\n * Prints the current content displayed in your app's web view.\n *\n * **Platform Behavior:**\n * - **iOS**: Uses UIPrintInteractionController with WKWebView's view printable\n * - **Android**: Uses WebView.createPrintDocumentAdapter() with PrintManager\n * - **Web**: Triggers window.print() for current page\n *\n * **Print Styling:**\n * Supports CSS print media queries for customization. The web view's current\n * styles will be applied, including any @media print rules.\n *\n * **Use Cases:**\n * - Print the current app screen/page\n * - Print web-based reports or dashboards\n * - Print user-generated content displayed in web view\n *\n * @param options - Optional configuration for printing (name only)\n * @returns Promise that resolves when print dialog is dismissed\n * @throws Error if web view is not available or printing fails\n * @since 7.0.0\n * @example\n * ```typescript\n * // Print current web view with default name\n * await Printer.printWebView();\n *\n * // Print with custom job name\n * await Printer.printWebView({\n * name: 'Dashboard Screenshot',\n * });\n *\n * // Use with print-specific CSS in your HTML\n * // Add this to your app's CSS:\n * // @media print {\n * // .no-print { display: none; }\n * // body { font-size: 12pt; }\n * // }\n * await Printer.printWebView({\n * name: 'User Profile',\n * });\n * ```\n */\n printWebView(options?: PrintOptions): Promise<void>;\n\n /**\n * Get the native Capacitor plugin version.\n *\n * Returns the hardcoded plugin version from native code (iOS/Android) or\n * package version (Web). This is useful for debugging and ensuring plugin\n * compatibility.\n *\n * @returns Promise that resolves with the plugin version string\n * @throws Error if getting the version fails\n * @since 7.0.0\n * @example\n * ```typescript\n * const { version } = await Printer.getPluginVersion();\n * console.log('Printer plugin version:', version);\n * // Output: \"7.0.0\"\n * ```\n */\n getPluginVersion(): Promise<{ version: string }>;\n}\n\n/**\n * Options for printing base64 encoded data.\n *\n * @since 7.0.0\n */\nexport interface PrintBase64Options extends PrintOptions {\n /**\n * Valid base64 encoded string representing the file content.\n *\n * The base64 string should NOT include the data URL prefix (e.g., \"data:application/pdf;base64,\").\n * Only provide the raw base64 encoded content.\n *\n * **Performance Considerations:**\n * - Base64 encoding increases data size by approximately 33%\n * - Large files (>5MB) may cause memory issues when decoding\n * - Consider using printFile() for large documents\n *\n * **Platform Notes:**\n * - **iOS**: Decoded to NSData and passed to UIPrintInteractionController\n * - **Android**: Decoded to byte array and written to temporary file\n * - **Web**: Converted to Blob for printing\n *\n * @since 7.0.0\n * @example 'JVBERi0xLjQKJeLjz9MKMyAwIG9iago8PC9UeXBlL...'\n */\n data: string;\n\n /**\n * MIME type of the base64 encoded data.\n *\n * **Supported types:**\n * - `application/pdf` - PDF documents\n * - `image/jpeg` - JPEG images\n * - `image/png` - PNG images\n * - `image/gif` - GIF images (iOS/Android only)\n * - `image/heic` - HEIC images (iOS only)\n * - `image/heif` - HEIF images (iOS only)\n *\n * **Platform Support:**\n * - All platforms support PDF, JPEG, and PNG\n * - GIF support varies by platform\n * - HEIC/HEIF are iOS-specific formats\n *\n * @since 7.0.0\n * @example 'application/pdf'\n * @example 'image/jpeg'\n */\n mimeType: string;\n}\n\n/**\n * Options for printing files from device storage.\n *\n * @since 7.0.0\n */\nexport interface PrintFileOptions extends PrintOptions {\n /**\n * Path to the file to print.\n *\n * **iOS Path Formats:**\n * - `file://` URL: Full file URL path\n * - Relative path: Path relative to app's documents directory\n * - Must be within app's accessible directories (documents, temporary, cache)\n *\n * **Android Path Formats:**\n * - `content://` URI: Content provider URI (recommended for external files)\n * - `file://` path: Direct file system path\n * - Must have read permission for the file\n *\n * **Common Use Cases:**\n * - App documents: Files saved in app's document directory\n * - Downloads: Files from system downloads folder (use content:// on Android)\n * - Temporary files: Files in app's temporary/cache directory\n * - Shared storage: Files from external storage (Android, requires permissions)\n *\n * @since 7.0.0\n * @platform ios Supports file:// paths and relative paths\n * @platform android Supports content:// URIs and file:// paths\n * @example 'content://com.android.providers.downloads.documents/document/123'\n * @example 'file:///var/mobile/Containers/Data/Application/.../Documents/document.pdf'\n * @example 'file:///storage/emulated/0/Download/receipt.pdf'\n */\n path: string;\n\n /**\n * MIME type of the file.\n *\n * **Platform Behavior:**\n * - **Android**: REQUIRED for content:// URIs. Helps the system determine how to handle the file.\n * Optional for file:// paths (auto-detected from extension).\n * - **iOS**: Ignored. File type is auto-detected from file extension.\n * - **Web**: Optional. Auto-detected if not provided.\n *\n * **Common MIME Types:**\n * - `application/pdf` - PDF documents\n * - `image/jpeg` - JPEG images\n * - `image/png` - PNG images\n * - `image/gif` - GIF images\n *\n * @since 7.0.0\n * @default Undefined (auto-detected from file extension)\n * @platform android Used for content:// URIs and file type detection\n * @platform ios Ignored (auto-detected)\n * @example 'application/pdf'\n * @example 'image/jpeg'\n */\n mimeType?: string;\n}\n\n/**\n * Options for printing HTML content.\n *\n * @since 7.0.0\n */\nexport interface PrintHtmlOptions extends PrintOptions {\n /**\n * HTML content to print.\n *\n * **Content Requirements:**\n * - Should be a complete HTML document with `<html>`, `<head>`, and `<body>` tags\n * - Can include inline CSS styles or `<style>` tags\n * - External resources (images, fonts) should use absolute URLs\n * - JavaScript is not executed during print rendering\n *\n * **Print Optimization Tips:**\n * - Use `@media print` CSS rules for print-specific styling\n * - Control page breaks with `page-break-before`, `page-break-after`, `page-break-inside`\n * - Hide UI elements using `.no-print { display: none; }` class\n * - Adjust font sizes for readability (12pt is standard for print)\n * - Use print-friendly colors (avoid dark backgrounds)\n *\n * **Platform Rendering:**\n * - **iOS**: Rendered in WKWebView before printing\n * - **Android**: Rendered in WebView before printing\n * - **Web**: Rendered in hidden iframe before printing\n *\n * **Character Encoding:**\n * - UTF-8 is recommended and default\n * - Include charset in HTML: `<meta charset=\"UTF-8\">`\n *\n * @since 7.0.0\n * @example '<html><body><h1>Hello World</h1><p>This is a test document.</p></body></html>'\n * @example\n * ```typescript\n * const htmlWithStyles = `\n * <html>\n * <head>\n * <meta charset=\"UTF-8\">\n * <style>\n * @media print {\n * body { font-family: Arial, sans-serif; font-size: 12pt; }\n * .no-print { display: none; }\n * h1 { color: #333; page-break-before: always; }\n * }\n * </style>\n * </head>\n * <body>\n * <h1>Invoice #12345</h1>\n * <p>Amount: $299.99</p>\n * </body>\n * </html>\n * `;\n * ```\n */\n html: string;\n}\n\n/**\n * Options for printing PDF documents.\n *\n * @since 7.0.0\n */\nexport interface PrintPdfOptions extends PrintOptions {\n /**\n * Path to the PDF document.\n *\n * **iOS Path Formats:**\n * - `file://` URL: Full file URL path to PDF document\n * - Relative path: Path relative to app's documents directory\n * - Must be within app's accessible directories (documents, temporary, cache)\n * - PDF must be valid and not password-protected\n *\n * **Android Path Formats:**\n * - `content://` URI: Content provider URI (recommended for external PDFs)\n * - `file://` path: Direct file system path to PDF\n * - Must have read permission for the file\n * - Supports both single-page and multi-page PDFs\n *\n * **Web Path Formats:**\n * - Relative or absolute path accessible from web context\n * - Must be a valid PDF file\n *\n * **Validation:**\n * - File must exist at the specified path\n * - File must be a valid PDF (checked by magic number/header)\n * - File must be readable by the app\n *\n * **Common Sources:**\n * - App documents: PDFs saved in app's document directory\n * - Downloads: PDFs from system downloads (use content:// on Android)\n * - Generated PDFs: Temporary PDFs created by the app\n * - Network downloads: PDFs downloaded and saved locally\n *\n * @since 7.0.0\n * @platform ios Supports file:// paths and relative paths\n * @platform android Supports content:// URIs and file:// paths\n * @platform web Supports accessible file paths\n * @example 'content://com.android.providers.downloads.documents/document/123'\n * @example 'file:///var/mobile/Containers/Data/Application/.../Documents/document.pdf'\n * @example 'file:///storage/emulated/0/Download/report.pdf'\n * @example 'Documents/invoice-2024.pdf'\n */\n path: string;\n}\n\n/**\n * Base options for all print operations.\n *\n * @since 7.0.0\n */\nexport interface PrintOptions {\n /**\n * Name of the print job.\n *\n * **Usage:**\n * - Displayed in the system print queue\n * - Shown in print history/logs\n * - May appear in printer status displays\n * - Used as default filename for \"Save as PDF\" option\n *\n * **Platform Behavior:**\n * - **iOS**: Shown in print preview header and activity view\n * - **Android**: Displayed in print job notification and print queue\n * - **Web**: Used as document title in print dialog\n *\n * **Best Practices:**\n * - Use descriptive names (e.g., \"Invoice #12345\", \"Q4 Report\")\n * - Keep under 50 characters for better display\n * - Avoid special characters that may cause issues in filenames\n * - Include relevant identifiers (order numbers, dates, etc.)\n *\n * **Examples:**\n * - \"Invoice #12345\"\n * - \"Sales Report - 2024 Q4\"\n * - \"Customer Receipt - John Doe\"\n * - \"Product Photo - SKU-ABC123\"\n *\n * @since 7.0.0\n * @default 'Document'\n * @platform ios Shown in print preview and activity view\n * @platform android Shown in print queue and notifications\n * @platform web Used as document title in print dialog\n * @example 'Invoice #12345'\n * @example 'Annual Report 2024'\n * @example 'Receipt - Order #789'\n */\n name?: string;\n}\n\n/**\n * Type alias for print web view options.\n *\n * @since 7.0.0\n */\nexport type PrintWebViewOptions = PrintOptions;\n"]}
1
+ {"version":3,"file":"definitions.js","sourceRoot":"","sources":["../../src/definitions.ts"],"names":[],"mappings":"","sourcesContent":["export interface PrinterPlugin {\n /**\n * Presents the printing UI to print files encoded as base64 strings.\n *\n * **Platform Behavior:**\n * - **iOS**: Uses UIPrintInteractionController with base64 decoded data\n * - **Android**: Uses PrintManager with base64 decoded data\n * - **Web**: Creates a blob from base64 data and opens print dialog\n *\n * **Performance Warning:**\n * Large files can lead to app crashes due to memory constraints when decoding base64.\n * For files larger than 5MB, it's recommended to use printFile() instead.\n *\n * @param options - The base64 data and configuration for printing\n * @returns Promise that resolves when print dialog is dismissed\n * @throws Error if base64 data is invalid or printing fails\n * @since 7.0.0\n * @example\n * ```typescript\n * // Print a base64 encoded PDF\n * await Printer.printBase64({\n * name: 'Invoice #12345',\n * data: 'JVBERi0xLjQKJeLjz9MKMyAwIG9iago8PC9UeXBlL...',\n * mimeType: 'application/pdf',\n * });\n *\n * // Print a base64 encoded image\n * await Printer.printBase64({\n * name: 'Product Photo',\n * data: '/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDA...',\n * mimeType: 'image/jpeg',\n * });\n * ```\n */\n printBase64(options: PrintBase64Options): Promise<void>;\n\n /**\n * Presents the printing UI to print device files.\n *\n * **Platform Behavior:**\n * - **iOS**: Uses UIPrintInteractionController with file URL. Supports file:// paths or paths relative to app's documents directory.\n * - **Android**: Uses PrintManager with file path. Supports both content:// URIs and file:// paths.\n * - **Web**: Reads file and opens print dialog\n *\n * **Supported File Types:**\n * - PDF documents (application/pdf)\n * - Images: JPEG, PNG, GIF, HEIC, HEIF\n *\n * @param options - The file path and configuration for printing\n * @returns Promise that resolves when print dialog is dismissed\n * @throws Error if file path is invalid, file not found, or unsupported file type\n * @since 7.0.0\n * @example\n * ```typescript\n * // iOS: Print from app documents directory\n * await Printer.printFile({\n * name: 'Contract',\n * path: 'file:///var/mobile/Containers/Data/Application/.../Documents/contract.pdf',\n * });\n *\n * // Android: Print from content URI\n * await Printer.printFile({\n * name: 'Receipt',\n * path: 'content://com.android.providers.downloads.documents/document/123',\n * mimeType: 'application/pdf',\n * });\n *\n * // Android: Print from file path\n * await Printer.printFile({\n * name: 'Photo',\n * path: 'file:///storage/emulated/0/Download/photo.jpg',\n * mimeType: 'image/jpeg',\n * });\n * ```\n */\n printFile(options: PrintFileOptions): Promise<void>;\n\n /**\n * Presents the printing UI to print HTML documents.\n *\n * **Platform Behavior:**\n * - **iOS**: Renders HTML in WKWebView, then prints using UIPrintInteractionController\n * - **Android**: Renders HTML in WebView, then prints using PrintManager\n * - **Web**: Creates iframe with HTML content and triggers print dialog\n *\n * **HTML Requirements:**\n * - Should be a complete HTML document with proper structure\n * - Can include inline CSS styles or style tags\n * - External resources (images, stylesheets) should use absolute URLs\n * - Print-specific CSS can be added using @media print rules\n *\n * **CSS Print Styling:**\n * Use CSS media queries to customize print output:\n * - Control page breaks: page-break-before, page-break-after, page-break-inside\n * - Hide elements: display: none for no-print classes\n * - Adjust font sizes and colors for print\n *\n * @param options - The HTML content and configuration for printing\n * @returns Promise that resolves when print dialog is dismissed\n * @throws Error if HTML is invalid or printing fails\n * @since 7.0.0\n * @example\n * ```typescript\n * // Simple HTML document\n * await Printer.printHtml({\n * name: 'Sales Report',\n * html: '<html><body><h1>Q4 Sales Report</h1><p>Revenue: $125,000</p></body></html>',\n * });\n *\n * // HTML with print-specific CSS\n * await Printer.printHtml({\n * name: 'Styled Invoice',\n * html: `\n * <html>\n * <head>\n * <style>\n * @media print {\n * body { font-size: 12pt; }\n * .no-print { display: none; }\n * h1 { page-break-before: always; }\n * }\n * </style>\n * </head>\n * <body>\n * <h1>Invoice #12345</h1>\n * <p>Amount due: $299.99</p>\n * <button class=\"no-print\">Don't print this button</button>\n * </body>\n * </html>\n * `,\n * });\n * ```\n */\n printHtml(options: PrintHtmlOptions): Promise<void>;\n\n /**\n * Presents the printing UI to print PDF documents.\n *\n * **Platform Behavior:**\n * - **iOS**: Uses UIPrintInteractionController with PDF file URL\n * - **Android**: Uses PrintManager with PdfDocument\n * - **Web**: Creates object URL and opens print dialog\n *\n * **File Path Requirements:**\n * - **iOS**: Must be file:// path or relative to app's documents directory\n * - **Android**: Supports content:// URIs (from downloads, media store) or file:// paths\n * - **Web**: Must be accessible file path\n *\n * @param options - The PDF file path and configuration for printing\n * @returns Promise that resolves when print dialog is dismissed\n * @throws Error if PDF path is invalid, file not found, or not a valid PDF\n * @since 7.0.0\n * @example\n * ```typescript\n * // Print PDF from app storage\n * await Printer.printPdf({\n * name: 'Annual Report 2024',\n * path: 'file:///var/mobile/Containers/Data/Application/.../Documents/report.pdf',\n * });\n *\n * // Print PDF from Android downloads\n * await Printer.printPdf({\n * name: 'Downloaded Document',\n * path: 'content://com.android.providers.downloads.documents/document/123',\n * });\n * ```\n */\n printPdf(options: PrintPdfOptions): Promise<void>;\n\n /**\n * Presents the printing UI to print web view content.\n *\n * Prints the current content displayed in your app's web view.\n *\n * **Platform Behavior:**\n * - **iOS**: Uses UIPrintInteractionController with WKWebView's view printable\n * - **Android**: Uses WebView.createPrintDocumentAdapter() with PrintManager\n * - **Web**: Triggers window.print() for current page\n *\n * **Print Styling:**\n * Supports CSS print media queries for customization. The web view's current\n * styles will be applied, including any @media print rules.\n *\n * **Use Cases:**\n * - Print the current app screen/page\n * - Print web-based reports or dashboards\n * - Print user-generated content displayed in web view\n *\n * @param options - Optional configuration for printing (name only)\n * @returns Promise that resolves when print dialog is dismissed\n * @throws Error if web view is not available or printing fails\n * @since 7.0.0\n * @example\n * ```typescript\n * // Print current web view with default name\n * await Printer.printWebView();\n *\n * // Print with custom job name\n * await Printer.printWebView({\n * name: 'Dashboard Screenshot',\n * });\n *\n * // Use with print-specific CSS in your HTML\n * // Add this to your app's CSS:\n * // @media print {\n * // .no-print { display: none; }\n * // body { font-size: 12pt; }\n * // }\n * await Printer.printWebView({\n * name: 'User Profile',\n * });\n * ```\n */\n\n /**\n * Presents the printing UI for content inside an iframe element.\n *\n * Useful when the full HTML document is too large to pass to printHtml().\n *\n * **Platform Behavior:**\n * - **iOS**: Evaluates JavaScript in the WebView to print the iframe content\n * - **Android**: Evaluates JavaScript in the WebView to print the iframe content\n * - **Web**: Finds the iframe and triggers its print dialog\n *\n * @param options - CSS selector and optional print job name\n * @returns Promise that resolves when print dialog is dismissed\n * @throws Error if the iframe is not found or printing fails\n * @since 8.0.19\n * @example\n * ```typescript\n * await Printer.printIframe({\n * selector: '#report-frame',\n * name: 'Monthly Report',\n * });\n * ```\n */\n printIframe(options: PrintIframeOptions): Promise<void>;\n\n printWebView(options?: PrintOptions): Promise<void>;\n\n /**\n * Get the native Capacitor plugin version.\n *\n * Returns the hardcoded plugin version from native code (iOS/Android) or\n * package version (Web). This is useful for debugging and ensuring plugin\n * compatibility.\n *\n * @returns Promise that resolves with the plugin version string\n * @throws Error if getting the version fails\n * @since 7.0.0\n * @example\n * ```typescript\n * const { version } = await Printer.getPluginVersion();\n * console.log('Printer plugin version:', version);\n * // Output: \"7.0.0\"\n * ```\n */\n getPluginVersion(): Promise<{ version: string }>;\n}\n\n/**\n * Options for printing base64 encoded data.\n *\n * @since 7.0.0\n */\nexport interface PrintBase64Options extends PrintOptions {\n /**\n * Valid base64 encoded string representing the file content.\n *\n * The base64 string should NOT include the data URL prefix (e.g., \"data:application/pdf;base64,\").\n * Only provide the raw base64 encoded content.\n *\n * **Performance Considerations:**\n * - Base64 encoding increases data size by approximately 33%\n * - Large files (>5MB) may cause memory issues when decoding\n * - Consider using printFile() for large documents\n *\n * **Platform Notes:**\n * - **iOS**: Decoded to NSData and passed to UIPrintInteractionController\n * - **Android**: Decoded to byte array and written to temporary file\n * - **Web**: Converted to Blob for printing\n *\n * @since 7.0.0\n * @example 'JVBERi0xLjQKJeLjz9MKMyAwIG9iago8PC9UeXBlL...'\n */\n data: string;\n\n /**\n * MIME type of the base64 encoded data.\n *\n * **Supported types:**\n * - `application/pdf` - PDF documents\n * - `image/jpeg` - JPEG images\n * - `image/png` - PNG images\n * - `image/gif` - GIF images (iOS/Android only)\n * - `image/heic` - HEIC images (iOS only)\n * - `image/heif` - HEIF images (iOS only)\n *\n * **Platform Support:**\n * - All platforms support PDF, JPEG, and PNG\n * - GIF support varies by platform\n * - HEIC/HEIF are iOS-specific formats\n *\n * @since 7.0.0\n * @example 'application/pdf'\n * @example 'image/jpeg'\n */\n mimeType: string;\n}\n\n/**\n * Options for printing files from device storage.\n *\n * @since 7.0.0\n */\nexport interface PrintFileOptions extends PrintOptions {\n /**\n * Path to the file to print.\n *\n * **iOS Path Formats:**\n * - `file://` URL: Full file URL path\n * - Relative path: Path relative to app's documents directory\n * - Must be within app's accessible directories (documents, temporary, cache)\n *\n * **Android Path Formats:**\n * - `content://` URI: Content provider URI (recommended for external files)\n * - `file://` path: Direct file system path\n * - Must have read permission for the file\n *\n * **Common Use Cases:**\n * - App documents: Files saved in app's document directory\n * - Downloads: Files from system downloads folder (use content:// on Android)\n * - Temporary files: Files in app's temporary/cache directory\n * - Shared storage: Files from external storage (Android, requires permissions)\n *\n * @since 7.0.0\n * @platform ios Supports file:// paths and relative paths\n * @platform android Supports content:// URIs and file:// paths\n * @example 'content://com.android.providers.downloads.documents/document/123'\n * @example 'file:///var/mobile/Containers/Data/Application/.../Documents/document.pdf'\n * @example 'file:///storage/emulated/0/Download/receipt.pdf'\n */\n path: string;\n\n /**\n * MIME type of the file.\n *\n * **Platform Behavior:**\n * - **Android**: REQUIRED for content:// URIs. Helps the system determine how to handle the file.\n * Optional for file:// paths (auto-detected from extension).\n * - **iOS**: Ignored. File type is auto-detected from file extension.\n * - **Web**: Optional. Auto-detected if not provided.\n *\n * **Common MIME Types:**\n * - `application/pdf` - PDF documents\n * - `image/jpeg` - JPEG images\n * - `image/png` - PNG images\n * - `image/gif` - GIF images\n *\n * @since 7.0.0\n * @default Undefined (auto-detected from file extension)\n * @platform android Used for content:// URIs and file type detection\n * @platform ios Ignored (auto-detected)\n * @example 'application/pdf'\n * @example 'image/jpeg'\n */\n mimeType?: string;\n}\n\n/**\n * Options for printing HTML content.\n *\n * @since 7.0.0\n */\nexport interface PrintHtmlOptions extends PrintOptions {\n /**\n * HTML content to print.\n *\n * **Content Requirements:**\n * - Should be a complete HTML document with `<html>`, `<head>`, and `<body>` tags\n * - Can include inline CSS styles or `<style>` tags\n * - External resources (images, fonts) should use absolute URLs\n * - JavaScript is not executed during print rendering\n *\n * **Print Optimization Tips:**\n * - Use `@media print` CSS rules for print-specific styling\n * - Control page breaks with `page-break-before`, `page-break-after`, `page-break-inside`\n * - Hide UI elements using `.no-print { display: none; }` class\n * - Adjust font sizes for readability (12pt is standard for print)\n * - Use print-friendly colors (avoid dark backgrounds)\n *\n * **Platform Rendering:**\n * - **iOS**: Rendered in WKWebView before printing\n * - **Android**: Rendered in WebView before printing\n * - **Web**: Rendered in hidden iframe before printing\n *\n * **Character Encoding:**\n * - UTF-8 is recommended and default\n * - Include charset in HTML: `<meta charset=\"UTF-8\">`\n *\n * @since 7.0.0\n * @example '<html><body><h1>Hello World</h1><p>This is a test document.</p></body></html>'\n * @example\n * ```typescript\n * const htmlWithStyles = `\n * <html>\n * <head>\n * <meta charset=\"UTF-8\">\n * <style>\n * @media print {\n * body { font-family: Arial, sans-serif; font-size: 12pt; }\n * .no-print { display: none; }\n * h1 { color: #333; page-break-before: always; }\n * }\n * </style>\n * </head>\n * <body>\n * <h1>Invoice #12345</h1>\n * <p>Amount: $299.99</p>\n * </body>\n * </html>\n * `;\n * ```\n */\n html: string;\n}\n\n/**\n * Options for printing PDF documents.\n *\n * @since 7.0.0\n */\nexport interface PrintPdfOptions extends PrintOptions {\n /**\n * Path to the PDF document.\n *\n * **iOS Path Formats:**\n * - `file://` URL: Full file URL path to PDF document\n * - Relative path: Path relative to app's documents directory\n * - Must be within app's accessible directories (documents, temporary, cache)\n * - PDF must be valid and not password-protected\n *\n * **Android Path Formats:**\n * - `content://` URI: Content provider URI (recommended for external PDFs)\n * - `file://` path: Direct file system path to PDF\n * - Must have read permission for the file\n * - Supports both single-page and multi-page PDFs\n *\n * **Web Path Formats:**\n * - Relative or absolute path accessible from web context\n * - Must be a valid PDF file\n *\n * **Validation:**\n * - File must exist at the specified path\n * - File must be a valid PDF (checked by magic number/header)\n * - File must be readable by the app\n *\n * **Common Sources:**\n * - App documents: PDFs saved in app's document directory\n * - Downloads: PDFs from system downloads (use content:// on Android)\n * - Generated PDFs: Temporary PDFs created by the app\n * - Network downloads: PDFs downloaded and saved locally\n *\n * @since 7.0.0\n * @platform ios Supports file:// paths and relative paths\n * @platform android Supports content:// URIs and file:// paths\n * @platform web Supports accessible file paths\n * @example 'content://com.android.providers.downloads.documents/document/123'\n * @example 'file:///var/mobile/Containers/Data/Application/.../Documents/document.pdf'\n * @example 'file:///storage/emulated/0/Download/report.pdf'\n * @example 'Documents/invoice-2024.pdf'\n */\n path: string;\n}\n\n/**\n * Base options for all print operations.\n *\n * @since 7.0.0\n */\nexport interface PrintOptions {\n /**\n * Name of the print job.\n *\n * **Usage:**\n * - Displayed in the system print queue\n * - Shown in print history/logs\n * - May appear in printer status displays\n * - Used as default filename for \"Save as PDF\" option\n *\n * **Platform Behavior:**\n * - **iOS**: Shown in print preview header and activity view\n * - **Android**: Displayed in print job notification and print queue\n * - **Web**: Used as document title in print dialog\n *\n * **Best Practices:**\n * - Use descriptive names (e.g., \"Invoice #12345\", \"Q4 Report\")\n * - Keep under 50 characters for better display\n * - Avoid special characters that may cause issues in filenames\n * - Include relevant identifiers (order numbers, dates, etc.)\n *\n * **Examples:**\n * - \"Invoice #12345\"\n * - \"Sales Report - 2024 Q4\"\n * - \"Customer Receipt - John Doe\"\n * - \"Product Photo - SKU-ABC123\"\n *\n * @since 7.0.0\n * @default 'Document'\n * @platform ios Shown in print preview and activity view\n * @platform android Shown in print queue and notifications\n * @platform web Used as document title in print dialog\n * @example 'Invoice #12345'\n * @example 'Annual Report 2024'\n * @example 'Receipt - Order #789'\n */\n name?: string;\n}\n\n/**\n * Type alias for print web view options.\n *\n * @since 7.0.0\n */\n\n/**\n * Options for printing iframe content.\n *\n * @since 8.0.19\n */\nexport interface PrintIframeOptions extends PrintOptions {\n /**\n * CSS selector for the iframe element to print.\n *\n * The selector must match a single iframe in the current document.\n *\n * @since 8.0.19\n * @example '#report-frame'\n * @example 'iframe[name=\"invoice\"]'\n */\n selector: string;\n}\n\nexport type PrintWebViewOptions = PrintOptions;\n"]}
package/dist/esm/web.d.ts CHANGED
@@ -1,10 +1,11 @@
1
1
  import { WebPlugin } from '@capacitor/core';
2
- import type { PrintBase64Options, PrintFileOptions, PrintHtmlOptions, PrintOptions, PrintPdfOptions, PrinterPlugin } from './definitions';
2
+ import type { PrintBase64Options, PrintFileOptions, PrintHtmlOptions, PrintOptions, PrintIframeOptions, PrintPdfOptions, PrinterPlugin } from './definitions';
3
3
  export declare class PrinterWeb extends WebPlugin implements PrinterPlugin {
4
4
  printBase64(options: PrintBase64Options): Promise<void>;
5
5
  printFile(options: PrintFileOptions): Promise<void>;
6
6
  printHtml(options: PrintHtmlOptions): Promise<void>;
7
7
  printPdf(options: PrintPdfOptions): Promise<void>;
8
+ printIframe(options: PrintIframeOptions): Promise<void>;
8
9
  printWebView(options?: PrintOptions): Promise<void>;
9
10
  getPluginVersion(): Promise<{
10
11
  version: string;
package/dist/esm/web.js CHANGED
@@ -1,8 +1,10 @@
1
1
  import { WebPlugin } from '@capacitor/core';
2
+ const PDF_PRINT_DELAY_MS = 500;
3
+ const HTML_PRINT_DELAY_MS = 100;
4
+ const CLEANUP_FALLBACK_MS = 60000;
2
5
  export class PrinterWeb extends WebPlugin {
3
6
  async printBase64(options) {
4
7
  const { data, mimeType, name } = options;
5
- // Convert base64 to blob
6
8
  const byteCharacters = atob(data);
7
9
  const byteNumbers = new Array(byteCharacters.length);
8
10
  for (let i = 0; i < byteCharacters.length; i++) {
@@ -10,47 +12,60 @@ export class PrinterWeb extends WebPlugin {
10
12
  }
11
13
  const byteArray = new Uint8Array(byteNumbers);
12
14
  const blob = new Blob([byteArray], { type: mimeType });
13
- // Create object URL and print
14
15
  const url = URL.createObjectURL(blob);
15
- await this.printFromUrl(url, name);
16
- URL.revokeObjectURL(url);
16
+ try {
17
+ await this.printFromUrl(url, name, mimeType);
18
+ }
19
+ finally {
20
+ URL.revokeObjectURL(url);
21
+ }
17
22
  }
18
23
  async printFile(options) {
19
- const { path, name } = options;
20
- // On web, we can only print URLs that are accessible
21
- // This will work for file:// URLs in some browsers or HTTP(S) URLs
22
- await this.printFromUrl(path, name);
24
+ const { path, name, mimeType } = options;
25
+ await this.printFromUrl(path, name, mimeType);
23
26
  }
24
27
  async printHtml(options) {
25
28
  const { html, name } = options;
26
- // Create a blob URL from the HTML content
27
29
  const blob = new Blob([html], { type: 'text/html' });
28
30
  const url = URL.createObjectURL(blob);
29
- await this.printFromUrl(url, name);
30
- URL.revokeObjectURL(url);
31
+ try {
32
+ await this.printFromUrl(url, name, 'text/html');
33
+ }
34
+ finally {
35
+ URL.revokeObjectURL(url);
36
+ }
31
37
  }
32
38
  async printPdf(options) {
33
39
  const { path, name } = options;
34
- // On web, print the PDF URL
35
- await this.printFromUrl(path, name);
40
+ await this.printFromUrl(path, name, 'application/pdf');
41
+ }
42
+ async printIframe(options) {
43
+ const { selector, name } = options;
44
+ const iframe = document.querySelector(selector);
45
+ if (!(iframe instanceof HTMLIFrameElement) || !iframe.contentWindow) {
46
+ throw new Error(`iframe not found: ${selector}`);
47
+ }
48
+ const originalTitle = document.title;
49
+ if (name) {
50
+ document.title = name;
51
+ }
52
+ iframe.contentWindow.focus();
53
+ iframe.contentWindow.print();
54
+ document.title = originalTitle;
36
55
  }
37
56
  async printWebView(options) {
38
- // Set document title for print job name
39
57
  const originalTitle = document.title;
40
58
  if (options === null || options === void 0 ? void 0 : options.name) {
41
59
  document.title = options.name;
42
60
  }
43
- // Trigger browser print dialog
44
61
  window.print();
45
- // Restore original title
46
62
  document.title = originalTitle;
47
63
  }
48
64
  async getPluginVersion() {
49
65
  return { version: '7.0.0' };
50
66
  }
51
- async printFromUrl(url, name) {
67
+ async printFromUrl(url, name, mimeType) {
52
68
  return new Promise((resolve, reject) => {
53
- // Create hidden iframe
54
69
  const iframe = document.createElement('iframe');
55
70
  iframe.style.position = 'fixed';
56
71
  iframe.style.right = '0';
@@ -58,46 +73,45 @@ export class PrinterWeb extends WebPlugin {
58
73
  iframe.style.width = '0';
59
74
  iframe.style.height = '0';
60
75
  iframe.style.border = 'none';
61
- // Set up load handler
62
- iframe.onload = () => {
63
- try {
64
- // Set document title if name provided
65
- if (name && iframe.contentDocument) {
66
- iframe.contentDocument.title = name;
67
- }
68
- // Small delay to ensure content is loaded
69
- setTimeout(() => {
70
- try {
71
- // Try to access the iframe's window
72
- const iframeWindow = iframe.contentWindow;
73
- if (!iframeWindow) {
74
- throw new Error('Cannot access iframe window');
75
- }
76
- // Print the iframe content
77
- iframeWindow.focus();
78
- iframeWindow.print();
79
- // Clean up after a delay
80
- setTimeout(() => {
81
- document.body.removeChild(iframe);
82
- resolve();
83
- }, 100);
84
- }
85
- catch (error) {
86
- document.body.removeChild(iframe);
87
- reject(error);
88
- }
89
- }, 100);
76
+ let cleanedUp = false;
77
+ const cleanup = () => {
78
+ if (cleanedUp) {
79
+ return;
90
80
  }
91
- catch (error) {
81
+ cleanedUp = true;
82
+ if (iframe.parentNode) {
92
83
  document.body.removeChild(iframe);
93
- reject(error);
94
84
  }
85
+ resolve();
86
+ };
87
+ const printDelayMs = (mimeType === null || mimeType === void 0 ? void 0 : mimeType.toLowerCase()) === 'application/pdf' ? PDF_PRINT_DELAY_MS : HTML_PRINT_DELAY_MS;
88
+ iframe.onload = () => {
89
+ window.setTimeout(() => {
90
+ try {
91
+ const iframeWindow = iframe.contentWindow;
92
+ if (!iframeWindow) {
93
+ throw new Error('Cannot access iframe window');
94
+ }
95
+ if (name && iframe.contentDocument) {
96
+ iframe.contentDocument.title = name;
97
+ }
98
+ iframeWindow.addEventListener('afterprint', () => cleanup(), { once: true });
99
+ iframeWindow.focus();
100
+ iframeWindow.print();
101
+ window.setTimeout(() => cleanup(), CLEANUP_FALLBACK_MS);
102
+ }
103
+ catch (error) {
104
+ cleanup();
105
+ reject(error);
106
+ }
107
+ }, printDelayMs);
95
108
  };
96
109
  iframe.onerror = () => {
97
- document.body.removeChild(iframe);
110
+ if (iframe.parentNode) {
111
+ document.body.removeChild(iframe);
112
+ }
98
113
  reject(new Error('Failed to load content for printing'));
99
114
  };
100
- // Add iframe to document and set source
101
115
  document.body.appendChild(iframe);
102
116
  iframe.src = url;
103
117
  });
@@ -1 +1 @@
1
- {"version":3,"file":"web.js","sourceRoot":"","sources":["../../src/web.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAW5C,MAAM,OAAO,UAAW,SAAQ,SAAS;IACvC,KAAK,CAAC,WAAW,CAAC,OAA2B;QAC3C,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAE,GAAG,OA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AAC,IAAI,KAAK,CAAC,qCAAqC,CAAC,CAAC,CAAC;YAC3D,CAAC,CAAC;YAEF,wCAAwC;YACxC,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC;YAClC,MAAM,CAAC,GAAG,GAAG,GAAG,CAAC;QACnB,CAAC,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["import { WebPlugin } from '@capacitor/core';\n\nimport type {\n PrintBase64Options,\n PrintFileOptions,\n PrintHtmlOptions,\n PrintOptions,\n PrintPdfOptions,\n PrinterPlugin,\n} from './definitions';\n\nexport class PrinterWeb extends WebPlugin implements PrinterPlugin {\n async printBase64(options: PrintBase64Options): Promise<void> {\n const { data, mimeType, name } = options;\n\n // Convert base64 to blob\n const byteCharacters = atob(data);\n const byteNumbers = new Array(byteCharacters.length);\n for (let i = 0; i < byteCharacters.length; i++) {\n byteNumbers[i] = byteCharacters.charCodeAt(i);\n }\n const byteArray = new Uint8Array(byteNumbers);\n const blob = new Blob([byteArray], { type: mimeType });\n\n // Create object URL and print\n const url = URL.createObjectURL(blob);\n await this.printFromUrl(url, name);\n URL.revokeObjectURL(url);\n }\n\n async printFile(options: PrintFileOptions): Promise<void> {\n const { path, name } = options;\n\n // On web, we can only print URLs that are accessible\n // This will work for file:// URLs in some browsers or HTTP(S) URLs\n await this.printFromUrl(path, name);\n }\n\n async printHtml(options: PrintHtmlOptions): Promise<void> {\n const { html, name } = options;\n\n // Create a blob URL from the HTML content\n const blob = new Blob([html], { type: 'text/html' });\n const url = URL.createObjectURL(blob);\n await this.printFromUrl(url, name);\n URL.revokeObjectURL(url);\n }\n\n async printPdf(options: PrintPdfOptions): Promise<void> {\n const { path, name } = options;\n\n // On web, print the PDF URL\n await this.printFromUrl(path, name);\n }\n\n async printWebView(options?: PrintOptions): Promise<void> {\n // Set document title for print job name\n const originalTitle = document.title;\n if (options?.name) {\n document.title = options.name;\n }\n\n // Trigger browser print dialog\n window.print();\n\n // Restore original title\n document.title = originalTitle;\n }\n\n async getPluginVersion(): Promise<{ version: string }> {\n return { version: '7.0.0' };\n }\n\n private async printFromUrl(url: string, name?: string): Promise<void> {\n return new Promise((resolve, reject) => {\n // Create hidden iframe\n const iframe = document.createElement('iframe');\n iframe.style.position = 'fixed';\n iframe.style.right = '0';\n iframe.style.bottom = '0';\n iframe.style.width = '0';\n iframe.style.height = '0';\n iframe.style.border = 'none';\n\n // Set up load handler\n iframe.onload = () => {\n try {\n // Set document title if name provided\n if (name && iframe.contentDocument) {\n iframe.contentDocument.title = name;\n }\n\n // Small delay to ensure content is loaded\n setTimeout(() => {\n try {\n // Try to access the iframe's window\n const iframeWindow = iframe.contentWindow;\n if (!iframeWindow) {\n throw new Error('Cannot access iframe window');\n }\n\n // Print the iframe content\n iframeWindow.focus();\n iframeWindow.print();\n\n // Clean up after a delay\n setTimeout(() => {\n document.body.removeChild(iframe);\n resolve();\n }, 100);\n } catch (error) {\n document.body.removeChild(iframe);\n reject(error);\n }\n }, 100);\n } catch (error) {\n document.body.removeChild(iframe);\n reject(error);\n }\n };\n\n iframe.onerror = () => {\n document.body.removeChild(iframe);\n reject(new Error('Failed to load content for printing'));\n };\n\n // Add iframe to document and set source\n document.body.appendChild(iframe);\n iframe.src = url;\n });\n }\n}\n"]}
1
+ {"version":3,"file":"web.js","sourceRoot":"","sources":["../../src/web.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAY5C,MAAM,kBAAkB,GAAG,GAAG,CAAC;AAC/B,MAAM,mBAAmB,GAAG,GAAG,CAAC;AAChC,MAAM,mBAAmB,GAAG,KAAM,CAAC;AAEnC,MAAM,OAAO,UAAW,SAAQ,SAAS;IACvC,KAAK,CAAC,WAAW,CAAC,OAA2B;QAC3C,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAE,GAAG,OAAO,CAAC;QAEzC,MAAM,cAAc,GAAG,IAAI,CAAC,IAAI,CAAC,CAAC;QAClC,MAA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M,CAAC,aAAa,CAAC;wBAC1C,IAAI,CAAC,YAAY,EAAE,CAAC;4BAClB,MAAM,IAAI,KAAK,CAAC,6BAA6B,CAAC,CAAC;wBACjD,CAAC;wBAED,IAAI,IAAI,IAAI,MAAM,CAAC,eAAe,EAAE,CAAC;4BACnC,MAAM,CAAC,eAAe,CAAC,KAAK,GAAG,IAAI,CAAC;wBACtC,CAAC;wBAED,YAAY,CAAC,gBAAgB,CAAC,YAAY,EAAE,GAAG,EAAE,CAAC,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;wBAC7E,YAAY,CAAC,KAAK,EAAE,CAAC;wBACrB,YAAY,CAAC,KAAK,EAAE,CAAC;wBACrB,MAAM,CAAC,UAAU,CAAC,GAAG,EAAE,CAAC,OAAO,EAAE,EAAE,mBAAmB,CAAC,CAAC;oBAC1D,CAAC;oBAAC,OAAO,KAAK,EAAE,CAAC;wBACf,OAAO,EAAE,CAAC;wBACV,MAAM,CAAC,KAAK,CAAC,CAAC;oBAChB,CAAC;gBACH,CAAC,EAAE,YAAY,CAAC,CAAC;YACnB,CAAC,CAAC;YAEF,MAAM,CAAC,OAAO,GAAG,GAAG,EAAE;gBACpB,IAAI,MAAM,CAAC,UAAU,EAAE,CAAC;oBACtB,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC;gBACpC,CAAC;gBACD,MAAM,CAAC,IAAI,KAAK,CAAC,qCAAqC,CAAC,CAAC,CAAC;YAC3D,CAAC,CAAC;YAEF,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC;YAClC,MAAM,CAAC,GAAG,GAAG,GAAG,CAAC;QACnB,CAAC,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["import { WebPlugin } from '@capacitor/core';\n\nimport type {\n PrintBase64Options,\n PrintFileOptions,\n PrintHtmlOptions,\n PrintOptions,\n PrintIframeOptions,\n PrintPdfOptions,\n PrinterPlugin,\n} from './definitions';\n\nconst PDF_PRINT_DELAY_MS = 500;\nconst HTML_PRINT_DELAY_MS = 100;\nconst CLEANUP_FALLBACK_MS = 60_000;\n\nexport class PrinterWeb extends WebPlugin implements PrinterPlugin {\n async printBase64(options: PrintBase64Options): Promise<void> {\n const { data, mimeType, name } = options;\n\n const byteCharacters = atob(data);\n const byteNumbers = new Array(byteCharacters.length);\n for (let i = 0; i < byteCharacters.length; i++) {\n byteNumbers[i] = byteCharacters.charCodeAt(i);\n }\n const byteArray = new Uint8Array(byteNumbers);\n const blob = new Blob([byteArray], { type: mimeType });\n\n const url = URL.createObjectURL(blob);\n try {\n await this.printFromUrl(url, name, mimeType);\n } finally {\n URL.revokeObjectURL(url);\n }\n }\n\n async printFile(options: PrintFileOptions): Promise<void> {\n const { path, name, mimeType } = options;\n await this.printFromUrl(path, name, mimeType);\n }\n\n async printHtml(options: PrintHtmlOptions): Promise<void> {\n const { html, name } = options;\n\n const blob = new Blob([html], { type: 'text/html' });\n const url = URL.createObjectURL(blob);\n try {\n await this.printFromUrl(url, name, 'text/html');\n } finally {\n URL.revokeObjectURL(url);\n }\n }\n\n async printPdf(options: PrintPdfOptions): Promise<void> {\n const { path, name } = options;\n await this.printFromUrl(path, name, 'application/pdf');\n }\n\n async printIframe(options: PrintIframeOptions): Promise<void> {\n const { selector, name } = options;\n const iframe = document.querySelector(selector);\n\n if (!(iframe instanceof HTMLIFrameElement) || !iframe.contentWindow) {\n throw new Error(`iframe not found: ${selector}`);\n }\n\n const originalTitle = document.title;\n if (name) {\n document.title = name;\n }\n\n iframe.contentWindow.focus();\n iframe.contentWindow.print();\n\n document.title = originalTitle;\n }\n\n async printWebView(options?: PrintOptions): Promise<void> {\n const originalTitle = document.title;\n if (options?.name) {\n document.title = options.name;\n }\n\n window.print();\n\n document.title = originalTitle;\n }\n\n async getPluginVersion(): Promise<{ version: string }> {\n return { version: '7.0.0' };\n }\n\n private async printFromUrl(url: string, name?: string, mimeType?: string): Promise<void> {\n return new Promise((resolve, reject) => {\n const iframe = document.createElement('iframe');\n iframe.style.position = 'fixed';\n iframe.style.right = '0';\n iframe.style.bottom = '0';\n iframe.style.width = '0';\n iframe.style.height = '0';\n iframe.style.border = 'none';\n\n let cleanedUp = false;\n const cleanup = () => {\n if (cleanedUp) {\n return;\n }\n cleanedUp = true;\n if (iframe.parentNode) {\n document.body.removeChild(iframe);\n }\n resolve();\n };\n\n const printDelayMs = mimeType?.toLowerCase() === 'application/pdf' ? PDF_PRINT_DELAY_MS : HTML_PRINT_DELAY_MS;\n\n iframe.onload = () => {\n window.setTimeout(() => {\n try {\n const iframeWindow = iframe.contentWindow;\n if (!iframeWindow) {\n throw new Error('Cannot access iframe window');\n }\n\n if (name && iframe.contentDocument) {\n iframe.contentDocument.title = name;\n }\n\n iframeWindow.addEventListener('afterprint', () => cleanup(), { once: true });\n iframeWindow.focus();\n iframeWindow.print();\n window.setTimeout(() => cleanup(), CLEANUP_FALLBACK_MS);\n } catch (error) {\n cleanup();\n reject(error);\n }\n }, printDelayMs);\n };\n\n iframe.onerror = () => {\n if (iframe.parentNode) {\n document.body.removeChild(iframe);\n }\n reject(new Error('Failed to load content for printing'));\n };\n\n document.body.appendChild(iframe);\n iframe.src = url;\n });\n }\n}\n"]}
@@ -6,10 +6,12 @@ const Printer = core.registerPlugin('Printer', {
6
6
  web: () => Promise.resolve().then(function () { return web; }).then((m) => new m.PrinterWeb()),
7
7
  });
8
8
 
9
+ const PDF_PRINT_DELAY_MS = 500;
10
+ const HTML_PRINT_DELAY_MS = 100;
11
+ const CLEANUP_FALLBACK_MS = 60000;
9
12
  class PrinterWeb extends core.WebPlugin {
10
13
  async printBase64(options) {
11
14
  const { data, mimeType, name } = options;
12
- // Convert base64 to blob
13
15
  const byteCharacters = atob(data);
14
16
  const byteNumbers = new Array(byteCharacters.length);
15
17
  for (let i = 0; i < byteCharacters.length; i++) {
@@ -17,47 +19,60 @@ class PrinterWeb extends core.WebPlugin {
17
19
  }
18
20
  const byteArray = new Uint8Array(byteNumbers);
19
21
  const blob = new Blob([byteArray], { type: mimeType });
20
- // Create object URL and print
21
22
  const url = URL.createObjectURL(blob);
22
- await this.printFromUrl(url, name);
23
- URL.revokeObjectURL(url);
23
+ try {
24
+ await this.printFromUrl(url, name, mimeType);
25
+ }
26
+ finally {
27
+ URL.revokeObjectURL(url);
28
+ }
24
29
  }
25
30
  async printFile(options) {
26
- const { path, name } = options;
27
- // On web, we can only print URLs that are accessible
28
- // This will work for file:// URLs in some browsers or HTTP(S) URLs
29
- await this.printFromUrl(path, name);
31
+ const { path, name, mimeType } = options;
32
+ await this.printFromUrl(path, name, mimeType);
30
33
  }
31
34
  async printHtml(options) {
32
35
  const { html, name } = options;
33
- // Create a blob URL from the HTML content
34
36
  const blob = new Blob([html], { type: 'text/html' });
35
37
  const url = URL.createObjectURL(blob);
36
- await this.printFromUrl(url, name);
37
- URL.revokeObjectURL(url);
38
+ try {
39
+ await this.printFromUrl(url, name, 'text/html');
40
+ }
41
+ finally {
42
+ URL.revokeObjectURL(url);
43
+ }
38
44
  }
39
45
  async printPdf(options) {
40
46
  const { path, name } = options;
41
- // On web, print the PDF URL
42
- await this.printFromUrl(path, name);
47
+ await this.printFromUrl(path, name, 'application/pdf');
48
+ }
49
+ async printIframe(options) {
50
+ const { selector, name } = options;
51
+ const iframe = document.querySelector(selector);
52
+ if (!(iframe instanceof HTMLIFrameElement) || !iframe.contentWindow) {
53
+ throw new Error(`iframe not found: ${selector}`);
54
+ }
55
+ const originalTitle = document.title;
56
+ if (name) {
57
+ document.title = name;
58
+ }
59
+ iframe.contentWindow.focus();
60
+ iframe.contentWindow.print();
61
+ document.title = originalTitle;
43
62
  }
44
63
  async printWebView(options) {
45
- // Set document title for print job name
46
64
  const originalTitle = document.title;
47
65
  if (options === null || options === void 0 ? void 0 : options.name) {
48
66
  document.title = options.name;
49
67
  }
50
- // Trigger browser print dialog
51
68
  window.print();
52
- // Restore original title
53
69
  document.title = originalTitle;
54
70
  }
55
71
  async getPluginVersion() {
56
72
  return { version: '7.0.0' };
57
73
  }
58
- async printFromUrl(url, name) {
74
+ async printFromUrl(url, name, mimeType) {
59
75
  return new Promise((resolve, reject) => {
60
- // Create hidden iframe
61
76
  const iframe = document.createElement('iframe');
62
77
  iframe.style.position = 'fixed';
63
78
  iframe.style.right = '0';
@@ -65,46 +80,45 @@ class PrinterWeb extends core.WebPlugin {
65
80
  iframe.style.width = '0';
66
81
  iframe.style.height = '0';
67
82
  iframe.style.border = 'none';
68
- // Set up load handler
69
- iframe.onload = () => {
70
- try {
71
- // Set document title if name provided
72
- if (name && iframe.contentDocument) {
73
- iframe.contentDocument.title = name;
74
- }
75
- // Small delay to ensure content is loaded
76
- setTimeout(() => {
77
- try {
78
- // Try to access the iframe's window
79
- const iframeWindow = iframe.contentWindow;
80
- if (!iframeWindow) {
81
- throw new Error('Cannot access iframe window');
82
- }
83
- // Print the iframe content
84
- iframeWindow.focus();
85
- iframeWindow.print();
86
- // Clean up after a delay
87
- setTimeout(() => {
88
- document.body.removeChild(iframe);
89
- resolve();
90
- }, 100);
91
- }
92
- catch (error) {
93
- document.body.removeChild(iframe);
94
- reject(error);
95
- }
96
- }, 100);
83
+ let cleanedUp = false;
84
+ const cleanup = () => {
85
+ if (cleanedUp) {
86
+ return;
97
87
  }
98
- catch (error) {
88
+ cleanedUp = true;
89
+ if (iframe.parentNode) {
99
90
  document.body.removeChild(iframe);
100
- reject(error);
101
91
  }
92
+ resolve();
93
+ };
94
+ const printDelayMs = (mimeType === null || mimeType === void 0 ? void 0 : mimeType.toLowerCase()) === 'application/pdf' ? PDF_PRINT_DELAY_MS : HTML_PRINT_DELAY_MS;
95
+ iframe.onload = () => {
96
+ window.setTimeout(() => {
97
+ try {
98
+ const iframeWindow = iframe.contentWindow;
99
+ if (!iframeWindow) {
100
+ throw new Error('Cannot access iframe window');
101
+ }
102
+ if (name && iframe.contentDocument) {
103
+ iframe.contentDocument.title = name;
104
+ }
105
+ iframeWindow.addEventListener('afterprint', () => cleanup(), { once: true });
106
+ iframeWindow.focus();
107
+ iframeWindow.print();
108
+ window.setTimeout(() => cleanup(), CLEANUP_FALLBACK_MS);
109
+ }
110
+ catch (error) {
111
+ cleanup();
112
+ reject(error);
113
+ }
114
+ }, printDelayMs);
102
115
  };
103
116
  iframe.onerror = () => {
104
- document.body.removeChild(iframe);
117
+ if (iframe.parentNode) {
118
+ document.body.removeChild(iframe);
119
+ }
105
120
  reject(new Error('Failed to load content for printing'));
106
121
  };
107
- // Add iframe to document and set source
108
122
  document.body.appendChild(iframe);
109
123
  iframe.src = url;
110
124
  });
@@ -1 +1 @@
1
- {"version":3,"file":"plugin.cjs.js","sources":["esm/index.js","esm/web.js"],"sourcesContent":["import { registerPlugin } from '@capacitor/core';\nconst Printer = registerPlugin('Printer', {\n web: () => import('./web').then((m) => new m.PrinterWeb()),\n});\nexport * from './definitions';\nexport { Printer };\n//# sourceMappingURL=index.js.map","import { WebPlugin } from '@capacitor/core';\nexport class PrinterWeb extends WebPlugin {\n async printBase64(options) {\n const { data, mimeType, name } = options;\n // Convert base64 to blob\n const byteCharacters = atob(data);\n const byteNumbers = new Array(byteCharacters.length);\n for (let i = 0; i < byteCharacters.length; i++) {\n byteNumbers[i] = byteCharacters.charCodeAt(i);\n }\n const byteArray = new Uint8Array(byteNumbers);\n const blob = new Blob([byteArray], { type: mimeType });\n // Create object URL and print\n const url = URL.createObjectURL(blob);\n await this.printFromUrl(url, name);\n URL.revokeObjectURL(url);\n }\n async printFile(options) {\n const { path, name } = options;\n // On web, we can only print URLs that are accessible\n // This will work for file:// URLs in some browsers or HTTP(S) URLs\n await this.printFromUrl(path, name);\n }\n async printHtml(options) {\n const { html, name } = options;\n // Create a blob URL from the HTML content\n const blob = new Blob([html], { type: 'text/html' });\n const url = URL.createObjectURL(blob);\n await this.printFromUrl(url, name);\n URL.revokeObjectURL(url);\n }\n async printPdf(options) {\n const { path, name } = options;\n // On web, print the PDF URL\n await this.printFromUrl(path, name);\n }\n async printWebView(options) {\n // Set document title for print job name\n const originalTitle = document.title;\n if (options === null || options === void 0 ? void 0 : options.name) {\n document.title = options.name;\n }\n // Trigger browser print dialog\n window.print();\n // Restore original title\n document.title = originalTitle;\n }\n async getPluginVersion() {\n return { version: '7.0.0' };\n }\n async printFromUrl(url, name) {\n return new Promise((resolve, reject) => {\n // Create hidden iframe\n const iframe = document.createElement('iframe');\n iframe.style.position = 'fixed';\n iframe.style.right = '0';\n iframe.style.bottom = '0';\n iframe.style.width = '0';\n iframe.style.height = '0';\n iframe.style.border = 'none';\n // Set up load handler\n iframe.onload = () => {\n try {\n // Set document title if name provided\n if (name && iframe.contentDocument) {\n iframe.contentDocument.title = name;\n }\n // Small delay to ensure content is loaded\n setTimeout(() => {\n try {\n // Try to access the iframe's window\n const iframeWindow = iframe.contentWindow;\n if (!iframeWindow) {\n throw new Error('Cannot access iframe window');\n }\n // Print the iframe content\n iframeWindow.focus();\n iframeWindow.print();\n // Clean up after a delay\n setTimeout(() => {\n document.body.removeChild(iframe);\n resolve();\n }, 100);\n }\n catch (error) {\n document.body.removeChild(iframe);\n reject(error);\n }\n }, 100);\n }\n catch (error) {\n document.body.removeChild(iframe);\n reject(error);\n }\n };\n iframe.onerror = () => {\n document.body.removeChild(iframe);\n reject(new Error('Failed to load content for printing'));\n };\n // Add iframe to document and set source\n document.body.appendChild(iframe);\n iframe.src = url;\n });\n }\n}\n//# sourceMappingURL=web.js.map"],"names":["registerPlugin","WebPlugin"],"mappings":";;;;AACK,MAAC,OAAO,GAAGA,mBAAc,CAAC,SAAS,EAAE;AAC1C,IAAI,GAAG,EAAE,MAAM,mDAAe,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,IAAI,CAAC,CAAC,UAAU,EAAE,CAAC;AAC9D,CAAC;;ACFM,MAAM,UAAU,SAASC,cAAS,CAAC;AAC1C,IAAI,MAAM,WAAW,CAAC,OAAO,EAAE;AAC/B,QAAQ,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAE,G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AM,CAAC,IAAI,KAAK,CAAC,qCAAqC,CAAC,CAAC;AACxE,YAAY,CAAC;AACb;AACA,YAAY,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC;AAC7C,YAAY,MAAM,CAAC,GAAG,GAAG,GAAG;AAC5B,QAAQ,CAAC,CAAC;AACV,IAAI;AACJ;;;;;;;;;"}
1
+ {"version":3,"file":"plugin.cjs.js","sources":["esm/index.js","esm/web.js"],"sourcesContent":["import { registerPlugin } from '@capacitor/core';\nconst Printer = registerPlugin('Printer', {\n web: () => import('./web').then((m) => new m.PrinterWeb()),\n});\nexport * from './definitions';\nexport { Printer };\n//# sourceMappingURL=index.js.map","import { WebPlugin } from '@capacitor/core';\nconst PDF_PRINT_DELAY_MS = 500;\nconst HTML_PRINT_DELAY_MS = 100;\nconst CLEANUP_FALLBACK_MS = 60000;\nexport class PrinterWeb extends WebPlugin {\n async printBase64(options) {\n const { data, mimeType, name } = options;\n const byteCharacters = atob(data);\n const byteNumbers = new Array(byteCharacters.length);\n for (let i = 0; i < byteCharacters.length; i++) {\n byteNumbers[i] = byteCharacters.charCodeAt(i);\n }\n const byteArray = new Uint8Array(byteNumbers);\n const blob = new Blob([byteArray], { type: mimeType });\n const url = URL.createObjectURL(blob);\n try {\n await this.printFromUrl(url, name, mimeType);\n }\n finally {\n URL.revokeObjectURL(url);\n }\n }\n async printFile(options) {\n const { path, name, mimeType } = options;\n await this.printFromUrl(path, name, mimeType);\n }\n async printHtml(options) {\n const { html, name } = options;\n const blob = new Blob([html], { type: 'text/html' });\n const url = URL.createObjectURL(blob);\n try {\n await this.printFromUrl(url, name, 'text/html');\n }\n finally {\n URL.revokeObjectURL(url);\n }\n }\n async printPdf(options) {\n const { path, name } = options;\n await this.printFromUrl(path, name, 'application/pdf');\n }\n async printIframe(options) {\n const { selector, name } = options;\n const iframe = document.querySelector(selector);\n if (!(iframe instanceof HTMLIFrameElement) || !iframe.contentWindow) {\n throw new Error(`iframe not found: ${selector}`);\n }\n const originalTitle = document.title;\n if (name) {\n document.title = name;\n }\n iframe.contentWindow.focus();\n iframe.contentWindow.print();\n document.title = originalTitle;\n }\n async printWebView(options) {\n const originalTitle = document.title;\n if (options === null || options === void 0 ? void 0 : options.name) {\n document.title = options.name;\n }\n window.print();\n document.title = originalTitle;\n }\n async getPluginVersion() {\n return { version: '7.0.0' };\n }\n async printFromUrl(url, name, mimeType) {\n return new Promise((resolve, reject) => {\n const iframe = document.createElement('iframe');\n iframe.style.position = 'fixed';\n iframe.style.right = '0';\n iframe.style.bottom = '0';\n iframe.style.width = '0';\n iframe.style.height = '0';\n iframe.style.border = 'none';\n let cleanedUp = false;\n const cleanup = () => {\n if (cleanedUp) {\n return;\n }\n cleanedUp = true;\n if (iframe.parentNode) {\n document.body.removeChild(iframe);\n }\n resolve();\n };\n const printDelayMs = (mimeType === null || mimeType === void 0 ? void 0 : mimeType.toLowerCase()) === 'application/pdf' ? PDF_PRINT_DELAY_MS : HTML_PRINT_DELAY_MS;\n iframe.onload = () => {\n window.setTimeout(() => {\n try {\n const iframeWindow = iframe.contentWindow;\n if (!iframeWindow) {\n throw new Error('Cannot access iframe window');\n }\n if (name && iframe.contentDocument) {\n iframe.contentDocument.title = name;\n }\n iframeWindow.addEventListener('afterprint', () => cleanup(), { once: true });\n iframeWindow.focus();\n iframeWindow.print();\n window.setTimeout(() => cleanup(), CLEANUP_FALLBACK_MS);\n }\n catch (error) {\n cleanup();\n reject(error);\n }\n }, printDelayMs);\n };\n iframe.onerror = () => {\n if (iframe.parentNode) {\n document.body.removeChild(iframe);\n }\n reject(new Error('Failed to load content for printing'));\n };\n document.body.appendChild(iframe);\n iframe.src = url;\n });\n }\n}\n//# sourceMappingURL=web.js.map"],"names":["registerPlugin","WebPlugin"],"mappings":";;;;AACK,MAAC,OAAO,GAAGA,mBAAc,CAAC,SAAS,EAAE;AAC1C,IAAI,GAAG,EAAE,MAAM,mDAAe,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,IAAI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AAC;AAChC,YAAY,CAAC;AACb,YAAY,MAAM,CAAC,OAAO,GAAG,MAAM;AACnC,gBAAgB,IAAI,MAAM,CAAC,UAAU,EAAE;AACvC,oBAAoB,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC;AACrD,gBAAgB;AAChB,gBAAgB,MAAM,CAAC,IAAI,KAAK,CAAC,qCAAqC,CAAC,CAAC;AACxE,YAAY,CAAC;AACb,YAAY,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC;AAC7C,YAAY,MAAM,CAAC,GAAG,GAAG,GAAG;AAC5B,QAAQ,CAAC,CAAC;AACV,IAAI;AACJ;;;;;;;;;"}
package/dist/plugin.js CHANGED
@@ -5,10 +5,12 @@ var capacitorPrinter = (function (exports, core) {
5
5
  web: () => Promise.resolve().then(function () { return web; }).then((m) => new m.PrinterWeb()),
6
6
  });
7
7
 
8
+ const PDF_PRINT_DELAY_MS = 500;
9
+ const HTML_PRINT_DELAY_MS = 100;
10
+ const CLEANUP_FALLBACK_MS = 60000;
8
11
  class PrinterWeb extends core.WebPlugin {
9
12
  async printBase64(options) {
10
13
  const { data, mimeType, name } = options;
11
- // Convert base64 to blob
12
14
  const byteCharacters = atob(data);
13
15
  const byteNumbers = new Array(byteCharacters.length);
14
16
  for (let i = 0; i < byteCharacters.length; i++) {
@@ -16,47 +18,60 @@ var capacitorPrinter = (function (exports, core) {
16
18
  }
17
19
  const byteArray = new Uint8Array(byteNumbers);
18
20
  const blob = new Blob([byteArray], { type: mimeType });
19
- // Create object URL and print
20
21
  const url = URL.createObjectURL(blob);
21
- await this.printFromUrl(url, name);
22
- URL.revokeObjectURL(url);
22
+ try {
23
+ await this.printFromUrl(url, name, mimeType);
24
+ }
25
+ finally {
26
+ URL.revokeObjectURL(url);
27
+ }
23
28
  }
24
29
  async printFile(options) {
25
- const { path, name } = options;
26
- // On web, we can only print URLs that are accessible
27
- // This will work for file:// URLs in some browsers or HTTP(S) URLs
28
- await this.printFromUrl(path, name);
30
+ const { path, name, mimeType } = options;
31
+ await this.printFromUrl(path, name, mimeType);
29
32
  }
30
33
  async printHtml(options) {
31
34
  const { html, name } = options;
32
- // Create a blob URL from the HTML content
33
35
  const blob = new Blob([html], { type: 'text/html' });
34
36
  const url = URL.createObjectURL(blob);
35
- await this.printFromUrl(url, name);
36
- URL.revokeObjectURL(url);
37
+ try {
38
+ await this.printFromUrl(url, name, 'text/html');
39
+ }
40
+ finally {
41
+ URL.revokeObjectURL(url);
42
+ }
37
43
  }
38
44
  async printPdf(options) {
39
45
  const { path, name } = options;
40
- // On web, print the PDF URL
41
- await this.printFromUrl(path, name);
46
+ await this.printFromUrl(path, name, 'application/pdf');
47
+ }
48
+ async printIframe(options) {
49
+ const { selector, name } = options;
50
+ const iframe = document.querySelector(selector);
51
+ if (!(iframe instanceof HTMLIFrameElement) || !iframe.contentWindow) {
52
+ throw new Error(`iframe not found: ${selector}`);
53
+ }
54
+ const originalTitle = document.title;
55
+ if (name) {
56
+ document.title = name;
57
+ }
58
+ iframe.contentWindow.focus();
59
+ iframe.contentWindow.print();
60
+ document.title = originalTitle;
42
61
  }
43
62
  async printWebView(options) {
44
- // Set document title for print job name
45
63
  const originalTitle = document.title;
46
64
  if (options === null || options === void 0 ? void 0 : options.name) {
47
65
  document.title = options.name;
48
66
  }
49
- // Trigger browser print dialog
50
67
  window.print();
51
- // Restore original title
52
68
  document.title = originalTitle;
53
69
  }
54
70
  async getPluginVersion() {
55
71
  return { version: '7.0.0' };
56
72
  }
57
- async printFromUrl(url, name) {
73
+ async printFromUrl(url, name, mimeType) {
58
74
  return new Promise((resolve, reject) => {
59
- // Create hidden iframe
60
75
  const iframe = document.createElement('iframe');
61
76
  iframe.style.position = 'fixed';
62
77
  iframe.style.right = '0';
@@ -64,46 +79,45 @@ var capacitorPrinter = (function (exports, core) {
64
79
  iframe.style.width = '0';
65
80
  iframe.style.height = '0';
66
81
  iframe.style.border = 'none';
67
- // Set up load handler
68
- iframe.onload = () => {
69
- try {
70
- // Set document title if name provided
71
- if (name && iframe.contentDocument) {
72
- iframe.contentDocument.title = name;
73
- }
74
- // Small delay to ensure content is loaded
75
- setTimeout(() => {
76
- try {
77
- // Try to access the iframe's window
78
- const iframeWindow = iframe.contentWindow;
79
- if (!iframeWindow) {
80
- throw new Error('Cannot access iframe window');
81
- }
82
- // Print the iframe content
83
- iframeWindow.focus();
84
- iframeWindow.print();
85
- // Clean up after a delay
86
- setTimeout(() => {
87
- document.body.removeChild(iframe);
88
- resolve();
89
- }, 100);
90
- }
91
- catch (error) {
92
- document.body.removeChild(iframe);
93
- reject(error);
94
- }
95
- }, 100);
82
+ let cleanedUp = false;
83
+ const cleanup = () => {
84
+ if (cleanedUp) {
85
+ return;
96
86
  }
97
- catch (error) {
87
+ cleanedUp = true;
88
+ if (iframe.parentNode) {
98
89
  document.body.removeChild(iframe);
99
- reject(error);
100
90
  }
91
+ resolve();
92
+ };
93
+ const printDelayMs = (mimeType === null || mimeType === void 0 ? void 0 : mimeType.toLowerCase()) === 'application/pdf' ? PDF_PRINT_DELAY_MS : HTML_PRINT_DELAY_MS;
94
+ iframe.onload = () => {
95
+ window.setTimeout(() => {
96
+ try {
97
+ const iframeWindow = iframe.contentWindow;
98
+ if (!iframeWindow) {
99
+ throw new Error('Cannot access iframe window');
100
+ }
101
+ if (name && iframe.contentDocument) {
102
+ iframe.contentDocument.title = name;
103
+ }
104
+ iframeWindow.addEventListener('afterprint', () => cleanup(), { once: true });
105
+ iframeWindow.focus();
106
+ iframeWindow.print();
107
+ window.setTimeout(() => cleanup(), CLEANUP_FALLBACK_MS);
108
+ }
109
+ catch (error) {
110
+ cleanup();
111
+ reject(error);
112
+ }
113
+ }, printDelayMs);
101
114
  };
102
115
  iframe.onerror = () => {
103
- document.body.removeChild(iframe);
116
+ if (iframe.parentNode) {
117
+ document.body.removeChild(iframe);
118
+ }
104
119
  reject(new Error('Failed to load content for printing'));
105
120
  };
106
- // Add iframe to document and set source
107
121
  document.body.appendChild(iframe);
108
122
  iframe.src = url;
109
123
  });
@@ -1 +1 @@
1
- {"version":3,"file":"plugin.js","sources":["esm/index.js","esm/web.js"],"sourcesContent":["import { registerPlugin } from '@capacitor/core';\nconst Printer = registerPlugin('Printer', {\n web: () => import('./web').then((m) => new m.PrinterWeb()),\n});\nexport * from './definitions';\nexport { Printer };\n//# sourceMappingURL=index.js.map","import { WebPlugin } from '@capacitor/core';\nexport class PrinterWeb extends WebPlugin {\n async printBase64(options) {\n const { data, mimeType, name } = options;\n // Convert base64 to blob\n const byteCharacters = atob(data);\n const byteNumbers = new Array(byteCharacters.length);\n for (let i = 0; i < byteCharacters.length; i++) {\n byteNumbers[i] = byteCharacters.charCodeAt(i);\n }\n const byteArray = new Uint8Array(byteNumbers);\n const blob = new Blob([byteArray], { type: mimeType });\n // Create object URL and print\n const url = URL.createObjectURL(blob);\n await this.printFromUrl(url, name);\n URL.revokeObjectURL(url);\n }\n async printFile(options) {\n const { path, name } = options;\n // On web, we can only print URLs that are accessible\n // This will work for file:// URLs in some browsers or HTTP(S) URLs\n await this.printFromUrl(path, name);\n }\n async printHtml(options) {\n const { html, name } = options;\n // Create a blob URL from the HTML content\n const blob = new Blob([html], { type: 'text/html' });\n const url = URL.createObjectURL(blob);\n await this.printFromUrl(url, name);\n URL.revokeObjectURL(url);\n }\n async printPdf(options) {\n const { path, name } = options;\n // On web, print the PDF URL\n await this.printFromUrl(path, name);\n }\n async printWebView(options) {\n // Set document title for print job name\n const originalTitle = document.title;\n if (options === null || options === void 0 ? void 0 : options.name) {\n document.title = options.name;\n }\n // Trigger browser print dialog\n window.print();\n // Restore original title\n document.title = originalTitle;\n }\n async getPluginVersion() {\n return { version: '7.0.0' };\n }\n async printFromUrl(url, name) {\n return new Promise((resolve, reject) => {\n // Create hidden iframe\n const iframe = document.createElement('iframe');\n iframe.style.position = 'fixed';\n iframe.style.right = '0';\n iframe.style.bottom = '0';\n iframe.style.width = '0';\n iframe.style.height = '0';\n iframe.style.border = 'none';\n // Set up load handler\n iframe.onload = () => {\n try {\n // Set document title if name provided\n if (name && iframe.contentDocument) {\n iframe.contentDocument.title = name;\n }\n // Small delay to ensure content is loaded\n setTimeout(() => {\n try {\n // Try to access the iframe's window\n const iframeWindow = iframe.contentWindow;\n if (!iframeWindow) {\n throw new Error('Cannot access iframe window');\n }\n // Print the iframe content\n iframeWindow.focus();\n iframeWindow.print();\n // Clean up after a delay\n setTimeout(() => {\n document.body.removeChild(iframe);\n resolve();\n }, 100);\n }\n catch (error) {\n document.body.removeChild(iframe);\n reject(error);\n }\n }, 100);\n }\n catch (error) {\n document.body.removeChild(iframe);\n reject(error);\n }\n };\n iframe.onerror = () => {\n document.body.removeChild(iframe);\n reject(new Error('Failed to load content for printing'));\n };\n // Add iframe to document and set source\n document.body.appendChild(iframe);\n iframe.src = url;\n });\n }\n}\n//# sourceMappingURL=web.js.map"],"names":["registerPlugin","WebPlugin"],"mappings":";;;AACK,UAAC,OAAO,GAAGA,mBAAc,CAAC,SAAS,EAAE;IAC1C,IAAI,GAAG,EAAE,MAAM,mDAAe,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,IAAI,CAAC,CAAC,UAAU,EAAE,CAAC;IAC9D,CAAC;;ICFM,MAAM,UAAU,SAASC,cAAS,CAAC;IAC1C,IAAI,MAAM,WAAW,CAAC,OAAO,EAAE;IAC/B,QAAQ,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAE,GAAG,OAAO;IAChD;IACA,QAAQ,MAAM,cAAc,GAAG,IAAI,CAAC,IAAI,CAAC;IACzC,QAAQ,MAAM,WAAW,GAAG,IAAI,KAAK,CAAC,cAAc,CAAC,MAAM,CAAC;IAC5D,QAAQ,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,cAAc,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;IACxD,YAAY,WAAW,CAAC,CAAC,CAAC,GAAG,cAAc,CAAC,UAAU,CAAC,CAAC,CAAC;IACzD,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,YAAY,GAAG,MAAM,CAAC,aAAa;IACrE,4BAA4B,IAAI,CAAC,YAAY,EAAE;IAC/C,gCAAgC,MAAM,IAAI,KAAK,CAAC,6BAA6B,CAAC;IAC9E,4BAA4B;IAC5B;IACA,4BAA4B,YAAY,CAAC,KAAK,EAAE;IAChD,4BAA4B,YAAY,CAAC,KAAK,EAAE;IAChD;IACA,4BAA4B,UAAU,CAAC,MAAM;IAC7C,gCAAgC,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC;IACjE,gCAAgC,OAAO,EAAE;IACzC,4BAA4B,CAAC,EAAE,GAAG,CAAC;IACnC,wBAAwB;IACxB,wBAAwB,OAAO,KAAK,EAAE;IACtC,4BAA4B,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC;IAC7D,4BAA4B,MAAM,CAAC,KAAK,CAAC;IACzC,wBAAwB;IACxB,oBAAoB,CAAC,EAAE,GAAG,CAAC;IAC3B,gBAAgB;IAChB,gBAAgB,OAAO,KAAK,EAAE;IAC9B,oBAAoB,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC;IACrD,oBAAoB,MAAM,CAAC,KAAK,CAAC;IACjC,gBAAgB;IAChB,YAAY,CAAC;IACb,YAAY,MAAM,CAAC,OAAO,GAAG,MAAM;IACnC,gBAAgB,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC;IACjD,gBAAgB,MAAM,CAAC,IAAI,KAAK,CAAC,qCAAqC,CAAC,CAAC;IACxE,YAAY,CAAC;IACb;IACA,YAAY,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC;IAC7C,YAAY,MAAM,CAAC,GAAG,GAAG,GAAG;IAC5B,QAAQ,CAAC,CAAC;IACV,IAAI;IACJ;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"plugin.js","sources":["esm/index.js","esm/web.js"],"sourcesContent":["import { registerPlugin } from '@capacitor/core';\nconst Printer = registerPlugin('Printer', {\n web: () => import('./web').then((m) => new m.PrinterWeb()),\n});\nexport * from './definitions';\nexport { Printer };\n//# sourceMappingURL=index.js.map","import { WebPlugin } from '@capacitor/core';\nconst PDF_PRINT_DELAY_MS = 500;\nconst HTML_PRINT_DELAY_MS = 100;\nconst CLEANUP_FALLBACK_MS = 60000;\nexport class PrinterWeb extends WebPlugin {\n async printBase64(options) {\n const { data, mimeType, name } = options;\n const byteCharacters = atob(data);\n const byteNumbers = new Array(byteCharacters.length);\n for (let i = 0; i < byteCharacters.length; i++) {\n byteNumbers[i] = byteCharacters.charCodeAt(i);\n }\n const byteArray = new Uint8Array(byteNumbers);\n const blob = new Blob([byteArray], { type: mimeType });\n const url = URL.createObjectURL(blob);\n try {\n await this.printFromUrl(url, name, mimeType);\n }\n finally {\n URL.revokeObjectURL(url);\n }\n }\n async printFile(options) {\n const { path, name, mimeType } = options;\n await this.printFromUrl(path, name, mimeType);\n }\n async printHtml(options) {\n const { html, name } = options;\n const blob = new Blob([html], { type: 'text/html' });\n const url = URL.createObjectURL(blob);\n try {\n await this.printFromUrl(url, name, 'text/html');\n }\n finally {\n URL.revokeObjectURL(url);\n }\n }\n async printPdf(options) {\n const { path, name } = options;\n await this.printFromUrl(path, name, 'application/pdf');\n }\n async printIframe(options) {\n const { selector, name } = options;\n const iframe = document.querySelector(selector);\n if (!(iframe instanceof HTMLIFrameElement) || !iframe.contentWindow) {\n throw new Error(`iframe not found: ${selector}`);\n }\n const originalTitle = document.title;\n if (name) {\n document.title = name;\n }\n iframe.contentWindow.focus();\n iframe.contentWindow.print();\n document.title = originalTitle;\n }\n async printWebView(options) {\n const originalTitle = document.title;\n if (options === null || options === void 0 ? void 0 : options.name) {\n document.title = options.name;\n }\n window.print();\n document.title = originalTitle;\n }\n async getPluginVersion() {\n return { version: '7.0.0' };\n }\n async printFromUrl(url, name, mimeType) {\n return new Promise((resolve, reject) => {\n const iframe = document.createElement('iframe');\n iframe.style.position = 'fixed';\n iframe.style.right = '0';\n iframe.style.bottom = '0';\n iframe.style.width = '0';\n iframe.style.height = '0';\n iframe.style.border = 'none';\n let cleanedUp = false;\n const cleanup = () => {\n if (cleanedUp) {\n return;\n }\n cleanedUp = true;\n if (iframe.parentNode) {\n document.body.removeChild(iframe);\n }\n resolve();\n };\n const printDelayMs = (mimeType === null || mimeType === void 0 ? void 0 : mimeType.toLowerCase()) === 'application/pdf' ? PDF_PRINT_DELAY_MS : HTML_PRINT_DELAY_MS;\n iframe.onload = () => {\n window.setTimeout(() => {\n try {\n const iframeWindow = iframe.contentWindow;\n if (!iframeWindow) {\n throw new Error('Cannot access iframe window');\n }\n if (name && iframe.contentDocument) {\n iframe.contentDocument.title = name;\n }\n iframeWindow.addEventListener('afterprint', () => cleanup(), { once: true });\n iframeWindow.focus();\n iframeWindow.print();\n window.setTimeout(() => cleanup(), CLEANUP_FALLBACK_MS);\n }\n catch (error) {\n cleanup();\n reject(error);\n }\n }, printDelayMs);\n };\n iframe.onerror = () => {\n if (iframe.parentNode) {\n document.body.removeChild(iframe);\n }\n reject(new Error('Failed to load content for printing'));\n };\n document.body.appendChild(iframe);\n iframe.src = url;\n });\n }\n}\n//# sourceMappingURL=web.js.map"],"names":["registerPlugin","WebPlugin"],"mappings":";;;AACK,UAAC,OAAO,GAAGA,mBAAc,CAAC,SAAS,EAAE;IAC1C,IAAI,GAAG,EAAE,MAAM,mDAAe,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,IAAI,CAAC,CAAC,UAAU,EAAE,CAAC;IAC9D,CAAC;;ICFD,MAAM,kBAAkB,GAAG,GAAG;IAC9B,MAAM,mBAAmB,GAAG,GAAG;IAC/B,MAAM,mBAAmB,GAAG,KAAK;IAC1B,MAAM,UAAU,SAASC,cAAS,CAAC;IAC1C,IAAI,MAAM,WAAW,CAAC,OAAO,EAAE;IAC/B,QAAQ,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAE,GAAG,OAAO;IAChD,QAAQ,MAAM,cAAc,GAAG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C7C,YAAY,MAAM,CAAC,GAAG,GAAG,GAAG;IAC5B,QAAQ,CAAC,CAAC;IACV,IAAI;IACJ;;;;;;;;;;;;;;;"}
@@ -142,6 +142,38 @@ import WebKit
142
142
  )
143
143
  }
144
144
 
145
+ /// Print iframe content from the current web view
146
+ public func printIframe(
147
+ webView: WKWebView,
148
+ selector: String,
149
+ name: String
150
+ ) throws {
151
+ let escapedSelector = selector
152
+ .replacingOccurrences(of: "\\", with: "\\\\")
153
+ .replacingOccurrences(of: "\"", with: "\\\"")
154
+ .replacingOccurrences(of: "\'", with: "\\\'")
155
+ let escapedName = name
156
+ .replacingOccurrences(of: "\\", with: "\\\\")
157
+ .replacingOccurrences(of: "\"", with: "\\\"")
158
+ .replacingOccurrences(of: "\'", with: "\\\'")
159
+
160
+ let script = """
161
+ (function() {
162
+ var frame = document.querySelector('\\(escapedSelector)');
163
+ if (!frame || !frame.contentWindow) {
164
+ throw new Error('iframe not found');
165
+ }
166
+ if ('\\(escapedName)') {
167
+ document.title = '\\(escapedName)';
168
+ }
169
+ frame.contentWindow.focus();
170
+ frame.contentWindow.print();
171
+ })();
172
+ """
173
+
174
+ webView.evaluateJavaScript(script, completionHandler: nil)
175
+ }
176
+
145
177
  /// Print web view content
146
178
  public func printWebView(
147
179
  webView: WKWebView,
@@ -3,7 +3,7 @@ import Capacitor
3
3
 
4
4
  @objc(PrinterPlugin)
5
5
  public class PrinterPlugin: CAPPlugin, CAPBridgedPlugin {
6
- private let pluginVersion: String = "8.0.17"
6
+ private let pluginVersion: String = "8.1.0"
7
7
  public let identifier = "PrinterPlugin"
8
8
  public let jsName = "Printer"
9
9
  public let pluginMethods: [CAPPluginMethod] = [
@@ -11,6 +11,7 @@ public class PrinterPlugin: CAPPlugin, CAPBridgedPlugin {
11
11
  CAPPluginMethod(name: "printFile", returnType: CAPPluginReturnPromise),
12
12
  CAPPluginMethod(name: "printHtml", returnType: CAPPluginReturnPromise),
13
13
  CAPPluginMethod(name: "printPdf", returnType: CAPPluginReturnPromise),
14
+ CAPPluginMethod(name: "printIframe", returnType: CAPPluginReturnPromise),
14
15
  CAPPluginMethod(name: "printWebView", returnType: CAPPluginReturnPromise),
15
16
  CAPPluginMethod(name: "getPluginVersion", returnType: CAPPluginReturnPromise)
16
17
  ]
@@ -119,6 +120,34 @@ public class PrinterPlugin: CAPPlugin, CAPBridgedPlugin {
119
120
  }
120
121
  }
121
122
 
123
+ @objc func printIframe(_ call: CAPPluginCall) {
124
+ guard let selector = call.getString("selector") else {
125
+ call.reject("selector is required")
126
+ return
127
+ }
128
+
129
+ let name = call.getString("name") ?? "Document"
130
+
131
+ DispatchQueue.main.async { [weak self] in
132
+ guard let self = self else { return }
133
+ guard let webView = self.bridge?.webView else {
134
+ call.reject("WebView not available")
135
+ return
136
+ }
137
+
138
+ do {
139
+ try self.implementation.printIframe(
140
+ webView: webView,
141
+ selector: selector,
142
+ name: name
143
+ )
144
+ call.resolve()
145
+ } catch {
146
+ call.reject("Failed to print iframe: \(error.localizedDescription)")
147
+ }
148
+ }
149
+ }
150
+
122
151
  @objc func printWebView(_ call: CAPPluginCall) {
123
152
  let name = call.getString("name") ?? "Document"
124
153
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capgo/capacitor-printer",
3
- "version": "8.0.17",
3
+ "version": "8.1.0",
4
4
  "description": "Capacitor plugin for printing documents, HTML, PDFs, images and web views",
5
5
  "main": "dist/plugin.cjs.js",
6
6
  "module": "dist/esm/index.js",
@@ -52,8 +52,7 @@
52
52
  "prepublishOnly": "bun run build",
53
53
  "check:wiring": "node scripts/check-capacitor-plugin-wiring.mjs",
54
54
  "example:install": "cd example-app && bun install --frozen-lockfile",
55
- "example:build": "bun run build && cd example-app && bun install --frozen-lockfile && bun run build",
56
- "example:capgo:deploy": "bun run example:build && bun scripts/deploy-example-capgo.mjs"
55
+ "example:build": "bun run build && cd example-app && bun install --frozen-lockfile && bun run build"
57
56
  },
58
57
  "devDependencies": {
59
58
  "@capacitor/android": "^8.0.0",