@embedpdf/plugin-print 1.0.20 → 1.0.21

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/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("@embedpdf/core"),r=require("@embedpdf/plugin-render"),t="print",n={id:t,name:"Print Plugin",version:"1.0.0",provides:["print"],requires:["render"],optional:[],defaultConfig:{enabled:!0}};var a=(e=>(e.Normal="normal",e.High="high",e))(a||{}),s=(e=>(e.Current="current",e.All="all",e.Custom="custom",e))(s||{});const i=class extends e.BasePlugin{constructor(e,t,n){var a;super(e,t),this.config=n,this.renderCapability=null==(a=this.registry.getPlugin(r.RenderPlugin.id))?void 0:a.provides()}async initialize(e){}buildCapability(){return{preparePrint:this.preparePrint.bind(this),parsePageRange:this.parsePageRange.bind(this)}}async preparePrint(e,r,t){var n;const a=this.coreState.core;if(!a.document)throw new Error("No document loaded");const s=this.getPagesToPrint(e,a.document.pages.length),i=s.length,o=(null==(n=this.config)?void 0:n.batchSize)||3;null==r||r({current:0,total:i,status:"preparing",message:`Preparing to render ${i} page${1!==i?"s":""}...`});const l=this.getScaleFactor(e.quality);for(let g=0;g<s.length;g+=o){const n=Math.min(g+o,s.length),a=s.slice(g,n).map((async(n,a)=>{null==r||r({current:g+a,total:i,status:"rendering",message:`Rendering page ${n+1}...`});const s=await this.renderPage(n,{scaleFactor:l,dpr:1,withAnnotations:e.includeAnnotations});null==t||t({pageIndex:n,blob:s})}));await Promise.all(a)}null==r||r({current:i,total:i,status:"complete",message:"All pages rendered successfully"})}async renderPage(e,r){return new Promise(((t,n)=>{this.renderCapability.renderPage({pageIndex:e,options:r}).wait((e=>t(e)),(r=>n(new Error(`Failed to render page ${e+1}: ${r.reason.message||"Unknown error"}`))))}))}getScaleFactor(e){switch(e){case a.High:return 1.5;case a.Normal:default:return 1}}getPagesToPrint(e,r){const{pageRange:t}=e;switch(t.type){case s.Current:return void 0!==t.currentPage?[t.currentPage]:[0];case s.All:return Array.from({length:r},((e,r)=>r));case s.Custom:return t.pages?t.pages.filter((e=>e>=0&&e<r)).sort(((e,r)=>e-r)):[0];default:return[0]}}parsePageRange(e){var r;try{const t=(null==(r=this.coreState.core.document)?void 0:r.pages.length)||0,n=[],a=e.split(",").map((e=>e.trim()));for(const e of a)if(e.includes("-")){const[r,a]=e.split("-").map((e=>parseInt(e.trim())));if(isNaN(r)||isNaN(a))return{pages:[],isValid:!1,error:`Invalid range: ${e}`};if(r>a)return{pages:[],isValid:!1,error:`Invalid range: ${e} (start > end)`};for(let e=r;e<=a;e++)e>=1&&e<=t&&n.push(e-1)}else{const r=parseInt(e);if(isNaN(r))return{pages:[],isValid:!1,error:`Invalid page number: ${e}`};r>=1&&r<=t&&n.push(r-1)}return{pages:[...new Set(n)].sort(((e,r)=>e-r)),isValid:!0}}catch(t){return{pages:[],isValid:!1,error:`Parsing error: ${t instanceof Error?t.message:"Unknown error"}`}}}};i.id="print";let o=i;const l={manifest:n,create:(e,r)=>new o(t,e,r),reducer:()=>{},initialState:{}};exports.PRINT_PLUGIN_ID=t,exports.PageRangeType=s,exports.PrintPlugin=o,exports.PrintPluginPackage=l,exports.PrintQuality=a,exports.manifest=n;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("@embedpdf/core"),t=require("@embedpdf/models"),r="print",n={id:r,name:"Print Plugin",version:"1.0.0",provides:["print"],requires:["render"],optional:[],defaultConfig:{enabled:!0}},i=class extends e.BasePlugin{constructor(t,r,n){super(t,r),this.printReady$=e.createEmitter()}async initialize(e){}buildCapability(){return{print:this.print.bind(this)}}onPrintRequest(e){return this.printReady$.on(e)}print(e){const r=new t.Task;r.progress({stage:"preparing",message:"Preparing document..."});return this.preparePrintDocument(e).wait((t=>{r.progress({stage:"document-ready",message:"Document prepared successfully"}),this.printReady$.emit({options:e,buffer:t,task:r})}),r.fail),r}preparePrintDocument(e){const r=this.coreState.core.document;return r?this.engine.preparePrintDocument(r,e):t.PdfTaskHelper.reject({code:t.PdfErrorCode.DocNotOpen,message:"Document not found"})}};i.id="print";let s=i;const o={manifest:n,create:(e,t)=>new s(r,e,t),reducer:()=>{},initialState:{}};exports.PRINT_PLUGIN_ID=r,exports.PrintPlugin=s,exports.PrintPluginPackage=o,exports.manifest=n;
2
2
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","sources":["../src/lib/manifest.ts","../src/lib/types.ts","../src/lib/print-plugin.ts","../src/lib/index.ts"],"sourcesContent":["import { PluginManifest } from '@embedpdf/core';\nimport { PrintPluginConfig } from './types';\n\nexport const PRINT_PLUGIN_ID = 'print';\n\nexport const manifest: PluginManifest<PrintPluginConfig> = {\n id: PRINT_PLUGIN_ID,\n name: 'Print Plugin',\n version: '1.0.0',\n provides: ['print'],\n requires: ['render'],\n optional: [],\n defaultConfig: {\n enabled: true,\n },\n};\n","import { BasePluginConfig } from '@embedpdf/core';\n\nexport interface PrintPluginConfig extends BasePluginConfig {\n defaultQuality?: PrintQuality;\n defaultIncludeAnnotations?: boolean;\n batchSize?: number;\n}\n\nexport enum PrintQuality {\n Normal = 'normal',\n High = 'high',\n}\n\nexport enum PageRangeType {\n Current = 'current',\n All = 'all',\n Custom = 'custom',\n}\n\nexport interface PageRangeCurrent {\n type: PageRangeType.Current;\n currentPage: number;\n}\n\nexport interface PageRangeAll {\n type: PageRangeType.All;\n}\n\nexport interface PageRangeCustom {\n type: PageRangeType.Custom;\n pages: number[];\n}\n\nexport type PageRange = PageRangeCurrent | PageRangeAll | PageRangeCustom;\n\nexport interface PrintOptions {\n pageRange: PageRange;\n includeAnnotations: boolean;\n quality: PrintQuality;\n}\n\nexport interface PrintProgress {\n current: number;\n total: number;\n status: 'preparing' | 'rendering' | 'complete' | 'error';\n message?: string;\n}\n\nexport interface PrintData {\n blobs: Blob[];\n options: PrintOptions;\n totalPages: number;\n}\n\nexport interface ParsedPageRange {\n pages: number[];\n isValid: boolean;\n error?: string;\n}\n\nexport interface PrintPageResult {\n pageIndex: number;\n blob: Blob;\n}\n\nexport interface PrintCapability {\n preparePrint: (\n options: PrintOptions,\n onProgress?: (progress: PrintProgress) => void,\n onPageReady?: (result: PrintPageResult) => void,\n ) => Promise<void>;\n parsePageRange: (rangeString: string) => ParsedPageRange;\n}\n","import { BasePlugin, PluginRegistry } from '@embedpdf/core';\nimport { RenderCapability, RenderPlugin } from '@embedpdf/plugin-render';\n\nimport {\n PageRangeType,\n ParsedPageRange,\n PrintOptions,\n PrintPageResult,\n PrintPluginConfig,\n PrintProgress,\n PrintQuality,\n} from './types';\nimport { PrintCapability } from './types';\nimport { PdfRenderPageOptions, Rotation } from '@embedpdf/models';\n\nexport class PrintPlugin extends BasePlugin<PrintPluginConfig, PrintCapability> {\n static readonly id = 'print' as const;\n\n private readonly renderCapability: RenderCapability;\n private readonly config: PrintPluginConfig;\n\n constructor(id: string, registry: PluginRegistry, config: PrintPluginConfig) {\n super(id, registry);\n\n this.config = config;\n this.renderCapability = this.registry.getPlugin<RenderPlugin>(RenderPlugin.id)?.provides()!;\n }\n\n async initialize(_config: PrintPluginConfig): Promise<void> {}\n\n protected buildCapability(): PrintCapability {\n return {\n preparePrint: this.preparePrint.bind(this),\n parsePageRange: this.parsePageRange.bind(this),\n };\n }\n\n private async preparePrint(\n options: PrintOptions,\n onProgress?: (progress: PrintProgress) => void,\n onPageReady?: (result: PrintPageResult) => void,\n ): Promise<void> {\n const coreState = this.coreState.core;\n\n if (!coreState.document) {\n throw new Error('No document loaded');\n }\n\n const pagesToPrint = this.getPagesToPrint(options, coreState.document.pages.length);\n const totalPages = pagesToPrint.length;\n const batchSize = this.config?.batchSize || 3; // Render 3 pages concurrently by default\n\n onProgress?.({\n current: 0,\n total: totalPages,\n status: 'preparing',\n message: `Preparing to render ${totalPages} page${totalPages !== 1 ? 's' : ''}...`,\n });\n\n const scaleFactor = this.getScaleFactor(options.quality);\n const dpr = 1;\n\n // Process pages in batches to avoid memory issues\n for (let batchStart = 0; batchStart < pagesToPrint.length; batchStart += batchSize) {\n const batchEnd = Math.min(batchStart + batchSize, pagesToPrint.length);\n const batch = pagesToPrint.slice(batchStart, batchEnd);\n\n // Render batch concurrently\n const batchPromises = batch.map(async (pageIndex, batchIndex) => {\n const overallIndex = batchStart + batchIndex;\n\n onProgress?.({\n current: overallIndex,\n total: totalPages,\n status: 'rendering',\n message: `Rendering page ${pageIndex + 1}...`,\n });\n\n const blob = await this.renderPage(pageIndex, {\n scaleFactor,\n dpr,\n withAnnotations: options.includeAnnotations,\n });\n\n // Send page ready immediately after rendering\n onPageReady?.({\n pageIndex,\n blob,\n });\n\n return;\n });\n\n // Wait for batch to complete\n await Promise.all(batchPromises);\n }\n\n onProgress?.({\n current: totalPages,\n total: totalPages,\n status: 'complete',\n message: 'All pages rendered successfully',\n });\n }\n\n private async renderPage(pageIndex: number, options: PdfRenderPageOptions): Promise<Blob> {\n return new Promise((resolve, reject) => {\n const renderTask = this.renderCapability.renderPage({\n pageIndex,\n options,\n });\n\n renderTask.wait(\n (blob) => resolve(blob),\n (error) =>\n reject(\n new Error(\n `Failed to render page ${pageIndex + 1}: ${error.reason.message || 'Unknown error'}`,\n ),\n ),\n );\n });\n }\n\n private getScaleFactor(quality: PrintQuality): number {\n switch (quality) {\n case PrintQuality.High:\n return 1.5; // Higher resolution for better print quality\n case PrintQuality.Normal:\n default:\n return 1; // Standard print resolution\n }\n }\n\n private getPagesToPrint(options: PrintOptions, totalPages: number): number[] {\n const { pageRange } = options;\n\n switch (pageRange.type) {\n case PageRangeType.Current:\n return pageRange.currentPage !== undefined ? [pageRange.currentPage] : [0];\n\n case PageRangeType.All:\n return Array.from({ length: totalPages }, (_, i) => i);\n\n case PageRangeType.Custom:\n if (!pageRange.pages) return [0];\n return pageRange.pages\n .filter((page) => page >= 0 && page < totalPages)\n .sort((a, b) => a - b);\n\n default:\n return [0];\n }\n }\n\n private parsePageRange(rangeString: string): ParsedPageRange {\n try {\n const totalPages = this.coreState.core.document?.pages.length || 0;\n const pages: number[] = [];\n const parts = rangeString.split(',').map((s) => s.trim());\n\n for (const part of parts) {\n if (part.includes('-')) {\n // Handle range like \"5-10\"\n const [start, end] = part.split('-').map((s) => parseInt(s.trim()));\n\n if (isNaN(start) || isNaN(end)) {\n return { pages: [], isValid: false, error: `Invalid range: ${part}` };\n }\n\n if (start > end) {\n return { pages: [], isValid: false, error: `Invalid range: ${part} (start > end)` };\n }\n\n for (let i = start; i <= end; i++) {\n if (i >= 1 && i <= totalPages) {\n pages.push(i - 1); // Convert to 0-based index\n }\n }\n } else {\n // Handle single page\n const pageNum = parseInt(part);\n\n if (isNaN(pageNum)) {\n return { pages: [], isValid: false, error: `Invalid page number: ${part}` };\n }\n\n if (pageNum >= 1 && pageNum <= totalPages) {\n pages.push(pageNum - 1); // Convert to 0-based index\n }\n }\n }\n\n // Remove duplicates and sort\n const uniquePages = [...new Set(pages)].sort((a, b) => a - b);\n\n return {\n pages: uniquePages,\n isValid: true,\n };\n } catch (error) {\n return {\n pages: [],\n isValid: false,\n error: `Parsing error: ${error instanceof Error ? error.message : 'Unknown error'}`,\n };\n }\n }\n}\n","import { PluginPackage } from '@embedpdf/core';\nimport { manifest, PRINT_PLUGIN_ID } from './manifest';\nimport { PrintPluginConfig } from './types';\nimport { PrintPlugin } from './print-plugin';\n\nexport const PrintPluginPackage: PluginPackage<PrintPlugin, PrintPluginConfig> = {\n manifest,\n create: (registry, config) => new PrintPlugin(PRINT_PLUGIN_ID, registry, config),\n reducer: () => {},\n initialState: {},\n};\n\nexport * from './print-plugin';\nexport * from './types';\nexport * from './manifest';\n"],"names":["PRINT_PLUGIN_ID","manifest","id","name","version","provides","requires","optional","defaultConfig","enabled","PrintQuality","PageRangeType","_PrintPlugin","BasePlugin","constructor","registry","config","super","this","renderCapability","_a","getPlugin","RenderPlugin","initialize","_config","buildCapability","preparePrint","bind","parsePageRange","options","onProgress","onPageReady","coreState","core","document","Error","pagesToPrint","getPagesToPrint","pages","length","totalPages","batchSize","current","total","status","message","scaleFactor","getScaleFactor","quality","batchStart","batchEnd","Math","min","batchPromises","slice","map","async","pageIndex","batchIndex","blob","renderPage","dpr","withAnnotations","includeAnnotations","Promise","all","resolve","reject","wait","error","reason","High","Normal","pageRange","type","Current","currentPage","All","Array","from","_","i","Custom","filter","page","sort","a","b","rangeString","parts","split","s","trim","part","includes","start","end","parseInt","isNaN","isValid","push","pageNum","Set","PrintPlugin","PrintPluginPackage","create","reducer","initialState"],"mappings":"uJAGaA,EAAkB,QAElBC,EAA8C,CACzDC,GAAIF,EACJG,KAAM,eACNC,QAAS,QACTC,SAAU,CAAC,SACXC,SAAU,CAAC,UACXC,SAAU,GACVC,cAAe,CACbC,SAAS,ICLD,IAAAC,GAAAA,IACVA,EAAS,OAAA,SACTA,EAAO,KAAA,OAFGA,IAAAA,GAAA,CAAA,GAKAC,GAAAA,IACVA,EAAU,QAAA,UACVA,EAAM,IAAA,MACNA,EAAS,OAAA,SAHCA,IAAAA,GAAA,CAAA,GCEL,MAAMC,EAAN,cAA0BC,EAAAA,WAM/B,WAAAC,CAAYZ,EAAYa,EAA0BC,SAChDC,MAAMf,EAAIa,GAEVG,KAAKF,OAASA,EACTE,KAAAC,iBAAmB,OAAAC,OAAKL,SAASM,UAAwBC,eAAapB,UAAK,EAAAkB,EAAAf,UAAS,CAG3F,gBAAMkB,CAAWC,GAA2C,CAElD,eAAAC,GACD,MAAA,CACLC,aAAcR,KAAKQ,aAAaC,KAAKT,MACrCU,eAAgBV,KAAKU,eAAeD,KAAKT,MAC3C,CAGF,kBAAcQ,CACZG,EACAC,EACAC,SAEM,MAAAC,EAAYd,KAAKc,UAAUC,KAE7B,IAACD,EAAUE,SACP,MAAA,IAAIC,MAAM,sBAGlB,MAAMC,EAAelB,KAAKmB,gBAAgBR,EAASG,EAAUE,SAASI,MAAMC,QACtEC,EAAaJ,EAAaG,OAC1BE,GAAY,OAAArB,EAAAF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,SAAS,SAEJ9B,GACA,MAAA,CACL/B,MAAO,GACP6D,SAAS,EACT9B,MAAO,kBAAkBA,aAAiBlC,MAAQkC,EAAMxB,QAAU,kBACpE,CACF,GA9LFjC,EAAgBV,GAAK,QADhB,IAAMqG,EAAN3F,ECVA,MAAM4F,EAAoE,CAC/EvG,WACAwG,OAAQ,CAAC1F,EAAUC,IAAW,IAAIuF,EAAYvG,EAAiBe,EAAUC,GACzE0F,QAAS,OACTC,aAAc,CAAA"}
1
+ {"version":3,"file":"index.cjs","sources":["../src/lib/manifest.ts","../src/lib/print-plugin.ts","../src/lib/index.ts"],"sourcesContent":["import { PluginManifest } from '@embedpdf/core';\nimport { PrintPluginConfig } from './types';\n\nexport const PRINT_PLUGIN_ID = 'print';\n\nexport const manifest: PluginManifest<PrintPluginConfig> = {\n id: PRINT_PLUGIN_ID,\n name: 'Print Plugin',\n version: '1.0.0',\n provides: ['print'],\n requires: ['render'],\n optional: [],\n defaultConfig: {\n enabled: true,\n },\n};\n","import { BasePlugin, createEmitter, Listener, PluginRegistry, Unsubscribe } from '@embedpdf/core';\nimport {\n PdfErrorCode,\n PdfErrorReason,\n PdfPrintOptions,\n PdfTaskHelper,\n Task,\n} from '@embedpdf/models';\n\nimport { PrintCapability, PrintPluginConfig, PrintProgress, PrintReadyEvent } from './types';\n\nexport class PrintPlugin extends BasePlugin<PrintPluginConfig, PrintCapability> {\n static readonly id = 'print' as const;\n\n private readonly printReady$ = createEmitter<PrintReadyEvent>();\n\n constructor(id: string, registry: PluginRegistry, _config: PrintPluginConfig) {\n super(id, registry);\n }\n\n async initialize(_: PrintPluginConfig): Promise<void> {}\n\n protected buildCapability(): PrintCapability {\n return {\n print: this.print.bind(this),\n };\n }\n\n public onPrintRequest(listener: Listener<PrintReadyEvent>): Unsubscribe {\n return this.printReady$.on(listener);\n }\n\n private print(options: PdfPrintOptions): Task<ArrayBuffer, PdfErrorReason, PrintProgress> {\n const task = new Task<ArrayBuffer, PdfErrorReason, PrintProgress>();\n task.progress({ stage: 'preparing', message: 'Preparing document...' });\n\n const prepare = this.preparePrintDocument(options);\n prepare.wait((buffer) => {\n task.progress({ stage: 'document-ready', message: 'Document prepared successfully' });\n // Emit buffer + task for the framework layer to display & trigger print\n this.printReady$.emit({ options, buffer, task });\n }, task.fail);\n\n return task;\n }\n\n public preparePrintDocument(options: PdfPrintOptions): Task<ArrayBuffer, PdfErrorReason> {\n const document = this.coreState.core.document;\n\n if (!document) {\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: 'Document not found',\n });\n }\n\n return this.engine.preparePrintDocument(document, options);\n }\n}\n","import { PluginPackage } from '@embedpdf/core';\nimport { manifest, PRINT_PLUGIN_ID } from './manifest';\nimport { PrintPluginConfig } from './types';\nimport { PrintPlugin } from './print-plugin';\n\nexport const PrintPluginPackage: PluginPackage<PrintPlugin, PrintPluginConfig> = {\n manifest,\n create: (registry, config) => new PrintPlugin(PRINT_PLUGIN_ID, registry, config),\n reducer: () => {},\n initialState: {},\n};\n\nexport * from './print-plugin';\nexport * from './types';\nexport * from './manifest';\n"],"names":["PRINT_PLUGIN_ID","manifest","id","name","version","provides","requires","optional","defaultConfig","enabled","_PrintPlugin","BasePlugin","constructor","registry","_config","super","this","printReady$","createEmitter","initialize","_","buildCapability","print","bind","onPrintRequest","listener","on","options","task","Task","progress","stage","message","preparePrintDocument","wait","buffer","emit","fail","document","coreState","core","engine","PdfTaskHelper","reject","code","PdfErrorCode","DocNotOpen","PrintPlugin","PrintPluginPackage","create","config","reducer","initialState"],"mappings":"gJAGaA,EAAkB,QAElBC,EAA8C,CACzDC,GAAIF,EACJG,KAAM,eACNC,QAAS,QACTC,SAAU,CAAC,SACXC,SAAU,CAAC,UACXC,SAAU,GACVC,cAAe,CACbC,SAAS,ICFAC,EAAN,cAA0BC,EAAAA,WAK/B,WAAAC,CAAYV,EAAYW,EAA0BC,GAChDC,MAAMb,EAAIW,GAHKG,KAAAC,YAAcC,iBAA+B,CAM9D,gBAAMC,CAAWC,GAAqC,CAE5C,eAAAC,GACD,MAAA,CACLC,MAAON,KAAKM,MAAMC,KAAKP,MACzB,CAGK,cAAAQ,CAAeC,GACb,OAAAT,KAAKC,YAAYS,GAAGD,EAAQ,CAG7B,KAAAH,CAAMK,GACN,MAAAC,EAAO,IAAIC,OACjBD,EAAKE,SAAS,CAAEC,MAAO,YAAaC,QAAS,0BAStC,OAPShB,KAAKiB,qBAAqBN,GAClCO,MAAMC,IACZP,EAAKE,SAAS,CAAEC,MAAO,iBAAkBC,QAAS,mCAElDhB,KAAKC,YAAYmB,KAAK,CAAET,UAASQ,SAAQP,QAAM,GAC9CA,EAAKS,MAEDT,CAAA,CAGF,oBAAAK,CAAqBN,GACpB,MAAAW,EAAWtB,KAAKuB,UAAUC,KAAKF,SAErC,OAAKA,EAOEtB,KAAKyB,OAAOR,qBAAqBK,EAAUX,GANzCe,EAAAA,cAAcC,OAAO,CAC1BC,KAAMC,EAAaA,aAAAC,WACnBd,QAAS,sBAI4C,GA5C3DtB,EAAgBR,GAAK,QADhB,IAAM6C,EAANrC,ECNA,MAAMsC,EAAoE,CAC/E/C,WACAgD,OAAQ,CAACpC,EAAUqC,IAAW,IAAIH,EAAY/C,EAAiBa,EAAUqC,GACzEC,QAAS,OACTC,aAAc,CAAA"}
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- import { BasePlugin } from "@embedpdf/core";
2
- import { RenderPlugin } from "@embedpdf/plugin-render";
1
+ import { BasePlugin, createEmitter } from "@embedpdf/core";
2
+ import { Task, PdfTaskHelper, PdfErrorCode } from "@embedpdf/models";
3
3
  const PRINT_PLUGIN_ID = "print";
4
4
  const manifest = {
5
5
  id: PRINT_PLUGIN_ID,
@@ -12,162 +12,40 @@ const manifest = {
12
12
  enabled: true
13
13
  }
14
14
  };
15
- var PrintQuality = /* @__PURE__ */ ((PrintQuality2) => {
16
- PrintQuality2["Normal"] = "normal";
17
- PrintQuality2["High"] = "high";
18
- return PrintQuality2;
19
- })(PrintQuality || {});
20
- var PageRangeType = /* @__PURE__ */ ((PageRangeType2) => {
21
- PageRangeType2["Current"] = "current";
22
- PageRangeType2["All"] = "all";
23
- PageRangeType2["Custom"] = "custom";
24
- return PageRangeType2;
25
- })(PageRangeType || {});
26
15
  const _PrintPlugin = class _PrintPlugin extends BasePlugin {
27
- constructor(id, registry, config) {
28
- var _a;
16
+ constructor(id, registry, _config) {
29
17
  super(id, registry);
30
- this.config = config;
31
- this.renderCapability = (_a = this.registry.getPlugin(RenderPlugin.id)) == null ? void 0 : _a.provides();
18
+ this.printReady$ = createEmitter();
32
19
  }
33
- async initialize(_config) {
20
+ async initialize(_) {
34
21
  }
35
22
  buildCapability() {
36
23
  return {
37
- preparePrint: this.preparePrint.bind(this),
38
- parsePageRange: this.parsePageRange.bind(this)
24
+ print: this.print.bind(this)
39
25
  };
40
26
  }
41
- async preparePrint(options, onProgress, onPageReady) {
42
- var _a;
43
- const coreState = this.coreState.core;
44
- if (!coreState.document) {
45
- throw new Error("No document loaded");
46
- }
47
- const pagesToPrint = this.getPagesToPrint(options, coreState.document.pages.length);
48
- const totalPages = pagesToPrint.length;
49
- const batchSize = ((_a = this.config) == null ? void 0 : _a.batchSize) || 3;
50
- onProgress == null ? void 0 : onProgress({
51
- current: 0,
52
- total: totalPages,
53
- status: "preparing",
54
- message: `Preparing to render ${totalPages} page${totalPages !== 1 ? "s" : ""}...`
55
- });
56
- const scaleFactor = this.getScaleFactor(options.quality);
57
- const dpr = 1;
58
- for (let batchStart = 0; batchStart < pagesToPrint.length; batchStart += batchSize) {
59
- const batchEnd = Math.min(batchStart + batchSize, pagesToPrint.length);
60
- const batch = pagesToPrint.slice(batchStart, batchEnd);
61
- const batchPromises = batch.map(async (pageIndex, batchIndex) => {
62
- const overallIndex = batchStart + batchIndex;
63
- onProgress == null ? void 0 : onProgress({
64
- current: overallIndex,
65
- total: totalPages,
66
- status: "rendering",
67
- message: `Rendering page ${pageIndex + 1}...`
68
- });
69
- const blob = await this.renderPage(pageIndex, {
70
- scaleFactor,
71
- dpr,
72
- withAnnotations: options.includeAnnotations
73
- });
74
- onPageReady == null ? void 0 : onPageReady({
75
- pageIndex,
76
- blob
77
- });
78
- return;
79
- });
80
- await Promise.all(batchPromises);
81
- }
82
- onProgress == null ? void 0 : onProgress({
83
- current: totalPages,
84
- total: totalPages,
85
- status: "complete",
86
- message: "All pages rendered successfully"
87
- });
27
+ onPrintRequest(listener) {
28
+ return this.printReady$.on(listener);
88
29
  }
89
- async renderPage(pageIndex, options) {
90
- return new Promise((resolve, reject) => {
91
- const renderTask = this.renderCapability.renderPage({
92
- pageIndex,
93
- options
94
- });
95
- renderTask.wait(
96
- (blob) => resolve(blob),
97
- (error) => reject(
98
- new Error(
99
- `Failed to render page ${pageIndex + 1}: ${error.reason.message || "Unknown error"}`
100
- )
101
- )
102
- );
103
- });
30
+ print(options) {
31
+ const task = new Task();
32
+ task.progress({ stage: "preparing", message: "Preparing document..." });
33
+ const prepare = this.preparePrintDocument(options);
34
+ prepare.wait((buffer) => {
35
+ task.progress({ stage: "document-ready", message: "Document prepared successfully" });
36
+ this.printReady$.emit({ options, buffer, task });
37
+ }, task.fail);
38
+ return task;
104
39
  }
105
- getScaleFactor(quality) {
106
- switch (quality) {
107
- case PrintQuality.High:
108
- return 1.5;
109
- // Higher resolution for better print quality
110
- case PrintQuality.Normal:
111
- default:
112
- return 1;
113
- }
114
- }
115
- getPagesToPrint(options, totalPages) {
116
- const { pageRange } = options;
117
- switch (pageRange.type) {
118
- case PageRangeType.Current:
119
- return pageRange.currentPage !== void 0 ? [pageRange.currentPage] : [0];
120
- case PageRangeType.All:
121
- return Array.from({ length: totalPages }, (_, i) => i);
122
- case PageRangeType.Custom:
123
- if (!pageRange.pages) return [0];
124
- return pageRange.pages.filter((page) => page >= 0 && page < totalPages).sort((a, b) => a - b);
125
- default:
126
- return [0];
127
- }
128
- }
129
- parsePageRange(rangeString) {
130
- var _a;
131
- try {
132
- const totalPages = ((_a = this.coreState.core.document) == null ? void 0 : _a.pages.length) || 0;
133
- const pages = [];
134
- const parts = rangeString.split(",").map((s) => s.trim());
135
- for (const part of parts) {
136
- if (part.includes("-")) {
137
- const [start, end] = part.split("-").map((s) => parseInt(s.trim()));
138
- if (isNaN(start) || isNaN(end)) {
139
- return { pages: [], isValid: false, error: `Invalid range: ${part}` };
140
- }
141
- if (start > end) {
142
- return { pages: [], isValid: false, error: `Invalid range: ${part} (start > end)` };
143
- }
144
- for (let i = start; i <= end; i++) {
145
- if (i >= 1 && i <= totalPages) {
146
- pages.push(i - 1);
147
- }
148
- }
149
- } else {
150
- const pageNum = parseInt(part);
151
- if (isNaN(pageNum)) {
152
- return { pages: [], isValid: false, error: `Invalid page number: ${part}` };
153
- }
154
- if (pageNum >= 1 && pageNum <= totalPages) {
155
- pages.push(pageNum - 1);
156
- }
157
- }
158
- }
159
- const uniquePages = [...new Set(pages)].sort((a, b) => a - b);
160
- return {
161
- pages: uniquePages,
162
- isValid: true
163
- };
164
- } catch (error) {
165
- return {
166
- pages: [],
167
- isValid: false,
168
- error: `Parsing error: ${error instanceof Error ? error.message : "Unknown error"}`
169
- };
40
+ preparePrintDocument(options) {
41
+ const document = this.coreState.core.document;
42
+ if (!document) {
43
+ return PdfTaskHelper.reject({
44
+ code: PdfErrorCode.DocNotOpen,
45
+ message: "Document not found"
46
+ });
170
47
  }
48
+ return this.engine.preparePrintDocument(document, options);
171
49
  }
172
50
  };
173
51
  _PrintPlugin.id = "print";
@@ -181,10 +59,8 @@ const PrintPluginPackage = {
181
59
  };
182
60
  export {
183
61
  PRINT_PLUGIN_ID,
184
- PageRangeType,
185
62
  PrintPlugin,
186
63
  PrintPluginPackage,
187
- PrintQuality,
188
64
  manifest
189
65
  };
190
66
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../src/lib/manifest.ts","../src/lib/types.ts","../src/lib/print-plugin.ts","../src/lib/index.ts"],"sourcesContent":["import { PluginManifest } from '@embedpdf/core';\nimport { PrintPluginConfig } from './types';\n\nexport const PRINT_PLUGIN_ID = 'print';\n\nexport const manifest: PluginManifest<PrintPluginConfig> = {\n id: PRINT_PLUGIN_ID,\n name: 'Print Plugin',\n version: '1.0.0',\n provides: ['print'],\n requires: ['render'],\n optional: [],\n defaultConfig: {\n enabled: true,\n },\n};\n","import { BasePluginConfig } from '@embedpdf/core';\n\nexport interface PrintPluginConfig extends BasePluginConfig {\n defaultQuality?: PrintQuality;\n defaultIncludeAnnotations?: boolean;\n batchSize?: number;\n}\n\nexport enum PrintQuality {\n Normal = 'normal',\n High = 'high',\n}\n\nexport enum PageRangeType {\n Current = 'current',\n All = 'all',\n Custom = 'custom',\n}\n\nexport interface PageRangeCurrent {\n type: PageRangeType.Current;\n currentPage: number;\n}\n\nexport interface PageRangeAll {\n type: PageRangeType.All;\n}\n\nexport interface PageRangeCustom {\n type: PageRangeType.Custom;\n pages: number[];\n}\n\nexport type PageRange = PageRangeCurrent | PageRangeAll | PageRangeCustom;\n\nexport interface PrintOptions {\n pageRange: PageRange;\n includeAnnotations: boolean;\n quality: PrintQuality;\n}\n\nexport interface PrintProgress {\n current: number;\n total: number;\n status: 'preparing' | 'rendering' | 'complete' | 'error';\n message?: string;\n}\n\nexport interface PrintData {\n blobs: Blob[];\n options: PrintOptions;\n totalPages: number;\n}\n\nexport interface ParsedPageRange {\n pages: number[];\n isValid: boolean;\n error?: string;\n}\n\nexport interface PrintPageResult {\n pageIndex: number;\n blob: Blob;\n}\n\nexport interface PrintCapability {\n preparePrint: (\n options: PrintOptions,\n onProgress?: (progress: PrintProgress) => void,\n onPageReady?: (result: PrintPageResult) => void,\n ) => Promise<void>;\n parsePageRange: (rangeString: string) => ParsedPageRange;\n}\n","import { BasePlugin, PluginRegistry } from '@embedpdf/core';\nimport { RenderCapability, RenderPlugin } from '@embedpdf/plugin-render';\n\nimport {\n PageRangeType,\n ParsedPageRange,\n PrintOptions,\n PrintPageResult,\n PrintPluginConfig,\n PrintProgress,\n PrintQuality,\n} from './types';\nimport { PrintCapability } from './types';\nimport { PdfRenderPageOptions, Rotation } from '@embedpdf/models';\n\nexport class PrintPlugin extends BasePlugin<PrintPluginConfig, PrintCapability> {\n static readonly id = 'print' as const;\n\n private readonly renderCapability: RenderCapability;\n private readonly config: PrintPluginConfig;\n\n constructor(id: string, registry: PluginRegistry, config: PrintPluginConfig) {\n super(id, registry);\n\n this.config = config;\n this.renderCapability = this.registry.getPlugin<RenderPlugin>(RenderPlugin.id)?.provides()!;\n }\n\n async initialize(_config: PrintPluginConfig): Promise<void> {}\n\n protected buildCapability(): PrintCapability {\n return {\n preparePrint: this.preparePrint.bind(this),\n parsePageRange: this.parsePageRange.bind(this),\n };\n }\n\n private async preparePrint(\n options: PrintOptions,\n onProgress?: (progress: PrintProgress) => void,\n onPageReady?: (result: PrintPageResult) => void,\n ): Promise<void> {\n const coreState = this.coreState.core;\n\n if (!coreState.document) {\n throw new Error('No document loaded');\n }\n\n const pagesToPrint = this.getPagesToPrint(options, coreState.document.pages.length);\n const totalPages = pagesToPrint.length;\n const batchSize = this.config?.batchSize || 3; // Render 3 pages concurrently by default\n\n onProgress?.({\n current: 0,\n total: totalPages,\n status: 'preparing',\n message: `Preparing to render ${totalPages} page${totalPages !== 1 ? 's' : ''}...`,\n });\n\n const scaleFactor = this.getScaleFactor(options.quality);\n const dpr = 1;\n\n // Process pages in batches to avoid memory issues\n for (let batchStart = 0; batchStart < pagesToPrint.length; batchStart += batchSize) {\n const batchEnd = Math.min(batchStart + batchSize, pagesToPrint.length);\n const batch = pagesToPrint.slice(batchStart, batchEnd);\n\n // Render batch concurrently\n const batchPromises = batch.map(async (pageIndex, batchIndex) => {\n const overallIndex = batchStart + batchIndex;\n\n onProgress?.({\n current: overallIndex,\n total: totalPages,\n status: 'rendering',\n message: `Rendering page ${pageIndex + 1}...`,\n });\n\n const blob = await this.renderPage(pageIndex, {\n scaleFactor,\n dpr,\n withAnnotations: options.includeAnnotations,\n });\n\n // Send page ready immediately after rendering\n onPageReady?.({\n pageIndex,\n blob,\n });\n\n return;\n });\n\n // Wait for batch to complete\n await Promise.all(batchPromises);\n }\n\n onProgress?.({\n current: totalPages,\n total: totalPages,\n status: 'complete',\n message: 'All pages rendered successfully',\n });\n }\n\n private async renderPage(pageIndex: number, options: PdfRenderPageOptions): Promise<Blob> {\n return new Promise((resolve, reject) => {\n const renderTask = this.renderCapability.renderPage({\n pageIndex,\n options,\n });\n\n renderTask.wait(\n (blob) => resolve(blob),\n (error) =>\n reject(\n new Error(\n `Failed to render page ${pageIndex + 1}: ${error.reason.message || 'Unknown error'}`,\n ),\n ),\n );\n });\n }\n\n private getScaleFactor(quality: PrintQuality): number {\n switch (quality) {\n case PrintQuality.High:\n return 1.5; // Higher resolution for better print quality\n case PrintQuality.Normal:\n default:\n return 1; // Standard print resolution\n }\n }\n\n private getPagesToPrint(options: PrintOptions, totalPages: number): number[] {\n const { pageRange } = options;\n\n switch (pageRange.type) {\n case PageRangeType.Current:\n return pageRange.currentPage !== undefined ? [pageRange.currentPage] : [0];\n\n case PageRangeType.All:\n return Array.from({ length: totalPages }, (_, i) => i);\n\n case PageRangeType.Custom:\n if (!pageRange.pages) return [0];\n return pageRange.pages\n .filter((page) => page >= 0 && page < totalPages)\n .sort((a, b) => a - b);\n\n default:\n return [0];\n }\n }\n\n private parsePageRange(rangeString: string): ParsedPageRange {\n try {\n const totalPages = this.coreState.core.document?.pages.length || 0;\n const pages: number[] = [];\n const parts = rangeString.split(',').map((s) => s.trim());\n\n for (const part of parts) {\n if (part.includes('-')) {\n // Handle range like \"5-10\"\n const [start, end] = part.split('-').map((s) => parseInt(s.trim()));\n\n if (isNaN(start) || isNaN(end)) {\n return { pages: [], isValid: false, error: `Invalid range: ${part}` };\n }\n\n if (start > end) {\n return { pages: [], isValid: false, error: `Invalid range: ${part} (start > end)` };\n }\n\n for (let i = start; i <= end; i++) {\n if (i >= 1 && i <= totalPages) {\n pages.push(i - 1); // Convert to 0-based index\n }\n }\n } else {\n // Handle single page\n const pageNum = parseInt(part);\n\n if (isNaN(pageNum)) {\n return { pages: [], isValid: false, error: `Invalid page number: ${part}` };\n }\n\n if (pageNum >= 1 && pageNum <= totalPages) {\n pages.push(pageNum - 1); // Convert to 0-based index\n }\n }\n }\n\n // Remove duplicates and sort\n const uniquePages = [...new Set(pages)].sort((a, b) => a - b);\n\n return {\n pages: uniquePages,\n isValid: true,\n };\n } catch (error) {\n return {\n pages: [],\n isValid: false,\n error: `Parsing error: ${error instanceof Error ? error.message : 'Unknown error'}`,\n };\n }\n }\n}\n","import { PluginPackage } from '@embedpdf/core';\nimport { manifest, PRINT_PLUGIN_ID } from './manifest';\nimport { PrintPluginConfig } from './types';\nimport { PrintPlugin } from './print-plugin';\n\nexport const PrintPluginPackage: PluginPackage<PrintPlugin, PrintPluginConfig> = {\n manifest,\n create: (registry, config) => new PrintPlugin(PRINT_PLUGIN_ID, registry, config),\n reducer: () => {},\n initialState: {},\n};\n\nexport * from './print-plugin';\nexport * from './types';\nexport * from './manifest';\n"],"names":["PrintQuality","PageRangeType"],"mappings":";;AAGO,MAAM,kBAAkB;AAExB,MAAM,WAA8C;AAAA,EACzD,IAAI;AAAA,EACJ,MAAM;AAAA,EACN,SAAS;AAAA,EACT,UAAU,CAAC,OAAO;AAAA,EAClB,UAAU,CAAC,QAAQ;AAAA,EACnB,UAAU,CAAC;AAAA,EACX,eAAe;AAAA,IACb,SAAS;AAAA,EAAA;AAEb;ACPY,IAAA,iCAAAA,kBAAL;AACLA,gBAAA,QAAS,IAAA;AACTA,gBAAA,MAAO,IAAA;AAFGA,SAAAA;AAAA,GAAA,gBAAA,CAAA,CAAA;AAKA,IAAA,kCAAAC,mBAAL;AACLA,iBAAA,SAAU,IAAA;AACVA,iBAAA,KAAM,IAAA;AACNA,iBAAA,QAAS,IAAA;AAHCA,SAAAA;AAAA,GAAA,iBAAA,CAAA,CAAA;ACEL,MAAM,eAAN,MAAM,qBAAoB,WAA+C;AA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OAAO;AAAA,QACP,SAAS;AAAA,MACX;AAAA,aACO,OAAO;AACP,aAAA;AAAA,QACL,OAAO,CAAC;AAAA,QACR,SAAS;AAAA,QACT,OAAO,kBAAkB,iBAAiB,QAAQ,MAAM,UAAU,eAAe;AAAA,MACnF;AAAA,IAAA;AAAA,EACF;AAEJ;AAhME,aAAgB,KAAK;AADhB,IAAM,cAAN;ACVA,MAAM,qBAAoE;AAAA,EAC/E;AAAA,EACA,QAAQ,CAAC,UAAU,WAAW,IAAI,YAAY,iBAAiB,UAAU,MAAM;AAAA,EAC/E,SAAS,MAAM;AAAA,EAAC;AAAA,EAChB,cAAc,CAAA;AAChB;"}
1
+ {"version":3,"file":"index.js","sources":["../src/lib/manifest.ts","../src/lib/print-plugin.ts","../src/lib/index.ts"],"sourcesContent":["import { PluginManifest } from '@embedpdf/core';\nimport { PrintPluginConfig } from './types';\n\nexport const PRINT_PLUGIN_ID = 'print';\n\nexport const manifest: PluginManifest<PrintPluginConfig> = {\n id: PRINT_PLUGIN_ID,\n name: 'Print Plugin',\n version: '1.0.0',\n provides: ['print'],\n requires: ['render'],\n optional: [],\n defaultConfig: {\n enabled: true,\n },\n};\n","import { BasePlugin, createEmitter, Listener, PluginRegistry, Unsubscribe } from '@embedpdf/core';\nimport {\n PdfErrorCode,\n PdfErrorReason,\n PdfPrintOptions,\n PdfTaskHelper,\n Task,\n} from '@embedpdf/models';\n\nimport { PrintCapability, PrintPluginConfig, PrintProgress, PrintReadyEvent } from './types';\n\nexport class PrintPlugin extends BasePlugin<PrintPluginConfig, PrintCapability> {\n static readonly id = 'print' as const;\n\n private readonly printReady$ = createEmitter<PrintReadyEvent>();\n\n constructor(id: string, registry: PluginRegistry, _config: PrintPluginConfig) {\n super(id, registry);\n }\n\n async initialize(_: PrintPluginConfig): Promise<void> {}\n\n protected buildCapability(): PrintCapability {\n return {\n print: this.print.bind(this),\n };\n }\n\n public onPrintRequest(listener: Listener<PrintReadyEvent>): Unsubscribe {\n return this.printReady$.on(listener);\n }\n\n private print(options: PdfPrintOptions): Task<ArrayBuffer, PdfErrorReason, PrintProgress> {\n const task = new Task<ArrayBuffer, PdfErrorReason, PrintProgress>();\n task.progress({ stage: 'preparing', message: 'Preparing document...' });\n\n const prepare = this.preparePrintDocument(options);\n prepare.wait((buffer) => {\n task.progress({ stage: 'document-ready', message: 'Document prepared successfully' });\n // Emit buffer + task for the framework layer to display & trigger print\n this.printReady$.emit({ options, buffer, task });\n }, task.fail);\n\n return task;\n }\n\n public preparePrintDocument(options: PdfPrintOptions): Task<ArrayBuffer, PdfErrorReason> {\n const document = this.coreState.core.document;\n\n if (!document) {\n return PdfTaskHelper.reject({\n code: PdfErrorCode.DocNotOpen,\n message: 'Document not found',\n });\n }\n\n return this.engine.preparePrintDocument(document, options);\n }\n}\n","import { PluginPackage } from '@embedpdf/core';\nimport { manifest, PRINT_PLUGIN_ID } from './manifest';\nimport { PrintPluginConfig } from './types';\nimport { PrintPlugin } from './print-plugin';\n\nexport const PrintPluginPackage: PluginPackage<PrintPlugin, PrintPluginConfig> = {\n manifest,\n create: (registry, config) => new PrintPlugin(PRINT_PLUGIN_ID, registry, config),\n reducer: () => {},\n initialState: {},\n};\n\nexport * from './print-plugin';\nexport * from './types';\nexport * from './manifest';\n"],"names":[],"mappings":";;AAGO,MAAM,kBAAkB;AAExB,MAAM,WAA8C;AAAA,EACzD,IAAI;AAAA,EACJ,MAAM;AAAA,EACN,SAAS;AAAA,EACT,UAAU,CAAC,OAAO;AAAA,EAClB,UAAU,CAAC,QAAQ;AAAA,EACnB,UAAU,CAAC;AAAA,EACX,eAAe;AAAA,IACb,SAAS;AAAA,EAAA;AAEb;ACJO,MAAM,eAAN,MAAM,qBAAoB,WAA+C;AAAA,EAK9E,YAAY,IAAY,UAA0B,SAA4B;AAC5E,UAAM,IAAI,QAAQ;AAHpB,SAAiB,cAAc,cAA+B;AAAA,EAAA;AAAA,EAM9D,MAAM,WAAW,GAAqC;AAAA,EAAA;AAAA,EAE5C,kBAAmC;AACpC,WAAA;AAAA,MACL,OAAO,KAAK,MAAM,KAAK,IAAI;AAAA,IAC7B;AAAA,EAAA;AAAA,EAGK,eAAe,UAAkD;AAC/D,WAAA,KAAK,YAAY,GAAG,QAAQ;AAAA,EAAA;AAAA,EAG7B,MAAM,SAA4E;AAClF,UAAA,OAAO,IAAI,KAAiD;AAClE,SAAK,SAAS,EAAE,OAAO,aAAa,SAAS,yBAAyB;AAEhE,UAAA,UAAU,KAAK,qBAAqB,OAAO;AACzC,YAAA,KAAK,CAAC,WAAW;AACvB,WAAK,SAAS,EAAE,OAAO,kBAAkB,SAAS,kCAAkC;AAEpF,WAAK,YAAY,KAAK,EAAE,SAAS,QAAQ,MAAM;AAAA,IAAA,GAC9C,KAAK,IAAI;AAEL,WAAA;AAAA,EAAA;AAAA,EAGF,qBAAqB,SAA6D;AACjF,UAAA,WAAW,KAAK,UAAU,KAAK;AAErC,QAAI,CAAC,UAAU;AACb,aAAO,cAAc,OAAO;AAAA,QAC1B,MAAM,aAAa;AAAA,QACnB,SAAS;AAAA,MAAA,CACV;AAAA,IAAA;AAGH,WAAO,KAAK,OAAO,qBAAqB,UAAU,OAAO;AAAA,EAAA;AAE7D;AA9CE,aAAgB,KAAK;AADhB,IAAM,cAAN;ACNA,MAAM,qBAAoE;AAAA,EAC/E;AAAA,EACA,QAAQ,CAAC,UAAU,WAAW,IAAI,YAAY,iBAAiB,UAAU,MAAM;AAAA,EAC/E,SAAS,MAAM;AAAA,EAAC;AAAA,EAChB,cAAc,CAAA;AAChB;"}
@@ -1,15 +1,13 @@
1
- import { BasePlugin, PluginRegistry } from '@embedpdf/core';
2
- import { PrintPluginConfig, PrintCapability } from './types';
1
+ import { BasePlugin, Listener, PluginRegistry, Unsubscribe } from '@embedpdf/core';
2
+ import { PdfErrorReason, PdfPrintOptions, Task } from '@embedpdf/models';
3
+ import { PrintCapability, PrintPluginConfig, PrintReadyEvent } from './types';
3
4
  export declare class PrintPlugin extends BasePlugin<PrintPluginConfig, PrintCapability> {
4
5
  static readonly id: "print";
5
- private readonly renderCapability;
6
- private readonly config;
7
- constructor(id: string, registry: PluginRegistry, config: PrintPluginConfig);
8
- initialize(_config: PrintPluginConfig): Promise<void>;
6
+ private readonly printReady$;
7
+ constructor(id: string, registry: PluginRegistry, _config: PrintPluginConfig);
8
+ initialize(_: PrintPluginConfig): Promise<void>;
9
9
  protected buildCapability(): PrintCapability;
10
- private preparePrint;
11
- private renderPage;
12
- private getScaleFactor;
13
- private getPagesToPrint;
14
- private parsePageRange;
10
+ onPrintRequest(listener: Listener<PrintReadyEvent>): Unsubscribe;
11
+ private print;
12
+ preparePrintDocument(options: PdfPrintOptions): Task<ArrayBuffer, PdfErrorReason>;
15
13
  }
@@ -1,56 +1,25 @@
1
1
  import { BasePluginConfig } from '@embedpdf/core';
2
+ import { PdfErrorReason, PdfPrintOptions, Task } from '@embedpdf/models';
2
3
  export interface PrintPluginConfig extends BasePluginConfig {
3
- defaultQuality?: PrintQuality;
4
- defaultIncludeAnnotations?: boolean;
5
- batchSize?: number;
6
4
  }
7
- export declare enum PrintQuality {
8
- Normal = "normal",
9
- High = "high"
10
- }
11
- export declare enum PageRangeType {
12
- Current = "current",
13
- All = "all",
14
- Custom = "custom"
15
- }
16
- export interface PageRangeCurrent {
17
- type: PageRangeType.Current;
18
- currentPage: number;
19
- }
20
- export interface PageRangeAll {
21
- type: PageRangeType.All;
22
- }
23
- export interface PageRangeCustom {
24
- type: PageRangeType.Custom;
25
- pages: number[];
26
- }
27
- export type PageRange = PageRangeCurrent | PageRangeAll | PageRangeCustom;
28
- export interface PrintOptions {
29
- pageRange: PageRange;
30
- includeAnnotations: boolean;
31
- quality: PrintQuality;
32
- }
33
- export interface PrintProgress {
34
- current: number;
35
- total: number;
36
- status: 'preparing' | 'rendering' | 'complete' | 'error';
37
- message?: string;
38
- }
39
- export interface PrintData {
40
- blobs: Blob[];
41
- options: PrintOptions;
42
- totalPages: number;
43
- }
44
- export interface ParsedPageRange {
45
- pages: number[];
46
- isValid: boolean;
47
- error?: string;
48
- }
49
- export interface PrintPageResult {
50
- pageIndex: number;
51
- blob: Blob;
5
+ export type PrintProgress = {
6
+ stage: 'preparing';
7
+ message: string;
8
+ } | {
9
+ stage: 'document-ready';
10
+ message: string;
11
+ } | {
12
+ stage: 'iframe-ready';
13
+ message: string;
14
+ } | {
15
+ stage: 'printing';
16
+ message: string;
17
+ };
18
+ export interface PrintReadyEvent {
19
+ options: PdfPrintOptions;
20
+ buffer: ArrayBuffer;
21
+ task: Task<ArrayBuffer, PdfErrorReason, PrintProgress>;
52
22
  }
53
23
  export interface PrintCapability {
54
- preparePrint: (options: PrintOptions, onProgress?: (progress: PrintProgress) => void, onPageReady?: (result: PrintPageResult) => void) => Promise<void>;
55
- parsePageRange: (rangeString: string) => ParsedPageRange;
24
+ print: (options: PdfPrintOptions) => Task<ArrayBuffer, PdfErrorReason, PrintProgress>;
56
25
  }
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("@embedpdf/core/preact"),t=require("@embedpdf/plugin-print"),r=require("preact/jsx-runtime"),n=require("preact"),i=require("preact/hooks"),s=()=>e.useCapability(t.PrintPlugin.id),o=n.createContext(null),a=({pageResult:e})=>{const[t,n]=i.useState("");i.useEffect((()=>{const t=URL.createObjectURL(e.blob);return n(t),()=>{URL.revokeObjectURL(t)}}),[e.blob]);return r.jsx("div",{style:{pageBreakAfter:"always",width:"210mm",minHeight:"297mm",margin:"0 auto",background:"white",position:"relative"},children:r.jsx("img",{src:t,onLoad:()=>{t&&URL.revokeObjectURL(t)},alt:`Page ${e.pageIndex+1}`,style:{width:"100%",height:"auto",display:"block",objectFit:"contain"}})})},l=({pages:e})=>r.jsxs("div",{style:{fontFamily:"Arial, sans-serif",fontSize:"12px",lineHeight:"1.4",color:"#000",backgroundColor:"#fff"},children:[r.jsx("style",{children:"\n @media print {\n body { margin: 0; padding: 0; }\n }\n "}),e.map((e=>r.jsx("div",{children:r.jsx(a,{pageResult:e})},e.pageIndex)))]});function u(){const e=i.useContext(o);if(!e)throw new Error("usePrintContext must be used within a PrintProvider");return e}exports.PrintProvider=function({children:e}){const{provides:t}=s(),a=i.useRef(null),[u,c]=i.useState(null),[d,p]=i.useState(!1),[g,P]=i.useState(!1),[m,f]=i.useState([]);i.useEffect((()=>{var e,t;const i=a.current,s=null==(t=null==(e=null==i?void 0:i.contentWindow)?void 0:e.document)?void 0:t.body;if(s&&m.length>0)return n.render(r.jsx(l,{pages:m}),s),p(!0),()=>{s&&n.render(null,s)}}),[m]);const x={parsePageRange:(null==t?void 0:t.parsePageRange)||(()=>({pages:[],isValid:!1})),executePrint:async e=>{var r;if(!t)throw new Error("Print capability not available");if(!(null==(r=a.current)?void 0:r.contentWindow))throw new Error("Print iframe not ready");P(!0),c(null),f([]),p(!1);try{const r=[];await t.preparePrint(e,(e=>{c(e)}),(e=>{r.push(e),f([...r])})),await new Promise((e=>setTimeout(e,500)));const n=a.current.contentWindow;n.focus(),n.print(),c({current:(null==u?void 0:u.total)||0,total:(null==u?void 0:u.total)||0,status:"complete",message:"Print dialog opened"})}catch(n){throw c({current:0,total:0,status:"error",message:`Print failed: ${n instanceof Error?n.message:"Unknown error"}`}),n}finally{P(!1)}},progress:u,isReady:d,isPrinting:g};return r.jsxs(o.Provider,{value:x,children:[e,r.jsx("iframe",{ref:a,style:{display:"none",width:"210mm",height:"297mm"},title:"Print Preview"})]})},exports.usePrintAction=()=>{const{executePrint:e,progress:t,isReady:r,isPrinting:n,parsePageRange:i}=u();return{executePrint:e,progress:t,isReady:r,isPrinting:n,parsePageRange:i}},exports.usePrintCapability=s,exports.usePrintContext=u,exports.usePrintPlugin=()=>e.usePlugin(t.PrintPlugin.id);
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("@embedpdf/core"),r=require("@embedpdf/plugin-print"),t=require("preact/jsx-runtime");require("preact");const n=require("preact/hooks"),i=require("@embedpdf/core/preact"),o=()=>i.usePlugin(r.PrintPlugin.id),u=()=>i.useCapability(r.PrintPlugin.id);function s(){const{provides:e}=u(),{plugin:r}=o(),i=n.useRef(null),s=n.useRef(null);return n.useEffect((()=>{if(!e||!r)return;const t=r.onPrintRequest((({buffer:e,task:r})=>{const t=i.current;if(!t)return;s.current&&(URL.revokeObjectURL(s.current),s.current=null);const n=URL.createObjectURL(new Blob([e],{type:"application/pdf"}));s.current=n,t.onload=()=>{var i,o;t.src===n&&(r.progress({stage:"iframe-ready",message:"Ready to print"}),null==(i=t.contentWindow)||i.focus(),null==(o=t.contentWindow)||o.print(),r.progress({stage:"printing",message:"Print dialog opened"}),r.resolve(e))},t.src=n}));return()=>{t(),s.current&&URL.revokeObjectURL(s.current)}}),[e,r]),t.jsx("iframe",{ref:i,style:{position:"absolute",display:"none"},title:"Print Document",src:"about:blank"})}const c=e.createPluginPackage(r.PrintPluginPackage).addUtility(s).build();exports.PrintFrame=s,exports.PrintPluginPackage=c,exports.usePrintCapability=u,exports.usePrintPlugin=o,Object.keys(r).forEach((e=>{"default"===e||Object.prototype.hasOwnProperty.call(exports,e)||Object.defineProperty(exports,e,{enumerable:!0,get:()=>r[e]})}));
2
2
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","sources":["../../src/shared/hooks/use-print.ts","../../src/shared/components/print.tsx","../../src/shared/hooks/use-print-action.ts"],"sourcesContent":["import { useCapability, usePlugin } from '@embedpdf/core/@framework';\nimport { PrintPlugin } from '@embedpdf/plugin-print';\n\nexport const usePrintPlugin = () => usePlugin<PrintPlugin>(PrintPlugin.id);\nexport const usePrintCapability = () => useCapability<PrintPlugin>(PrintPlugin.id);\n","import {\n createContext,\n render,\n useContext,\n useRef,\n useEffect,\n useState,\n ReactNode,\n} from '@framework';\nimport { usePrintCapability } from '../hooks/use-print';\nimport { PrintOptions, PrintProgress, PrintPageResult, ParsedPageRange } from '../../lib/types';\n\ninterface PrintContextValue {\n parsePageRange: (rangeString: string) => ParsedPageRange;\n executePrint: (options: PrintOptions) => Promise<void>;\n progress: PrintProgress | null;\n isReady: boolean;\n isPrinting: boolean;\n}\n\nconst PrintContext = createContext<PrintContextValue | null>(null);\n\ninterface PrintProviderProps {\n children: ReactNode;\n}\n\ninterface PrintPageProps {\n pageResult: PrintPageResult;\n}\n\nconst PrintPage = ({ pageResult }: PrintPageProps) => {\n const [imageUrl, setImageUrl] = useState<string>('');\n\n useEffect(() => {\n const url = URL.createObjectURL(pageResult.blob);\n setImageUrl(url);\n\n return () => {\n URL.revokeObjectURL(url);\n };\n }, [pageResult.blob]);\n\n const handleLoad = () => {\n if (imageUrl) {\n URL.revokeObjectURL(imageUrl);\n }\n };\n\n return (\n <div\n style={{\n pageBreakAfter: 'always',\n width: '210mm',\n minHeight: '297mm',\n margin: '0 auto',\n background: 'white',\n position: 'relative',\n }}\n >\n <img\n src={imageUrl}\n onLoad={handleLoad}\n alt={`Page ${pageResult.pageIndex + 1}`}\n style={{\n width: '100%',\n height: 'auto',\n display: 'block',\n objectFit: 'contain',\n }}\n />\n </div>\n );\n};\n\ninterface PrintLayoutProps {\n pages: PrintPageResult[];\n}\n\nconst PrintLayout = ({ pages }: PrintLayoutProps) => {\n return (\n <div\n style={{\n fontFamily: 'Arial, sans-serif',\n fontSize: '12px',\n lineHeight: '1.4',\n color: '#000',\n backgroundColor: '#fff',\n }}\n >\n <style>{`\n @media print {\n body { margin: 0; padding: 0; }\n }\n `}</style>\n {pages.map((pageResult) => (\n <div key={pageResult.pageIndex}>\n <PrintPage pageResult={pageResult} />\n </div>\n ))}\n </div>\n );\n};\n\nexport function PrintProvider({ children }: PrintProviderProps) {\n const { provides: printCapability } = usePrintCapability();\n const iframeRef = useRef<HTMLIFrameElement>(null);\n const [progress, setProgress] = useState<PrintProgress | null>(null);\n const [isReady, setIsReady] = useState(false);\n const [isPrinting, setIsPrinting] = useState(false);\n const [pages, setPages] = useState<PrintPageResult[]>([]);\n\n const executePrint = async (options: PrintOptions): Promise<void> => {\n if (!printCapability) {\n throw new Error('Print capability not available');\n }\n\n if (!iframeRef.current?.contentWindow) {\n throw new Error('Print iframe not ready');\n }\n\n setIsPrinting(true);\n setProgress(null);\n setPages([]);\n setIsReady(false);\n\n try {\n const collectedPages: PrintPageResult[] = [];\n\n // Prepare print with progress tracking\n await printCapability.preparePrint(\n options,\n // Progress callback\n (progressUpdate: PrintProgress) => {\n setProgress(progressUpdate);\n },\n // Page ready callback\n (pageResult: PrintPageResult) => {\n collectedPages.push(pageResult);\n setPages([...collectedPages]); // Update pages as they come in\n },\n );\n\n // Wait a bit for all content to load\n await new Promise((resolve) => setTimeout(resolve, 500));\n\n // Execute print\n const printWindow = iframeRef.current.contentWindow!;\n printWindow.focus();\n printWindow.print();\n\n setProgress({\n current: progress?.total || 0,\n total: progress?.total || 0,\n status: 'complete',\n message: 'Print dialog opened',\n });\n } catch (error) {\n setProgress({\n current: 0,\n total: 0,\n status: 'error',\n message: `Print failed: ${error instanceof Error ? error.message : 'Unknown error'}`,\n });\n throw error;\n } finally {\n setIsPrinting(false);\n }\n };\n\n // Render the print layout into the iframe when pages change\n useEffect(() => {\n const iframe = iframeRef.current;\n const mountNode = iframe?.contentWindow?.document?.body;\n\n if (mountNode && pages.length > 0) {\n render(<PrintLayout pages={pages} />, mountNode);\n setIsReady(true);\n\n return () => {\n if (mountNode) {\n render(null, mountNode);\n }\n };\n }\n }, [pages]);\n\n const contextValue: PrintContextValue = {\n parsePageRange: printCapability?.parsePageRange || (() => ({ pages: [], isValid: false })),\n executePrint,\n progress,\n isReady,\n isPrinting,\n };\n\n return (\n <PrintContext.Provider value={contextValue}>\n {children}\n <iframe\n ref={iframeRef}\n style={{\n display: 'none',\n width: '210mm',\n height: '297mm',\n }}\n title=\"Print Preview\"\n />\n </PrintContext.Provider>\n );\n}\n\nexport function usePrintContext(): PrintContextValue {\n const context = useContext(PrintContext);\n if (!context) {\n throw new Error('usePrintContext must be used within a PrintProvider');\n }\n return context;\n}\n","import { PrintOptions } from '@embedpdf/plugin-print';\nimport { usePrintContext } from '../components';\n\nexport const usePrintAction = () => {\n const { executePrint, progress, isReady, isPrinting, parsePageRange } = usePrintContext();\n\n return {\n executePrint,\n progress,\n isReady,\n isPrinting,\n parsePageRange,\n };\n};\n"],"names":["usePrintCapability","useCapability","PrintPlugin","id","PrintContext","createContext","PrintPage","pageResult","imageUrl","setImageUrl","useState","useEffect","url","URL","createObjectURL","blob","revokeObjectURL","jsxRuntime","jsx","style","pageBreakAfter","width","minHeight","margin","background","position","children","src","onLoad","alt","pageIndex","height","display","objectFit","PrintLayout","pages","jsxs","fontFamily","fontSize","lineHeight","color","backgroundColor","map","usePrintContext","context","useContext","Error","provides","printCapability","iframeRef","useRef","progress","setProgress","isReady","setIsReady","isPrinting","setIsPrinting","setPages","iframe","current","mountNode","_b","_a","contentWindow","document","body","length","preact$1","render","contextValue","parsePageRange","isValid","executePrint","async","options","collectedPages","preparePrint","progressUpdate","push","Promise","resolve","setTimeout","printWindow","focus","print","total","status","message","error","Provider","value","ref","title","usePlugin"],"mappings":"2OAIaA,EAAqB,IAAMC,gBAA2BC,EAAAA,YAAYC,ICgBzEC,EAAeC,gBAAwC,MAUvDC,EAAY,EAAGC,iBACnB,MAAOC,EAAUC,GAAeC,EAAAA,SAAiB,IAEjDC,EAAAA,WAAU,KACR,MAAMC,EAAMC,IAAIC,gBAAgBP,EAAWQ,MAG3C,OAFAN,EAAYG,GAEL,KACLC,IAAIG,gBAAgBJ,EAAG,CACzB,GACC,CAACL,EAAWQ,OASb,OAAAE,EAAAC,IAAC,MAAA,CACCC,MAAO,CACLC,eAAgB,SAChBC,MAAO,QACPC,UAAW,QACXC,OAAQ,SACRC,WAAY,QACZC,SAAU,YAGZC,SAAAT,EAAAC,IAAC,MAAA,CACCS,IAAKnB,EACLoB,OAnBa,KACbpB,GACFK,IAAIG,gBAAgBR,EAAQ,EAkB1BqB,IAAK,QAAQtB,EAAWuB,UAAY,IACpCX,MAAO,CACLE,MAAO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,GAAc,GACdJ,EAAY,MACZK,EAAS,IACTH,GAAW,GAEP,IACF,MAAMqB,EAAoC,SAGpC3B,EAAgB4B,aACpBF,GAECG,IACCzB,EAAYyB,EAAc,IAG3BtE,IACCoE,EAAeG,KAAKvE,GACXkD,EAAA,IAAIkB,GAAe,UAK1B,IAAII,SAASC,GAAYC,WAAWD,EAAS,OAG7C,MAAAE,EAAcjC,EAAUU,QAAQI,cACtCmB,EAAYC,QACZD,EAAYE,QAEAhC,EAAA,CACVO,eAASR,WAAUkC,QAAS,EAC5BA,aAAOlC,WAAUkC,QAAS,EAC1BC,OAAQ,WACRC,QAAS,8BAEJC,GAOD,MANMpC,EAAA,CACVO,QAAS,EACT0B,MAAO,EACPC,OAAQ,QACRC,QAAS,iBAAiBC,aAAiB1C,MAAQ0C,EAAMD,QAAU,oBAE/DC,CAAA,CACN,QACAhC,GAAc,EAAK,GAwBrBL,WACAE,UACAE,cAGF,SACGnB,KAAAhC,EAAaqF,SAAb,CAAsBC,MAAOrB,EAC3B3C,SAAA,CAAAA,EACDT,EAAAC,IAAC,SAAA,CACCyE,IAAK1C,EACL9B,MAAO,CACLa,QAAS,OACTX,MAAO,QACPU,OAAQ,SAEV6D,MAAM,oBAId,yBC7M8B,KAC5B,MAAMpB,aAAEA,EAAcrB,SAAAA,EAAAE,QAAUA,aAASE,EAAYe,eAAAA,GAAmB3B,IAEjE,MAAA,CACL6B,eACArB,WACAE,UACAE,aACAe,iBACF,gFFT4B,IAAMuB,YAAuB3F,EAAAA,YAAYC"}
1
+ {"version":3,"file":"index.cjs","sources":["../../src/shared/hooks/use-print.ts","../../src/shared/components/print.tsx","../../src/shared/index.ts"],"sourcesContent":["import { useCapability, usePlugin } from '@embedpdf/core/@framework';\nimport { PrintPlugin } from '@embedpdf/plugin-print';\n\nexport const usePrintPlugin = () => usePlugin<PrintPlugin>(PrintPlugin.id);\nexport const usePrintCapability = () => useCapability<PrintPlugin>(PrintPlugin.id);\n","import { useEffect, useRef } from '@framework';\nimport { usePrintCapability, usePrintPlugin } from '../hooks';\n\nexport function PrintFrame() {\n const { provides: printCapability } = usePrintCapability();\n const { plugin: printPlugin } = usePrintPlugin();\n const iframeRef = useRef<HTMLIFrameElement | null>(null);\n const urlRef = useRef<string | null>(null);\n\n useEffect(() => {\n if (!printCapability || !printPlugin) return;\n\n const unsubscribe = printPlugin.onPrintRequest(({ buffer, task }) => {\n const iframe = iframeRef.current;\n if (!iframe) return;\n\n // cleanup old URL\n if (urlRef.current) {\n URL.revokeObjectURL(urlRef.current);\n urlRef.current = null;\n }\n\n const url = URL.createObjectURL(new Blob([buffer], { type: 'application/pdf' }));\n urlRef.current = url;\n\n iframe.onload = () => {\n if (iframe.src === url) {\n task.progress({ stage: 'iframe-ready', message: 'Ready to print' });\n iframe.contentWindow?.focus();\n iframe.contentWindow?.print();\n task.progress({ stage: 'printing', message: 'Print dialog opened' });\n task.resolve(buffer);\n }\n };\n\n iframe.src = url;\n });\n\n return () => {\n unsubscribe();\n if (urlRef.current) {\n URL.revokeObjectURL(urlRef.current);\n }\n };\n }, [printCapability, printPlugin]);\n\n return (\n <iframe\n ref={iframeRef}\n style={{ position: 'absolute', display: 'none' }}\n title=\"Print Document\"\n src=\"about:blank\"\n />\n );\n}\n","import { createPluginPackage } from '@embedpdf/core';\nimport { PrintPluginPackage as BasePrintPackage } from '@embedpdf/plugin-print';\n\nimport { PrintFrame } from './components';\n\nexport * from './hooks';\nexport * from './components';\nexport * from '@embedpdf/plugin-print';\n\nexport const PrintPluginPackage = createPluginPackage(BasePrintPackage)\n .addUtility(PrintFrame)\n .build();\n"],"names":["usePrintPlugin","usePlugin","PrintPlugin","id","usePrintCapability","useCapability","PrintFrame","provides","printCapability","plugin","printPlugin","iframeRef","useRef","urlRef","useEffect","unsubscribe","onPrintRequest","buffer","task","iframe","current","URL","revokeObjectURL","url","createObjectURL","Blob","type","onload","src","progress","stage","message","_a","contentWindow","focus","_b","print","resolve","jsxRuntime","jsx","ref","style","position","display","title","PrintPluginPackage","createPluginPackage","BasePrintPackage","addUtility","build"],"mappings":"2QAGaA,EAAiB,IAAMC,YAAuBC,EAAAA,YAAYC,IAC1DC,EAAqB,IAAMC,gBAA2BH,EAAAA,YAAYC,ICDxE,SAASG,IACd,MAAQC,SAAUC,GAAoBJ,KAC9BK,OAAQC,GAAgBV,IAC1BW,EAAYC,SAAiC,MAC7CC,EAASD,SAAsB,MAwCnC,OAtCFE,EAAAA,WAAU,KACJ,IAACN,IAAoBE,EAAa,OAEtC,MAAMK,EAAcL,EAAYM,gBAAe,EAAGC,SAAQC,WACxD,MAAMC,EAASR,EAAUS,QACzB,IAAKD,EAAQ,OAGTN,EAAOO,UACLC,IAAAC,gBAAgBT,EAAOO,SAC3BP,EAAOO,QAAU,MAGnB,MAAMG,EAAMF,IAAIG,gBAAgB,IAAIC,KAAK,CAACR,GAAS,CAAES,KAAM,qBAC3Db,EAAOO,QAAUG,EAEjBJ,EAAOQ,OAAS,aACVR,EAAOS,MAAQL,IACjBL,EAAKW,SAAS,CAAEC,MAAO,eAAgBC,QAAS,mBAChD,OAAAC,EAAAb,EAAOc,gBAAeD,EAAAE,QACtB,OAAAC,EAAAhB,EAAOc,gBAAeE,EAAAC,QACtBlB,EAAKW,SAAS,CAAEC,MAAO,WAAYC,QAAS,wBAC5Cb,EAAKmB,QAAQpB,GAAM,EAIvBE,EAAOS,IAAML,CAAA,IAGf,MAAO,KACOR,IACRF,EAAOO,SACLC,IAAAC,gBAAgBT,EAAOO,QAAO,CAEtC,GACC,CAACZ,EAAiBE,IAGnB4B,EAAAC,IAAC,SAAA,CACCC,IAAK7B,EACL8B,MAAO,CAAEC,SAAU,WAAYC,QAAS,QACxCC,MAAM,iBACNhB,IAAI,eAGV,CC7CO,MAAMiB,EAAqBC,EAAoBA,oBAAAC,EAAgBF,oBACnEG,WAAW1C,GACX2C"}