kviewer 0.3.2 → 0.3.3

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/module.d.mts CHANGED
@@ -1,5 +1,5 @@
1
1
  import * as _nuxt_schema from '@nuxt/schema';
2
- export { ActiveTool, AddFormFieldPayload, CheckboxStyle, ExportPdfOptions, FormFieldDefinition, FormFieldOrigin, FormFieldType, FormFieldValue, KVIEWER_EMBED_PROTOCOL_VERSION, KViewerApi, KViewerEmbedBridgeOptions, KViewerEmbedClient, KViewerEmbedClientOptions, KViewerEmbedEventName, KViewerEmbedEventPayloads, KViewerEmbedMethodName, PlacedFieldDefaults, SignatureData, SignatureFieldStatus, SignatureHandlers, ViewMode, ViewerBottomToolId, ViewerLayoutToolId, ViewerMenuButtonItem, ViewerMenuCheckboxItem, ViewerMenuItem, ViewerMenuSeparatorItem, ViewerState, ViewerToolEntry, ViewerToolId, ViewerToolSlot, ViewerTopToolId, useKViewerEmbedBridge } from '../dist/runtime/public-types.js';
2
+ export { ActiveTool, AddFormFieldPayload, CheckboxStyle, ExportPdfOptions, FormFieldDefinition, FormFieldOrigin, FormFieldType, FormFieldValue, KVIEWER_EMBED_PROTOCOL_VERSION, KVIEWER_EMBED_UNSUPPORTED_METHOD_ERROR_NAME, KViewerApi, KViewerEmbedBridgeOptions, KViewerEmbedClient, KViewerEmbedClientOptions, KViewerEmbedEventName, KViewerEmbedEventPayloads, KViewerEmbedMethodName, KViewerHostApi, PlacedFieldDefaults, SignatureData, SignatureFieldStatus, SignatureHandlers, ViewMode, ViewerBottomToolId, ViewerLayoutToolId, ViewerMenuButtonItem, ViewerMenuCheckboxItem, ViewerMenuItem, ViewerMenuSeparatorItem, ViewerState, ViewerToolEntry, ViewerToolId, ViewerToolSlot, ViewerTopToolId, useKViewerEmbedBridge } from '../dist/runtime/public-types.js';
3
3
 
4
4
  interface ModuleOptions {
5
5
  /**
package/dist/module.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "kviewer",
3
3
  "configKey": "kviewer",
4
- "version": "0.3.2",
4
+ "version": "0.3.3",
5
5
  "builder": {
6
6
  "@nuxt/module-builder": "1.0.2",
7
7
  "unbuild": "3.6.1"
package/dist/module.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  import { createRequire } from 'node:module';
2
2
  import { dirname, join } from 'node:path';
3
3
  import { defineNuxtModule, createResolver, extendViteConfig, addPlugin, addComponentsDir, addImports } from '@nuxt/kit';
4
- export { KVIEWER_EMBED_PROTOCOL_VERSION, KViewerEmbedClient, useKViewerEmbedBridge } from '../dist/runtime/public-types.js';
4
+ export { KVIEWER_EMBED_PROTOCOL_VERSION, KVIEWER_EMBED_UNSUPPORTED_METHOD_ERROR_NAME, KViewerEmbedClient, useKViewerEmbedBridge } from '../dist/runtime/public-types.js';
5
5
 
6
6
  const module$1 = defineNuxtModule({
7
7
  meta: {
@@ -34,19 +34,14 @@ const module$1 = defineNuxtModule({
34
34
  config.optimizeDeps ||= {};
35
35
  config.optimizeDeps.include ||= [];
36
36
  config.optimizeDeps.include.push(
37
- "konva",
38
- "pdf-lib",
39
- "pdfjs-dist/legacy/build/pdf.mjs",
40
- "pdfjs-dist/web/pdf_viewer.mjs",
41
- // unicode-font.ts registers @pdf-lib/fontkit for Unicode font
42
- // embedding. Its ESM build does `import pako from 'pako'`, but pako 1.x
43
- // is CJS with no `default` export so unless fontkit is pre-bundled
44
- // (where esbuild applies CJS interop and synthesizes the default), the
45
- // browser receives the raw pako index.js and throws "does not provide
46
- // an export named 'default'". The `kviewer >` prefix anchors resolution
47
- // through this module, so it works even when pnpm leaves fontkit
48
- // un-hoisted in the consumer (a bare '@pdf-lib/fontkit' entry would not
49
- // resolve from the consumer root and Vite would silently skip it).
37
+ "kviewer > konva",
38
+ "kviewer > pdf-lib",
39
+ "kviewer > pdfjs-dist/legacy/build/pdf.mjs",
40
+ "kviewer > pdfjs-dist/web/pdf_viewer.mjs",
41
+ // fontkit's ESM build does `import pako from 'pako'`, but pako 1.x is
42
+ // CJS with no `default` export without pre-bundling (where esbuild
43
+ // synthesizes it) the browser throws "does not provide an export named
44
+ // 'default'".
50
45
  "kviewer > @pdf-lib/fontkit"
51
46
  );
52
47
  });
@@ -71,7 +66,12 @@ const module$1 = defineNuxtModule({
71
66
  addImports([
72
67
  { name: "useKViewerEmbedBridge", from: resolve("./runtime/embed/bridge-host") },
73
68
  { name: "KViewerEmbedClient", from: resolve("./runtime/embed/bridge-client") },
74
- { name: "KVIEWER_EMBED_PROTOCOL_VERSION", from: resolve("./runtime/embed/protocol") }
69
+ { name: "KVIEWER_EMBED_PROTOCOL_VERSION", from: resolve("./runtime/embed/protocol") },
70
+ {
71
+ name: "UNSUPPORTED_METHOD_ERROR_NAME",
72
+ as: "KVIEWER_EMBED_UNSUPPORTED_METHOD_ERROR_NAME",
73
+ from: resolve("./runtime/embed/protocol")
74
+ }
75
75
  ]);
76
76
  const require_ = createRequire(import.meta.url);
77
77
  const pdfjsDir = dirname(require_.resolve("pdfjs-dist/package.json"));
@@ -322,14 +322,7 @@ async function buildSignedSignatureAppearance(pdfDoc, dataUrl, width, height) {
322
322
  const mimeType = match[1] ?? "";
323
323
  const base64 = match[2] ?? "";
324
324
  const image = mimeType.includes("jpeg") || mimeType.includes("jpg") ? await pdfDoc.embedJpg(base64) : await pdfDoc.embedPng(base64);
325
- const imgAspect = image.width / image.height;
326
- const boxAspect = width / height;
327
- let drawW = width;
328
- let drawH = height;
329
- if (imgAspect > boxAspect) drawH = width / imgAspect;
330
- else drawW = height * imgAspect;
331
- const drawX = (width - drawW) / 2;
332
- const drawY = (height - drawH) / 2;
325
+ const { drawX, drawY, drawW, drawH } = fitImageInBox(image, width, height);
333
326
  const ops = [
334
327
  "q",
335
328
  `${drawW.toFixed(3)} 0 0 ${drawH.toFixed(3)} ${drawX.toFixed(3)} ${drawY.toFixed(3)} cm`,
@@ -346,6 +339,20 @@ async function buildSignedSignatureAppearance(pdfDoc, dataUrl, width, height) {
346
339
  const stream = PDFRawStream.of(dict, new TextEncoder().encode(ops));
347
340
  return pdfDoc.context.register(stream);
348
341
  }
342
+ function fitImageInBox(image, boxW, boxH) {
343
+ const imgAspect = image.width / image.height;
344
+ const boxAspect = boxW / boxH;
345
+ let drawW = boxW;
346
+ let drawH = boxH;
347
+ if (imgAspect > boxAspect) drawH = boxW / imgAspect;
348
+ else drawW = boxH * imgAspect;
349
+ return {
350
+ drawX: (boxW - drawW) / 2,
351
+ drawY: (boxH - drawH) / 2,
352
+ drawW,
353
+ drawH
354
+ };
355
+ }
349
356
  async function embedSignatureImage(pdfDoc, field) {
350
357
  const dataUrl = field.value;
351
358
  const match = dataUrl.match(/^data:(image\/[a-zA-Z0-9.+-]+);base64,(.+)$/);
@@ -370,11 +377,12 @@ async function embedSignatureImage(pdfDoc, field) {
370
377
  const pageRef = page.ref;
371
378
  const widgetPage = widget.P();
372
379
  if (widgetPage === pageRef || !widgetPage) {
380
+ const { drawX, drawY, drawW, drawH } = fitImageInBox(image, rect.width, rect.height);
373
381
  page.drawImage(image, {
374
- x: rect.x,
375
- y: rect.y,
376
- width: rect.width,
377
- height: rect.height
382
+ x: rect.x + drawX,
383
+ y: rect.y + drawY,
384
+ width: drawW,
385
+ height: drawH
378
386
  });
379
387
  break;
380
388
  }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Print a PDF by handing the actual (vector) bytes to the browser's native
3
+ * PDF pipeline, instead of letting the print dialog rasterize the on-screen
4
+ * canvases: a hidden iframe loads the blob and `contentWindow.print()` opens
5
+ * the dialog with the full-resolution document.
6
+ *
7
+ * On iOS/iPadOS Safari an iframe renders only the first PDF page, so there
8
+ * the blob opens in a new tab and the user prints from the native preview
9
+ * (share sheet → Print). Same fallback if `print()` throws (some browsers
10
+ * refuse to script-print plugin documents).
11
+ */
12
+ export declare function printPdfBytes(data: Uint8Array): Promise<void>;
@@ -0,0 +1,63 @@
1
+ import { isIPad } from "../../annotation/engine/input-device.js";
2
+ let activeFrame = null;
3
+ let activeUrl = null;
4
+ function reclaimPrevious() {
5
+ activeFrame?.remove();
6
+ activeFrame = null;
7
+ if (activeUrl) {
8
+ URL.revokeObjectURL(activeUrl);
9
+ activeUrl = null;
10
+ }
11
+ }
12
+ function openInNewTab(url) {
13
+ const win = window.open(url, "_blank");
14
+ if (!win) {
15
+ throw new Error(
16
+ "Could not open the PDF for printing \u2014 the popup was blocked. Allow popups for this site and try again."
17
+ );
18
+ }
19
+ }
20
+ export async function printPdfBytes(data) {
21
+ reclaimPrevious();
22
+ const arrayBuffer = Uint8Array.from(data).buffer;
23
+ const blob = new Blob([arrayBuffer], { type: "application/pdf" });
24
+ const url = URL.createObjectURL(blob);
25
+ activeUrl = url;
26
+ const isAppleMobile = isIPad() || /iPhone|iPod/.test(navigator.userAgent);
27
+ if (isAppleMobile) {
28
+ openInNewTab(url);
29
+ return;
30
+ }
31
+ const frame = document.createElement("iframe");
32
+ frame.style.position = "fixed";
33
+ frame.style.right = "0";
34
+ frame.style.bottom = "0";
35
+ frame.style.width = "1px";
36
+ frame.style.height = "1px";
37
+ frame.style.border = "0";
38
+ frame.style.visibility = "hidden";
39
+ frame.src = url;
40
+ activeFrame = frame;
41
+ await new Promise((resolve, reject) => {
42
+ const timer = setTimeout(() => {
43
+ reject(new Error("Timed out loading the PDF for printing"));
44
+ }, 15e3);
45
+ frame.addEventListener(
46
+ "load",
47
+ () => {
48
+ clearTimeout(timer);
49
+ resolve();
50
+ },
51
+ { once: true }
52
+ );
53
+ document.body.appendChild(frame);
54
+ });
55
+ try {
56
+ const win = frame.contentWindow;
57
+ if (!win) throw new Error("Print frame has no window");
58
+ win.focus();
59
+ win.print();
60
+ } catch {
61
+ openInNewTab(url);
62
+ }
63
+ }
@@ -78,6 +78,11 @@ type __VLS_Props = {
78
78
  messages?: KviewerMessageOverrides;
79
79
  };
80
80
  declare function exportPdf(options?: ExportPdfOptions): Promise<Uint8Array>;
81
+ /** Print via the real PDF instead of the on-screen canvases: export the
82
+ * document (annotations + form values baked in) and hand the vector bytes
83
+ * to the browser's native PDF print pipeline. Screen canvases are sized
84
+ * for the monitor and would come out blurry on paper. */
85
+ declare function printPdf(options?: ExportPdfOptions): Promise<void>;
81
86
  type ImportMode = 'replace' | 'merge';
82
87
  declare function importAnnotations(annotations: IAnnotationStore[], options?: {
83
88
  mode?: ImportMode;
@@ -100,6 +105,10 @@ declare const __VLS_base: import("vue").DefineComponent<__VLS_Props, {
100
105
  getAnnotations: () => IAnnotationStore[];
101
106
  importAnnotations: typeof importAnnotations;
102
107
  exportPdf: typeof exportPdf;
108
+ /** Export the document (same options as `exportPdf`, minus `download`)
109
+ * and open the browser's print dialog on the resulting vector PDF —
110
+ * full print quality, unlike printing the screen canvases. */
111
+ printPdf: typeof printPdf;
103
112
  getKonvaCanvasState: typeof getKonvaCanvasState;
104
113
  getFormFieldValues: () => import("../annotation/engine/types.js").FormFieldValue[];
105
114
  setFormFieldValue: (fieldName: string, value: string | boolean | string[]) => void;
@@ -180,6 +189,7 @@ declare const __VLS_base: import("vue").DefineComponent<__VLS_Props, {
180
189
  clickToSign: boolean;
181
190
  readonly: boolean;
182
191
  active: boolean;
192
+ formEditMode: boolean;
183
193
  locale: KviewerLocale;
184
194
  menuItems: ViewerMenuItem[];
185
195
  tools: ViewerToolEntry[];
@@ -188,7 +198,6 @@ declare const __VLS_base: import("vue").DefineComponent<__VLS_Props, {
188
198
  signatureHandlers: SignatureHandlers;
189
199
  viewMode: ViewMode;
190
200
  shapeDetection: boolean;
191
- formEditMode: boolean;
192
201
  roleColors: Record<string, string>;
193
202
  activeRoleId: string | null;
194
203
  editablePlacedFields: boolean;
@@ -214,6 +214,7 @@ import {
214
214
  } from "../annotation/pdf-import/decode";
215
215
  import { getTimestampString } from "../annotation/engine/utils";
216
216
  import { downloadPdfBytes } from "../annotation/pdf-export/download";
217
+ import { printPdfBytes } from "../annotation/pdf-export/print";
217
218
  import { exportAnnotationsToPdf } from "../annotation/pdf-export/export";
218
219
  import { createPageVirtualization } from "../composables/usePageVirtualization";
219
220
  import { createPageProxyCache } from "../composables/usePageProxyCache";
@@ -260,7 +261,7 @@ const fieldPlacedCallbacks = /* @__PURE__ */ new Set();
260
261
  const signedStatusCallbacks = /* @__PURE__ */ new Set();
261
262
  const viewerRoot = ref(null);
262
263
  const scrollContainer = ref(null);
263
- const { state: viewerState, setScrollToPageFn, setDownloadPdfFn, setApplyScaleFn } = provideViewerState();
264
+ const { state: viewerState, setScrollToPageFn, setDownloadPdfFn, setPrintPdfFn, setApplyScaleFn } = provideViewerState();
264
265
  watchEffect(() => {
265
266
  viewerState.readonly.value = props.readonly ?? false;
266
267
  });
@@ -806,6 +807,18 @@ async function exportPdf(options = {}) {
806
807
  }
807
808
  return bytes;
808
809
  }
810
+ async function printPdf(options = {}) {
811
+ if (scriptingManager?.isReady()) {
812
+ await scriptingManager.dispatchWillPrint().catch(() => {
813
+ });
814
+ }
815
+ const bytes = await exportPdf({ ...options, download: false });
816
+ await printPdfBytes(bytes);
817
+ if (scriptingManager?.isReady()) {
818
+ scriptingManager.dispatchDidPrint().catch(() => {
819
+ });
820
+ }
821
+ }
809
822
  async function importAnnotations(annotations, options) {
810
823
  const mode = options?.mode ?? "replace";
811
824
  const normalized = normalizeImportedAnnotations(
@@ -1025,6 +1038,9 @@ onMounted(() => {
1025
1038
  setDownloadPdfFn(async () => {
1026
1039
  await exportPdf({ download: true });
1027
1040
  });
1041
+ setPrintPdfFn(async () => {
1042
+ await printPdf();
1043
+ });
1028
1044
  loadDocument();
1029
1045
  window.addEventListener("keydown", onGlobalKeydown);
1030
1046
  });
@@ -1094,6 +1110,10 @@ defineExpose({
1094
1110
  getAnnotations: () => painter?.getData() ?? [],
1095
1111
  importAnnotations,
1096
1112
  exportPdf,
1113
+ /** Export the document (same options as `exportPdf`, minus `download`)
1114
+ * and open the browser's print dialog on the resulting vector PDF —
1115
+ * full print quality, unlike printing the screen canvases. */
1116
+ printPdf,
1097
1117
  getKonvaCanvasState,
1098
1118
  getFormFieldValues: () => formFieldsState.getAllFieldValues(),
1099
1119
  setFormFieldValue: (fieldName, value) => formFieldsState.setFieldValueByName(fieldName, value),
@@ -78,6 +78,11 @@ type __VLS_Props = {
78
78
  messages?: KviewerMessageOverrides;
79
79
  };
80
80
  declare function exportPdf(options?: ExportPdfOptions): Promise<Uint8Array>;
81
+ /** Print via the real PDF instead of the on-screen canvases: export the
82
+ * document (annotations + form values baked in) and hand the vector bytes
83
+ * to the browser's native PDF print pipeline. Screen canvases are sized
84
+ * for the monitor and would come out blurry on paper. */
85
+ declare function printPdf(options?: ExportPdfOptions): Promise<void>;
81
86
  type ImportMode = 'replace' | 'merge';
82
87
  declare function importAnnotations(annotations: IAnnotationStore[], options?: {
83
88
  mode?: ImportMode;
@@ -100,6 +105,10 @@ declare const __VLS_base: import("vue").DefineComponent<__VLS_Props, {
100
105
  getAnnotations: () => IAnnotationStore[];
101
106
  importAnnotations: typeof importAnnotations;
102
107
  exportPdf: typeof exportPdf;
108
+ /** Export the document (same options as `exportPdf`, minus `download`)
109
+ * and open the browser's print dialog on the resulting vector PDF —
110
+ * full print quality, unlike printing the screen canvases. */
111
+ printPdf: typeof printPdf;
103
112
  getKonvaCanvasState: typeof getKonvaCanvasState;
104
113
  getFormFieldValues: () => import("../annotation/engine/types.js").FormFieldValue[];
105
114
  setFormFieldValue: (fieldName: string, value: string | boolean | string[]) => void;
@@ -180,6 +189,7 @@ declare const __VLS_base: import("vue").DefineComponent<__VLS_Props, {
180
189
  clickToSign: boolean;
181
190
  readonly: boolean;
182
191
  active: boolean;
192
+ formEditMode: boolean;
183
193
  locale: KviewerLocale;
184
194
  menuItems: ViewerMenuItem[];
185
195
  tools: ViewerToolEntry[];
@@ -188,7 +198,6 @@ declare const __VLS_base: import("vue").DefineComponent<__VLS_Props, {
188
198
  signatureHandlers: SignatureHandlers;
189
199
  viewMode: ViewMode;
190
200
  shapeDetection: boolean;
191
- formEditMode: boolean;
192
201
  roleColors: Record<string, string>;
193
202
  activeRoleId: string | null;
194
203
  editablePlacedFields: boolean;
@@ -13,6 +13,16 @@
13
13
  data-testid="viewer-download"
14
14
  @click="onDownload"
15
15
  />
16
+ <UButton
17
+ icon="i-lucide-printer"
18
+ :label="t('print')"
19
+ variant="ghost"
20
+ color="neutral"
21
+ size="xs"
22
+ class="w-full justify-start"
23
+ data-testid="viewer-print"
24
+ @click="onPrint"
25
+ />
16
26
  <UButton
17
27
  :icon="state.shapeDetection.value ? 'i-lucide-square-check-big' : 'i-lucide-square-dashed'"
18
28
  :label="state.shapeDetection.value ? t('disableFormFieldDetection') : t('detectFormFields')"
@@ -76,4 +86,11 @@ async function onDownload() {
76
86
  console.error("Failed to export PDF from menu action", error);
77
87
  }
78
88
  }
89
+ async function onPrint() {
90
+ try {
91
+ await state.printPdf();
92
+ } catch (error) {
93
+ console.error("Failed to print PDF from menu action", error);
94
+ }
95
+ }
79
96
  </script>
@@ -44,6 +44,11 @@ export interface ScriptingManager {
44
44
  * PageOpen action can fire (the manager's `updatefromsandbox` /
45
45
  * pagerendered handling in pdf_viewer.mjs). */
46
46
  notifyPageRendered: (pageNumber: number) => void;
47
+ /** Run the document's `WillPrint` action and wait for the sandbox to
48
+ * finish it (scripts may adjust field values before printing). */
49
+ dispatchWillPrint: () => Promise<void>;
50
+ /** Fire the document's `DidPrint` action. */
51
+ dispatchDidPrint: () => Promise<void>;
47
52
  /** Bind a document to the sandbox. Safe to call repeatedly — pass
48
53
  * null to detach (e.g. before swapping documents). */
49
54
  setDocument: (pdfDoc: PDFDocumentProxy | null) => Promise<void>;
@@ -104,6 +104,12 @@ export async function createScriptingManager(deps) {
104
104
  notifyPageRendered(pageNumber) {
105
105
  eventBus.dispatch("pagerendered", { source: window, pageNumber });
106
106
  },
107
+ async dispatchWillPrint() {
108
+ await manager.dispatchWillPrint();
109
+ },
110
+ async dispatchDidPrint() {
111
+ await manager.dispatchDidPrint();
112
+ },
107
113
  async setDocument(pdfDoc) {
108
114
  await manager.setDocument(pdfDoc);
109
115
  },
@@ -54,6 +54,7 @@ export interface ViewerState {
54
54
  setStylusMode: (enabled: boolean) => void;
55
55
  scrollToPage: (pageNumber: number) => void;
56
56
  downloadPdf: () => Promise<void>;
57
+ printPdf: () => Promise<void>;
57
58
  history: AnnotationHistory;
58
59
  readonly: Ref<boolean>;
59
60
  shapeDetection: Ref<boolean>;
@@ -66,6 +67,7 @@ export interface ViewerStateProvider {
66
67
  state: ViewerState;
67
68
  setScrollToPageFn: (fn: (pageNumber: number) => void) => void;
68
69
  setDownloadPdfFn: (fn: () => Promise<void>) => void;
70
+ setPrintPdfFn: (fn: () => Promise<void>) => void;
69
71
  /** Register how custom-scale changes are applied. The Viewer registers a
70
72
  * position-preserving commit (zoom about the viewport centre); without
71
73
  * one, setScale falls back to a plain scale write. */
@@ -152,12 +152,16 @@ export function provideViewerState() {
152
152
  }
153
153
  let _scrollToPageFn = null;
154
154
  let _downloadPdfFn = null;
155
+ let _printPdfFn = null;
155
156
  function scrollToPage(pageNumber) {
156
157
  _scrollToPageFn?.(pageNumber);
157
158
  }
158
159
  async function downloadPdf() {
159
160
  await _downloadPdfFn?.();
160
161
  }
162
+ async function printPdf() {
163
+ await _printPdfFn?.();
164
+ }
161
165
  const history = createAnnotationHistory(annotations, painter);
162
166
  const state = {
163
167
  scale,
@@ -200,6 +204,7 @@ export function provideViewerState() {
200
204
  setStylusMode,
201
205
  scrollToPage,
202
206
  downloadPdf,
207
+ printPdf,
203
208
  history,
204
209
  readonly,
205
210
  shapeDetection: shapeDetectionEnabled,
@@ -217,6 +222,9 @@ export function provideViewerState() {
217
222
  setDownloadPdfFn(fn) {
218
223
  _downloadPdfFn = fn;
219
224
  },
225
+ setPrintPdfFn(fn) {
226
+ _printPdfFn = fn;
227
+ },
220
228
  setApplyScaleFn(fn) {
221
229
  _applyScaleFn = fn;
222
230
  }
@@ -44,6 +44,10 @@ export declare class KViewerEmbedClient {
44
44
  skipped: number;
45
45
  }>;
46
46
  exportPdf(options?: ExportPdfOptions): Promise<Uint8Array>;
47
+ /** Open the viewer's print dialog on the exported (vector) PDF —
48
+ * annotations and form values included, at full print quality.
49
+ * Resolves once the dialog is up, not when printing finishes. */
50
+ printPdf(options?: Omit<ExportPdfOptions, 'download' | 'fileName'>): Promise<void>;
47
51
  getFormFieldValues(): Promise<FormFieldValue[]>;
48
52
  setFormFieldValue(fieldName: string, value: string | boolean | string[]): Promise<void>;
49
53
  addFormField(payload: AddFormFieldPayload): Promise<FormFieldDefinition>;
@@ -60,6 +60,12 @@ export class KViewerEmbedClient {
60
60
  exportPdf(options) {
61
61
  return this.call("exportPdf", options);
62
62
  }
63
+ /** Open the viewer's print dialog on the exported (vector) PDF —
64
+ * annotations and form values included, at full print quality.
65
+ * Resolves once the dialog is up, not when printing finishes. */
66
+ printPdf(options) {
67
+ return this.call("printPdf", options);
68
+ }
63
69
  getFormFieldValues() {
64
70
  return this.call("getFormFieldValues");
65
71
  }
@@ -17,6 +17,7 @@ export interface KViewerApi {
17
17
  skipped: number;
18
18
  }>;
19
19
  exportPdf: (options?: ExportPdfOptions) => Promise<Uint8Array>;
20
+ printPdf: (options?: ExportPdfOptions) => Promise<void>;
20
21
  getFormFieldValues: () => FormFieldValue[];
21
22
  setFormFieldValue: (fieldName: string, value: string | boolean | string[]) => void;
22
23
  addFormField: (payload: AddFormFieldPayload) => FormFieldDefinition;
@@ -39,6 +40,14 @@ export interface KViewerApi {
39
40
  getViewedPages: () => number[];
40
41
  resetViewedPages: () => void;
41
42
  }
43
+ /**
44
+ * What the bridge actually requires of a host. Every capability is
45
+ * optional so an embedding application can hand over an adapter exposing
46
+ * only the parts it uses — a real `<KViewer>` ref satisfies this too.
47
+ * Unimplemented methods surface as an `UNSUPPORTED_METHOD_ERROR_NAME`
48
+ * response instead of breaking initialization.
49
+ */
50
+ export type KViewerHostApi = Partial<KViewerApi>;
42
51
  export interface KViewerEmbedBridgeOptions {
43
52
  /**
44
53
  * Origin of the parent window that hosts this iframe. Used both as
@@ -67,5 +76,5 @@ interface BridgeHandle {
67
76
  /** Manually tear down listeners. Called automatically on scope dispose. */
68
77
  unmount: () => void;
69
78
  }
70
- export declare function useKViewerEmbedBridge(viewerRef: Ref<KViewerApi | null | undefined>, options: KViewerEmbedBridgeOptions): BridgeHandle;
79
+ export declare function useKViewerEmbedBridge(viewerRef: Ref<KViewerHostApi | null | undefined>, options: KViewerEmbedBridgeOptions): BridgeHandle;
71
80
  export type { MethodName };
@@ -3,8 +3,42 @@ import {
3
3
  EVENT_KIND,
4
4
  KVIEWER_EMBED_PROTOCOL_VERSION,
5
5
  RESPONSE_KIND,
6
+ UNSUPPORTED_METHOD_ERROR_NAME,
6
7
  isRequest
7
8
  } from "./protocol.js";
9
+ const METHOD_REQUIREMENT = {
10
+ getAnnotations: "getAnnotations",
11
+ importAnnotations: "importAnnotations",
12
+ exportPdf: "exportPdf",
13
+ printPdf: "printPdf",
14
+ getFormFieldValues: "getFormFieldValues",
15
+ setFormFieldValue: "setFormFieldValue",
16
+ addFormField: "addFormField",
17
+ updateFormField: "updateFormField",
18
+ removeFormField: "removeFormField",
19
+ getFormFields: "getFormFields",
20
+ setFieldDefaults: "setFieldDefaults",
21
+ setClickToSign: "setClickToSign",
22
+ getSignedStatus: "getSignedStatus",
23
+ getSignatureFieldStatus: "getSignatureFieldStatus",
24
+ getFormEditMode: "formEditMode",
25
+ setFormEditMode: "setFormEditMode",
26
+ toggleFormEditMode: "toggleFormEditMode",
27
+ allPagesRead: "allPagesRead",
28
+ getViewedPages: "getViewedPages",
29
+ resetViewedPages: "resetViewedPages"
30
+ };
31
+ const ALL_METHODS = Object.keys(METHOD_REQUIREMENT);
32
+ function supportsMethod(viewer, method) {
33
+ const member = METHOD_REQUIREMENT[method];
34
+ if (!member) return false;
35
+ return member === "formEditMode" ? viewer.formEditMode !== void 0 : typeof viewer[member] === "function";
36
+ }
37
+ function unsupportedMethodError(method) {
38
+ const err = new Error(`KViewer embed host does not implement "${method}"`);
39
+ err.name = UNSUPPORTED_METHOD_ERROR_NAME;
40
+ return err;
41
+ }
8
42
  export function useKViewerEmbedBridge(viewerRef, options) {
9
43
  const allowAny = options.parentOrigin === "*";
10
44
  const winMaybe = options.windowRef ?? (typeof window !== "undefined" ? window : void 0);
@@ -28,10 +62,17 @@ export function useKViewerEmbedBridge(viewerRef, options) {
28
62
  parent.postMessage(message, options.parentOrigin);
29
63
  }
30
64
  async function dispatch(req) {
31
- const viewer = viewerRef.value;
32
- if (!viewer) {
65
+ const host = viewerRef.value;
66
+ if (!host) {
33
67
  throw new Error("KViewer ref is not yet available");
34
68
  }
69
+ if (!(req.method in METHOD_REQUIREMENT)) {
70
+ throw new Error(`Unknown KViewer embed method: ${req.method}`);
71
+ }
72
+ if (!supportsMethod(host, req.method)) {
73
+ throw unsupportedMethodError(req.method);
74
+ }
75
+ const viewer = host;
35
76
  switch (req.method) {
36
77
  case "getAnnotations":
37
78
  return viewer.getAnnotations();
@@ -43,6 +84,11 @@ export function useKViewerEmbedBridge(viewerRef, options) {
43
84
  const [opts] = req.args;
44
85
  return viewer.exportPdf(opts);
45
86
  }
87
+ case "printPdf": {
88
+ const [opts] = req.args;
89
+ await viewer.printPdf(opts);
90
+ return void 0;
91
+ }
46
92
  case "getFormFieldValues":
47
93
  return viewer.getFormFieldValues();
48
94
  case "setFormFieldValue": {
@@ -138,32 +184,60 @@ export function useKViewerEmbedBridge(viewerRef, options) {
138
184
  for (const stop of stopViewerStateWatches) stop();
139
185
  stopViewerStateWatches = [];
140
186
  if (!viewer) return;
141
- postEvent("ready", { protocolVersion: KVIEWER_EMBED_PROTOCOL_VERSION });
142
- stopViewerStateWatches.push(
143
- watch(
144
- () => unref(viewer.formEditMode),
145
- (enabled) => postEvent("formEditMode-changed", { enabled })
146
- ),
147
- viewer.onFieldPlaced(
148
- (field) => postEvent("field-placed", { field })
149
- ),
150
- viewer.onSignedStatusChanged(
151
- (payload) => postEvent("signedStatus-changed", payload)
152
- ),
153
- // Read-tracking. The getters touch the viewer's reactive viewed-pages
154
- // state, so watch re-runs them whenever a page is viewed or tracking
155
- // is reset.
156
- watch(
157
- () => viewer.allPagesRead(),
158
- (read, prev) => {
159
- if (read && !prev) postEvent("all-pages-read", {});
160
- }
161
- ),
162
- watch(
163
- () => viewer.getViewedPages(),
164
- (pages) => postEvent("viewedPages-changed", { pages, allRead: viewer.allPagesRead() })
165
- )
166
- );
187
+ const events = ["ready"];
188
+ if (viewer.formEditMode !== void 0) {
189
+ events.push("formEditMode-changed");
190
+ stopViewerStateWatches.push(
191
+ watch(
192
+ () => unref(viewer.formEditMode),
193
+ (enabled) => postEvent("formEditMode-changed", { enabled: enabled ?? false })
194
+ )
195
+ );
196
+ }
197
+ if (typeof viewer.onFieldPlaced === "function") {
198
+ events.push("field-placed");
199
+ stopViewerStateWatches.push(
200
+ viewer.onFieldPlaced(
201
+ (field) => postEvent("field-placed", { field })
202
+ )
203
+ );
204
+ }
205
+ if (typeof viewer.onSignedStatusChanged === "function") {
206
+ events.push("signedStatus-changed");
207
+ stopViewerStateWatches.push(
208
+ viewer.onSignedStatusChanged(
209
+ (payload) => postEvent("signedStatus-changed", payload)
210
+ )
211
+ );
212
+ }
213
+ if (typeof viewer.allPagesRead === "function") {
214
+ events.push("all-pages-read");
215
+ stopViewerStateWatches.push(
216
+ watch(
217
+ () => viewer.allPagesRead?.() ?? false,
218
+ (read, prev) => {
219
+ if (read && !prev) postEvent("all-pages-read", {});
220
+ }
221
+ )
222
+ );
223
+ }
224
+ if (typeof viewer.getViewedPages === "function") {
225
+ events.push("viewedPages-changed");
226
+ stopViewerStateWatches.push(
227
+ watch(
228
+ () => viewer.getViewedPages?.() ?? [],
229
+ (pages) => postEvent("viewedPages-changed", {
230
+ pages,
231
+ allRead: viewer.allPagesRead?.() ?? false
232
+ })
233
+ )
234
+ );
235
+ }
236
+ postEvent("ready", {
237
+ protocolVersion: KVIEWER_EMBED_PROTOCOL_VERSION,
238
+ methods: ALL_METHODS.filter((method) => supportsMethod(viewer, method)),
239
+ events
240
+ });
167
241
  },
168
242
  { immediate: true }
169
243
  );
@@ -4,6 +4,12 @@ export declare const KVIEWER_EMBED_PROTOCOL_VERSION = 1;
4
4
  export declare const REQUEST_KIND: "kviewer:request";
5
5
  export declare const RESPONSE_KIND: "kviewer:response";
6
6
  export declare const EVENT_KIND: "kviewer:event";
7
+ /**
8
+ * `error.name` on a response rejected because the embedding host's viewer
9
+ * adapter does not implement the requested method. Lets a parent tell a
10
+ * missing capability apart from a genuine failure inside the viewer.
11
+ */
12
+ export declare const UNSUPPORTED_METHOD_ERROR_NAME = "KViewerUnsupportedMethodError";
7
13
  export type ImportAnnotationsMode = 'replace' | 'merge';
8
14
  export interface MethodSignatures {
9
15
  getAnnotations: {
@@ -23,6 +29,10 @@ export interface MethodSignatures {
23
29
  args: [options?: ExportPdfOptions];
24
30
  result: Uint8Array;
25
31
  };
32
+ printPdf: {
33
+ args: [options?: Omit<ExportPdfOptions, 'download' | 'fileName'>];
34
+ result: undefined;
35
+ };
26
36
  getFormFieldValues: {
27
37
  args: [];
28
38
  result: FormFieldValue[];
@@ -115,6 +125,13 @@ export type ResponseMessage<M extends MethodName = MethodName> = {
115
125
  export interface EventPayloads {
116
126
  ready: {
117
127
  protocolVersion: number;
128
+ /** Methods the host's viewer adapter implements. Absent on hosts
129
+ * predating capability discovery, where the full API was mandatory —
130
+ * treat `undefined` as "assume everything". */
131
+ methods?: MethodName[];
132
+ /** Events the host actually subscribed to. Same `undefined` caveat as
133
+ * `methods`. */
134
+ events?: EventName[];
118
135
  };
119
136
  'formEditMode-changed': {
120
137
  enabled: boolean;
@@ -2,6 +2,7 @@ export const KVIEWER_EMBED_PROTOCOL_VERSION = 1;
2
2
  export const REQUEST_KIND = "kviewer:request";
3
3
  export const RESPONSE_KIND = "kviewer:response";
4
4
  export const EVENT_KIND = "kviewer:event";
5
+ export const UNSUPPORTED_METHOD_ERROR_NAME = "KViewerUnsupportedMethodError";
5
6
  export function isRequest(msg) {
6
7
  return !!msg && typeof msg === "object" && msg.kind === REQUEST_KIND && msg.v === KVIEWER_EMBED_PROTOCOL_VERSION;
7
8
  }
@@ -15,6 +15,7 @@ export declare const messages: {
15
15
  readonly clear: "Clear";
16
16
  readonly delete: "Delete";
17
17
  readonly download: "Download";
18
+ readonly print: "Print";
18
19
  readonly search: "Search";
19
20
  readonly marqueeSelect: "Marquee select";
20
21
  readonly eraser: "Eraser";
@@ -141,6 +142,7 @@ export declare const messages: {
141
142
  readonly clear: "Leeren";
142
143
  readonly delete: "Löschen";
143
144
  readonly download: "Herunterladen";
145
+ readonly print: "Drucken";
144
146
  readonly search: "Suchen";
145
147
  readonly marqueeSelect: "Mehrfachauswahl";
146
148
  readonly eraser: "Radierer";
@@ -7,6 +7,7 @@ export const messages = {
7
7
  clear: "Clear",
8
8
  delete: "Delete",
9
9
  download: "Download",
10
+ print: "Print",
10
11
  // Toolbar
11
12
  search: "Search",
12
13
  marqueeSelect: "Marquee select",
@@ -140,6 +141,7 @@ export const messages = {
140
141
  clear: "Leeren",
141
142
  delete: "L\xF6schen",
142
143
  download: "Herunterladen",
144
+ print: "Drucken",
143
145
  search: "Suchen",
144
146
  marqueeSelect: "Mehrfachauswahl",
145
147
  eraser: "Radierer",
@@ -3,11 +3,11 @@ export type { ViewerTabItem, AddTabOptions } from './components/ViewerTabs.vue.j
3
3
  export type { AddFormFieldPayload, CheckboxStyle, FormFieldDefinition, FormFieldOrigin, FormFieldType, FormFieldValue, PlacedFieldDefaultProps, PlacedFieldDefaults, SignatureData, SignatureFieldStatus, SignatureHandlers, } from './annotation/engine/types.js';
4
4
  export type { ViewMode } from './composables/viewMode.js';
5
5
  export type { ViewerState, ActiveTool } from './composables/useViewerState.js';
6
- export type { KViewerApi, KViewerEmbedBridgeOptions, } from './embed/bridge-host.js';
6
+ export type { KViewerApi, KViewerHostApi, KViewerEmbedBridgeOptions, } from './embed/bridge-host.js';
7
7
  export { useKViewerEmbedBridge } from './embed/bridge-host.js';
8
8
  export type { KViewerEmbedClientOptions } from './embed/bridge-client.js';
9
9
  export { KViewerEmbedClient } from './embed/bridge-client.js';
10
10
  export type { EventName as KViewerEmbedEventName, EventPayloads as KViewerEmbedEventPayloads, MethodName as KViewerEmbedMethodName, } from './embed/protocol.js';
11
- export { KVIEWER_EMBED_PROTOCOL_VERSION } from './embed/protocol.js';
11
+ export { KVIEWER_EMBED_PROTOCOL_VERSION, UNSUPPORTED_METHOD_ERROR_NAME as KVIEWER_EMBED_UNSUPPORTED_METHOD_ERROR_NAME, } from './embed/protocol.js';
12
12
  export type { ViewerMenuItem, ViewerMenuButtonItem, ViewerMenuCheckboxItem, ViewerMenuSeparatorItem, } from './menu-items.js';
13
13
  export type { ViewerToolId, ViewerTopToolId, ViewerBottomToolId, ViewerLayoutToolId, ViewerToolEntry, ViewerToolSlot, } from './toolbar-tools.js';
@@ -1,3 +1,6 @@
1
1
  export { useKViewerEmbedBridge } from "./embed/bridge-host.js";
2
2
  export { KViewerEmbedClient } from "./embed/bridge-client.js";
3
- export { KVIEWER_EMBED_PROTOCOL_VERSION } from "./embed/protocol.js";
3
+ export {
4
+ KVIEWER_EMBED_PROTOCOL_VERSION,
5
+ UNSUPPORTED_METHOD_ERROR_NAME as KVIEWER_EMBED_UNSUPPORTED_METHOD_ERROR_NAME
6
+ } from "./embed/protocol.js";
package/dist/types.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- export { type ActiveTool, type AddFormFieldPayload, type CheckboxStyle, type ExportPdfOptions, type FormFieldDefinition, type FormFieldOrigin, type FormFieldType, type FormFieldValue, type KVIEWER_EMBED_PROTOCOL_VERSION, type KViewerApi, type KViewerEmbedBridgeOptions, type KViewerEmbedClient, type KViewerEmbedClientOptions, type KViewerEmbedEventName, type KViewerEmbedEventPayloads, type KViewerEmbedMethodName, type PlacedFieldDefaults, type SignatureData, type SignatureFieldStatus, type SignatureHandlers, type ViewMode, type ViewerBottomToolId, type ViewerLayoutToolId, type ViewerMenuButtonItem, type ViewerMenuCheckboxItem, type ViewerMenuItem, type ViewerMenuSeparatorItem, type ViewerState, type ViewerToolEntry, type ViewerToolId, type ViewerToolSlot, type ViewerTopToolId, type useKViewerEmbedBridge } from '../dist/runtime/public-types.js'
1
+ export { type ActiveTool, type AddFormFieldPayload, type CheckboxStyle, type ExportPdfOptions, type FormFieldDefinition, type FormFieldOrigin, type FormFieldType, type FormFieldValue, type KVIEWER_EMBED_PROTOCOL_VERSION, type KVIEWER_EMBED_UNSUPPORTED_METHOD_ERROR_NAME, type KViewerApi, type KViewerEmbedBridgeOptions, type KViewerEmbedClient, type KViewerEmbedClientOptions, type KViewerEmbedEventName, type KViewerEmbedEventPayloads, type KViewerEmbedMethodName, type KViewerHostApi, type PlacedFieldDefaults, type SignatureData, type SignatureFieldStatus, type SignatureHandlers, type ViewMode, type ViewerBottomToolId, type ViewerLayoutToolId, type ViewerMenuButtonItem, type ViewerMenuCheckboxItem, type ViewerMenuItem, type ViewerMenuSeparatorItem, type ViewerState, type ViewerToolEntry, type ViewerToolId, type ViewerToolSlot, type ViewerTopToolId, type useKViewerEmbedBridge } from '../dist/runtime/public-types.js'
2
2
 
3
3
  export { default } from './module.mjs'
4
4
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kviewer",
3
- "version": "0.3.2",
3
+ "version": "0.3.3",
4
4
  "description": "Kabema PDF Editor",
5
5
  "repository": "kabema/kviewer",
6
6
  "license": "MIT",