### Install vue-pdf-embed with yarn Source: https://github.com/hrynko/vue-pdf-embed/blob/main/README.md Install the package using yarn, an alternative package manager. ```shell yarn add vue-pdf-embed ``` -------------------------------- ### Install vue-pdf-embed with npm Source: https://github.com/hrynko/vue-pdf-embed/blob/main/README.md Install the package using npm. This is the standard installation method for Node.js projects. ```shell npm install vue-pdf-embed ``` -------------------------------- ### Import usePdfSearch from vue-pdf-embed Source: https://github.com/hrynko/vue-pdf-embed/blob/main/_autodocs/api-reference/use-pdf-search.md Import the composable from the main package or the essential build. Use either import path depending on your bundle setup. ```ts import { usePdfSearch } from 'vue-pdf-embed' // or import { usePdfSearch } from 'vue-pdf-embed/dist/index.essential.mjs' ``` -------------------------------- ### usePdfSearch return object Source: https://github.com/hrynko/vue-pdf-embed/blob/main/_autodocs/api-reference/use-pdf-search.md Returns reactive refs and methods for search state and navigation. currentMatch starts at 0, currentMatchPage at 1, matchCount at 0. ```ts { clear: () => void, currentMatch: Ref, // starts at 0 currentMatchPage: Ref, // starts at 1 find: (newQuery: string, options?: SearchOptions) => void, findController: PDFFindController, matchCount: Ref, // starts at 0 next: () => void, previous: () => void, } ``` -------------------------------- ### Import VuePdfEmbed (main and essential builds) Source: https://github.com/hrynko/vue-pdf-embed/blob/main/_autodocs/api-reference/vue-pdf-embed.md Shows how to import the component from the main build (auto-bundled worker) or the essential build (manual worker configuration). ```ts import VuePdfEmbed from 'vue-pdf-embed' // or import VuePdfEmbed from 'vue-pdf-embed/dist/index.essential.mjs' ``` -------------------------------- ### Basic usage with full features (Vue SFC) Source: https://github.com/hrynko/vue-pdf-embed/blob/main/_autodocs/api-reference/vue-pdf-embed.md Imports VuePdfEmbed and optional CSS for text/annotation layers. Sets source, width, scale, page range, and event handler for loading failures. ```vue ``` -------------------------------- ### Basic load and download with usePdfDocument Source: https://github.com/hrynko/vue-pdf-embed/blob/main/_autodocs/api-reference/use-pdf-document.md Loads a PDF from a URL and downloads it. Logs the PDFDocumentProxy once loaded. ```ts import { usePdfDocument } from 'vue-pdf-embed' const { doc, download } = usePdfDocument({ source: 'https://example.com/document.pdf', }) console.log(doc.value) // PDFDocumentProxy once loaded await download('document.pdf') ``` -------------------------------- ### Basic usage of vue-pdf-embed component Source: https://github.com/hrynko/vue-pdf-embed/blob/main/README.md Shows how to import the component, optionally include annotation and text layer styles, and use the component in a template with the source prop. The source can be a URL, Base64, binary, or a document proxy. ```Vue ``` -------------------------------- ### VuePdfEmbed props declaration (withDefaults) Source: https://github.com/hrynko/vue-pdf-embed/blob/main/_autodocs/api-reference/vue-pdf-embed.md Exact prop declaration from the source file, showing all optional props and defaults. ```ts const props = withDefaults( defineProps<{ annotationLayer?: boolean findController?: PDFFindController forms?: boolean height?: number id?: string imageResourcesPath?: string linkService?: PDFLinkService matchScrolling?: boolean page?: number | number[] rotation?: number scale?: number source: Source textLayer?: boolean width?: number }>(), { matchScrolling: true, rotation: 0, scale: 1, } ) ``` -------------------------------- ### defineExpose with doc, download, and print Source: https://github.com/hrynko/vue-pdf-embed/blob/main/_autodocs/api-reference/vue-pdf-embed.md Exposes the component's public API surface: the doc ref, download method, and a print wrapper that maps allPages to undefined page number. The print method's default dpi is 300 and allPages defaults to false. ```ts defineExpose({ doc, download, print: (dpi?: number, filename?: string, allPages = false) => print(dpi, filename, allPages ? undefined : props.page), }) ``` -------------------------------- ### Import textLayer and annotationLayer styles Source: https://github.com/hrynko/vue-pdf-embed/blob/main/_autodocs/api-reference/entry-points.md Import the generated CSS files from the package's dist/styles/ directory to ensure correct text and annotation layer appearance in the app. ```ts import 'vue-pdf-embed/dist/styles/textLayer.css' import 'vue-pdf-embed/dist/styles/annotationLayer.css' ``` -------------------------------- ### Essential entry point (src/index.essential.ts) Source: https://github.com/hrynko/vue-pdf-embed/blob/main/_autodocs/api-reference/entry-points.md Exports the essential public API for the package: GlobalWorkerOptions, composables, and the default VuePdfEmbed component. This build leaves pdfjs-dist external, so the worker is not bundled and GlobalWorkerOptions.workerSrc must be configured explicitly by consumers. ```TypeScript export { GlobalWorkerOptions } from 'pdfjs-dist/legacy/build/pdf.mjs' export { usePdfDocument, usePdfSearch, useVuePdfEmbed } from './composables' export { default } from './VuePdfEmbed.vue' ``` -------------------------------- ### progress Source: https://github.com/hrynko/vue-pdf-embed/blob/main/_autodocs/api-reference/vue-pdf-embed.md Emitted with byte-wise loading progress notifications. ```APIDOC ## Event: progress ### Description Emitted with byte-wise loading progress notifications. ### Payload - **value** (OnProgressParameters) - An object containing `{ loaded, total, percent }`. ### Trigger Byte-wise loading progress notifications. ``` -------------------------------- ### find method implementation Source: https://github.com/hrynko/vue-pdf-embed/blob/main/_autodocs/api-reference/use-pdf-search.md Sets the search query and options, then dispatches a 'find' event. The PDFFindController listener performs the actual search. ```typescript const find = (newQuery: string, options: SearchOptions = {}) => { query.value = newQuery activeOptions = { ...defaultOptions, ...options } dispatch('') } ``` -------------------------------- ### find(newQuery: string, options?: SearchOptions) Source: https://github.com/hrynko/vue-pdf-embed/blob/main/_autodocs/api-reference/use-pdf-search.md Initiates a search for the given query string with optional behavior flags. Dispatches a find event on the internal EventBus, which the PDFFindController listens for to perform the search. ```APIDOC ## find(newQuery: string, options?: SearchOptions) ### Description Initiates a search for the given query string with optional behavior flags. Dispatches a find event on the internal EventBus, which the PDFFindController listens for to perform the search. ### Method find ### Parameters - **newQuery** (string) - Required - The search text. - **options** (SearchOptions) - Optional - Search behavior flags. Defaults to `{}` (all defaults above). ### Request Example ```ts find('example', { caseSensitive: true }) ``` ### Response No direct return value. The search results are reflected in the reactive refs `currentMatch`, `currentMatchPage`, and `matchCount`. ``` -------------------------------- ### usePdfDocument return object Source: https://github.com/hrynko/vue-pdf-embed/blob/main/_autodocs/api-reference/use-pdf-document.md The composable returns an object with doc (a ShallowRef to the PDFDocumentProxy or null), a download helper, and a print helper with configurable DPI, filename, and page number. ```ts { doc: ShallowRef, download: (filename?: string) => Promise, print: async (dpi = 300, filename = '', pageNumber?: number | number[]) => Promise } ``` -------------------------------- ### Load Document with usePdfDocument and Pass via source Prop Source: https://github.com/hrynko/vue-pdf-embed/blob/main/README.md Optimize document loading by using the usePdfDocument composable and passing the resulting doc to the source prop. Useful when sharing the source between multiple component instances. ```vue ``` -------------------------------- ### print(dpi?, filename?, allPages?) Source: https://github.com/hrynko/vue-pdf-embed/blob/main/_autodocs/api-reference/vue-pdf-embed.md Prints the document. By default prints only the currently displayed page; set allPages to true to print every page. ```APIDOC ## Method: print ### Description Component-level wrapper around the composable's `print`. Prints the document, optionally all pages. ### Signature ```ts print(dpi?: number, filename?: string, allPages = false): Promise ``` ### Parameters - **dpi** (number, optional, default: 300) - Print resolution; used to scale page canvases (`printUnits = dpi / 72`). - **filename** (string, optional) - Temporarily sets the window title so the browser print dialog suggests this name. - **allPages** (boolean, optional, default: `false`) - If `false` (default), prints only the pages currently displayed via the `page` prop; if `true`, prints every page of the document. ### Returns `Promise` - Resolves when the print job completes. ### Example ```ts // Print current page at default DPI await pdfEmbedRef.value.print() // Print all pages at 150 DPI with a custom title await pdfEmbedRef.value.print(150, 'My Document', true) ``` ``` -------------------------------- ### Import usePdfDocument from vue-pdf-embed Source: https://github.com/hrynko/vue-pdf-embed/blob/main/_autodocs/api-reference/use-pdf-document.md Shows the three supported import paths for usePdfDocument: the main package, the essential build, and the internal source path. All provide the same code. ```ts import { usePdfDocument } from 'vue-pdf-embed' // or import { usePdfDocument } from 'vue-pdf-embed/dist/index.essential.mjs' // or (internal path, same code) import { usePdfDocument } from 'vue-pdf-embed/src/composables' ``` -------------------------------- ### usePdfDocument Source: https://github.com/hrynko/vue-pdf-embed/blob/main/_autodocs/api-reference/use-pdf-document.md Documentation for the usePdfDocument composable, including its parameters, return value, and source normalization behavior. ```APIDOC ## usePdfDocument ### Description Loads a PDF document from any supported `Source` form into a `ShallowRef` and provides `download`/`print` helpers. It is the loading engine behind the `VuePdfEmbed` component and can be used standalone. ### Function Signature ```ts export function usePdfDocument({ onError, onPasswordRequest, onProgress, source, }: { onError?: (e: Error) => unknown onPasswordRequest?: (passwordRequestParams: PasswordRequestParams) => unknown onProgress?: (progressParams: OnProgressParameters) => unknown source: ComputedRef | MaybeRef | ShallowRef }) ``` ### Parameters - **source** (`ComputedRef` | `MaybeRef` | `ShallowRef`) - Required - A Vue ref (or plain value) of a `Source`. The loader `watchEffect`s it: changing the ref's value destroys the previous loading task and loads the new document. - **onError** (`(e: Error) => unknown`) - Optional - Called when loading fails. If omitted, the error is **re-thrown**. - **onPasswordRequest** (`(passwordRequestParams: PasswordRequestParams) => unknown`) - Optional - Called with `{ callback, isWrongPassword }` when the PDF requires a password. `callback` must be invoked with the password string. - **onProgress** (`(progressParams: OnProgressParameters) => unknown`) - Optional - Receives `{ loaded, total, percent }` byte counts while the PDF loads. ### Returns Returns an object with three members: ```ts { doc: ShallowRef, download: (filename?: string) => Promise, print: async (dpi = 300, filename = '', pageNumber?: number | number[]) => Promise } ``` ### Source Normalization The `source` value is converted to `DocumentInitParameters` before calling `getDocument` from `pdfjs-dist/legacy/build/pdf.mjs`: | Runtime value | Converted to | | --- | --- | | `string` or `URL` | `{ url: source }` | | `ArrayBuffer`, any `ArrayBufferView` (typed array), or `Array` | `{ data: source }` | | `PDFDocumentProxy` (object with own `_pdfInfo` prop) | used directly, no loading | | any other object | used as `DocumentInitParameters` as-is (may include `cMapUrl`, `wasmUrl`, `password`, `httpHeaders`, ...) | | `null` / `undefined` | nothing loaded; `doc` stays `null` | ### Loading Lifecycle While a load is in flight, `onCleanup` marks it stale, nulls the `onPassword`/`onProgress` handlers and calls `loadingTask.destroy()`. Stale completions/failures are dropped — including not destroying an externally-provided `PDFDocumentProxy`. ``` -------------------------------- ### usePdfDocument Source: https://github.com/hrynko/vue-pdf-embed/blob/main/_autodocs/api-reference/use-pdf-document.md Composable for loading PDF documents, downloading, printing, and handling progress, password, and error events. ```APIDOC ## usePdfDocument ### Description Composable for loading PDF documents, downloading, printing, and handling progress, password, and error events. ### Method usePdfDocument ### Parameters #### Options Object - **source** (string | object) - Required - The PDF source. Can be a URL string or an object with a `url` property. - **onProgress** (function) - Optional - Callback for download progress. Receives an object with `loaded` and `total` properties. - **onPasswordRequest** (function) - Optional - Callback for password-protected documents. Receives an object with `callback` and `isWrongPassword` properties. - **onError** (function) - Optional - Callback for load errors. ### Returns - **doc** (Ref) - The loaded PDF document proxy. - **download** (function) - Downloads the PDF. Accepts an optional filename string. - **print** (function) - Prints the PDF. Accepts optional DPI, page ID, and page number parameters. ### Example ```ts import { usePdfDocument } from 'vue-pdf-embed' const { doc, download, print } = usePdfDocument({ source: 'https://example.com/document.pdf', onProgress: ({ loaded, total }) => console.log(`${loaded}/${total}`), onPasswordRequest({ callback, isWrongPassword }) { const password = prompt(`Password${isWrongPassword ? ' (wrong)' : ''}:`) callback(password) }, onError: (e) => console.error('failed to load', e), }) await download('document.pdf') await print(150, 'page1', 1) ``` ``` -------------------------------- ### Configure PDF.js Web Worker Manually with Essential Build Source: https://github.com/hrynko/vue-pdf-embed/blob/main/README.md Use the essential build and set GlobalWorkerOptions.workerSrc when the default blob URL worker is blocked by CSP. Two options are shown: a bundler URL import or serving the worker from the public directory. ```javascript import VuePdfEmbed, { GlobalWorkerOptions, } from 'vue-pdf-embed/dist/index.essential.mjs' // Option 1: use a bundler URL import import PdfWorker from 'pdfjs-dist/build/pdf.worker.min.mjs?url' GlobalWorkerOptions.workerSrc = PdfWorker // Option 2: serve the worker from your public directory, // copied from pdfjs-dist/build/pdf.worker.min.mjs GlobalWorkerOptions.workerSrc = '/pdf.worker.min.mjs' ``` -------------------------------- ### next and previous method implementations Source: https://github.com/hrynko/vue-pdf-embed/blob/main/_autodocs/api-reference/use-pdf-search.md Re-dispatch the current query with type 'again' and findPrevious false/true respectively, moving to the next or previous match. ```typescript next: () => dispatch('again', false), previous: () => dispatch('again', true), ``` -------------------------------- ### Load vue-pdf-embed via CDN script tag Source: https://github.com/hrynko/vue-pdf-embed/blob/main/README.md Include the component directly in the browser using a script tag from unpkg. This allows usage without a build step. ```html ``` -------------------------------- ### download(filename?) Source: https://github.com/hrynko/vue-pdf-embed/blob/main/_autodocs/api-reference/vue-pdf-embed.md Downloads the document as a PDF file. Saves through saveDocument() when annotation storage holds form values, otherwise uses getData(). ```APIDOC ## Method: download ### Description Downloads the document as a PDF file. Behavior: saves through `saveDocument()` when the annotation storage holds form values, else uses `getData()`; the effective filename is the `filename` argument, falling back to the PDF's `contentDispositionFilename` metadata, else `''`. ### Signature ```ts download(filename?: string): Promise ``` ### Parameters - **filename** (string, optional) - The desired filename for the downloaded file. Falls back to the PDF's `contentDispositionFilename` metadata, then `''`. ### Returns `Promise` - Resolves when the download completes. ### Example ```ts await pdfEmbedRef.value.download('my-document.pdf') ``` ``` -------------------------------- ### usePdfSearch(doc) Source: https://github.com/hrynko/vue-pdf-embed/blob/main/_autodocs/api-reference/use-pdf-search.md Documentation for the usePdfSearch composable function, including its signature, parameters, return value, and search options. ```APIDOC ## usePdfSearch(doc) ### Description Creates a full-text search composable for a loaded PDF document. It creates and owns a `PDFFindController`, dispatches `find` events on a private `EventBus`, and exposes reactive search state. Pass the returned `findController` to the `VuePdfEmbed` component's `find-controller` prop (with the text layer enabled) to highlight matches in place. ### Signature ```ts export function usePdfSearch(doc: MaybeRefOrGetter) ``` ### Parameters - **doc** (`MaybeRefOrGetter`) - Required - The document to search, or a ref/getter resolving to one. A plain `PDFDocumentProxy` works, as does passing the `doc` ref returned by `usePdfDocument`. ### Returns Returns an object with the following properties: - **clear** (`() => void`) - Resets the search state. - **currentMatch** (`Ref`) - Starts at 0. - **currentMatchPage** (`Ref`) - Starts at 1. - **find** (`(newQuery: string, options?: SearchOptions) => void`) - Performs a search with the given query and options. - **findController** (`PDFFindController`) - The underlying find controller. - **matchCount** (`Ref`) - Starts at 0. - **next** (`() => void`) - Moves to the next match. - **previous** (`() => void`) - Moves to the previous match. ### Search Options - **caseSensitive** (`boolean`) - Optional - Default: `false` - Whether the search is case-sensitive. - **entireWord** (`boolean`) - Optional - Default: `false` - Whether to match entire words only. - **highlightAll** (`boolean`) - Optional - Default: `true` - Whether to highlight all matches. - **matchDiacritics** (`boolean`) - Optional - Default: `false` - Whether to match diacritics. ### Usage Example ```ts import { usePdfSearch } from 'vue-pdf-embed' // or import { usePdfSearch } from 'vue-pdf-embed/dist/index.essential.mjs' const { find, next, previous, clear, currentMatch, currentMatchPage, matchCount, findController } = usePdfSearch(doc) ``` ``` -------------------------------- ### clear method implementation Source: https://github.com/hrynko/vue-pdf-embed/blob/main/_autodocs/api-reference/use-pdf-search.md Resets query, options, and match state, then dispatches an empty query to remove highlights. Also called automatically when a new document is set. ```typescript const clear = () => { query.value = '' activeOptions = { ...defaultOptions } currentMatchPage.value = 1 currentMatch.value = 0 matchCount.value = 0 dispatch('') } ``` -------------------------------- ### Main entry src/index.ts Source: https://github.com/hrynko/vue-pdf-embed/blob/main/_autodocs/api-reference/entry-points.md Main entry point for the vue-pdf-embed package. Registers global Vue properties when window.Vue is present and auto-configures the pdf.js worker URL if not already set. Requires a bundler that supports the ?url import suffix. ```ts import { GlobalWorkerOptions } from 'pdfjs-dist/legacy/build/pdf.mjs' import PdfWorker from 'pdfjs-dist/legacy/build/pdf.worker.min.mjs?url' import { usePdfDocument, usePdfSearch, useVuePdfEmbed } from './composables' import VuePdfEmbed from './VuePdfEmbed.vue' if (typeof window !== 'undefined' && window.Vue) { window.VuePdfEmbed = VuePdfEmbed window.usePdfDocument = usePdfDocument window.usePdfSearch = usePdfSearch window.useVuePdfEmbed = useVuePdfEmbed } if (!GlobalWorkerOptions?.workerSrc) { GlobalWorkerOptions.workerSrc = PdfWorker } export { usePdfDocument, usePdfSearch, useVuePdfEmbed } from './composables' export default VuePdfEmbed ``` -------------------------------- ### loading-failed Source: https://github.com/hrynko/vue-pdf-embed/blob/main/_autodocs/api-reference/vue-pdf-embed.md Emitted when the document fails to load. ```APIDOC ## Event: loading-failed ### Description Emitted when the document fails to load. ### Payload - **value** (Error) - The error that occurred during loading. ### Trigger The document failed to load. Page list is cleared first. ``` -------------------------------- ### Error handling, password, progress, and print with usePdfDocument Source: https://github.com/hrynko/vue-pdf-embed/blob/main/_autodocs/api-reference/use-pdf-document.md Handles password-protected PDFs, progress updates, and errors. Prints page 1 at 150 dpi. ```ts import { usePdfDocument } from 'vue-pdf-embed' const { doc, download, print } = usePdfDocument({ source: { url: 'https://example.com/secret.pdf' }, onProgress: ({ loaded, total }) => console.log(`${loaded}/${total}`), onPasswordRequest({ callback, isWrongPassword }) { const password = prompt(`Password${isWrongPassword ? ' (wrong)' : ''}:`) callback(password) // unlocked in place, no reload needed }, onError: (e) => console.error('failed to load', e), }) // print only page 1 at 150 dpi await print(150, 'page1', 1) ``` -------------------------------- ### Set image-resources-path for Annotations Source: https://github.com/hrynko/vue-pdf-embed/blob/main/README.md Specify the image resource path for annotations to display correctly. ```vue ``` -------------------------------- ### findController Source: https://github.com/hrynko/vue-pdf-embed/blob/main/_autodocs/api-reference/use-pdf-search.md The underlying PDFFindController instance created with the internal event bus and an adapter PDFLinkService. Pass it to . ```APIDOC ## findController ### Description The underlying PDFFindController instance created with the internal event bus and an adapter PDFLinkService. Pass it to . ### Type PDFFindController ### Details - The adapter PDFLinkService's `page` property reads/writes `currentMatchPage.value` and its `pagesCount` getter returns `doc.numPages`. - `next`/`previous`/`find` may also be replaced by dispatching directly on `findController._eventBus` (internal property). ``` -------------------------------- ### doc Source: https://github.com/hrynko/vue-pdf-embed/blob/main/_autodocs/api-reference/use-pdf-document.md A shallow ref holding the loaded PDF document proxy, or null before load and after failures. Pass the unwrapped ref to the VuePdfEmbed source prop to share the document. ```APIDOC ## `doc` ### Description A shallow ref holding the loaded PDF document proxy, or `null` before load and after failures. Pass the unwrapped ref to the `VuePdfEmbed` `source` prop to reuse a shared document across component instances. ### Type `ShallowRef` ### Usage ```ts const { doc } = usePdfDocument() // Pass doc.value to VuePdfEmbed's source prop ``` ``` -------------------------------- ### Basic use with input and status display (Vue) Source: https://github.com/hrynko/vue-pdf-embed/blob/main/_autodocs/api-reference/use-pdf-search.md Use this snippet to integrate PDF search in a Vue component. It sets up a search input and navigation buttons, displaying the current match position. The findController is passed to VuePdfEmbed to enable highlighting. ```vue ``` -------------------------------- ### before-page slot Source: https://github.com/hrynko/vue-pdf-embed/blob/main/_autodocs/api-reference/vue-pdf-embed.md Scoped slot that renders content before each page container. Receives the 1-indexed page number as a scoped prop. ```APIDOC ## Slot: before-page ### Description Content inserted before each page container. Rendered once per displayed page. ### Scoped Props - **page** (number) - The 1-indexed page number. ### Usage Example ```vue ``` ``` -------------------------------- ### download method signature Source: https://github.com/hrynko/vue-pdf-embed/blob/main/_autodocs/api-reference/vue-pdf-embed.md Downloads the document as a PDF. Saves via saveDocument() when annotation storage holds form values, otherwise uses getData(). The effective filename falls back to contentDispositionFilename metadata, then an empty string. ```ts download(filename?: string): Promise ``` -------------------------------- ### rendered Source: https://github.com/hrynko/vue-pdf-embed/blob/main/_autodocs/api-reference/vue-pdf-embed.md Emitted when all selected pages finish rendering and the render was not aborted. ```APIDOC ## Event: rendered ### Description Emitted when all selected pages finish rendering and the render was not aborted. ### Payload None. ### Trigger All selected pages finished rendering and the render was not aborted. ``` -------------------------------- ### loaded Source: https://github.com/hrynko/vue-pdf-embed/blob/main/_autodocs/api-reference/vue-pdf-embed.md Emitted when the document finishes loading or when an externally-provided PDFDocumentProxy is assigned to the source. ```APIDOC ## Event: loaded ### Description Emitted when the document finishes loading or when an externally-provided PDFDocumentProxy is assigned to the source. ### Payload - **value** (PDFDocumentProxy) - The loaded PDF document proxy. ### Trigger The document finished loading (or an externally-provided `PDFDocumentProxy` was assigned to `source`). ``` -------------------------------- ### Advanced search with options and clearing (TypeScript) Source: https://github.com/hrynko/vue-pdf-embed/blob/main/_autodocs/api-reference/use-pdf-search.md Use this snippet for programmatic search with non-trivial options. It shows how to perform a case-sensitive, whole-word search, observe the reactive match state, and clear all highlights later. ```ts import { usePdfSearch } from 'vue-pdf-embed' const { find, clear, currentMatch, matchCount } = usePdfSearch(myDoc) // non-trivial options: only highlight whole words, case-sensitively find('PDF', { caseSensitive: true, entireWord: true, highlightAll: false }) // observe the reactive result console.log(`showing ${currentMatch.value} of ${matchCount.value} matches`) // later: drop all highlights clear() ``` -------------------------------- ### Full-Text Search with usePdfSearch and find-controller Prop Source: https://github.com/hrynko/vue-pdf-embed/blob/main/README.md Enable full-text search over a loaded document by passing the findController from usePdfSearch to the :find-controller prop. The text layer must be enabled to highlight matches in place. ```vue ``` -------------------------------- ### print method signature Source: https://github.com/hrynko/vue-pdf-embed/blob/main/_autodocs/api-reference/vue-pdf-embed.md Prints the document. The dpi parameter scales page canvases (printUnits = dpi / 72). When allPages is false (default), only the currently displayed page (via the page prop) is printed; when true, all pages are printed. ```ts print(dpi?: number, filename?: string, allPages = false): Promise ``` -------------------------------- ### doc Source: https://github.com/hrynko/vue-pdf-embed/blob/main/_autodocs/api-reference/vue-pdf-embed.md Public template-ref property exposing a ShallowRef to the loaded PDFDocumentProxy. Read its .value to inspect the document. ```APIDOC ## Property: doc ### Description A `ShallowRef` holding the loaded document proxy, same value emitted by the `loaded` event. ### Type `ShallowRef` ### Access Read the `.value` property of the ref to inspect the document. ### Example ```ts const pdfEmbed = ref() // after mount const doc = pdfEmbed.value.doc.value ``` ``` -------------------------------- ### clear() Source: https://github.com/hrynko/vue-pdf-embed/blob/main/_autodocs/api-reference/use-pdf-search.md Resets the query, active options, and all state refs, then dispatches an empty query to remove highlights. Also invoked automatically when a new document is set. ```APIDOC ## clear() ### Description Resets the query, active options, and all state refs, then dispatches an empty query to remove highlights. Also invoked automatically when a new document is set. ### Method clear ### Parameters None. ### Request Example ```ts clear() ``` ### Response No direct return value. All search state is reset. ``` -------------------------------- ### Configure GlobalWorkerOptions.workerSrc for essential build Source: https://github.com/hrynko/vue-pdf-embed/blob/main/_autodocs/configuration.md Configure the PDF.js worker for the essential build of vue-pdf-embed. The essential build does not bundle the worker, so you must set GlobalWorkerOptions.workerSrc manually. Option 1 uses a bundler-managed URL via the ?url import; Option 2 points to a worker file served from your public directory. Note that the path 'pdfjs-dist/build/pdf.worker.min.mjs' refers to pdfjs-dist 6.x layout; version 3.x/older layouts may differ. ```javascript import VuePdfEmbed, { GlobalWorkerOptions } from 'vue-pdf-embed/dist/index.essential.mjs' // Option 1: bundler-managed worker URL import PdfWorker from 'pdfjs-dist/build/pdf.worker.min.mjs?url' GlobalWorkerOptions.workerSrc = PdfWorker // Option 2: worker served from your public directory GlobalWorkerOptions.workerSrc = '/pdf.worker.min.mjs' ``` -------------------------------- ### Accessing exposed API via template ref (Vue SFC) Source: https://github.com/hrynko/vue-pdf-embed/blob/main/_autodocs/api-reference/vue-pdf-embed.md Uses a template ref to access the component's exposed methods like download and print, and the doc property for page count. Includes error handling via optional chaining. ```vue ``` -------------------------------- ### usePdfSearch function signature Source: https://github.com/hrynko/vue-pdf-embed/blob/main/_autodocs/api-reference/use-pdf-search.md The composable accepts a PDFDocumentProxy or a ref/getter resolving to one. Pass the doc ref from usePdfDocument or a plain proxy. ```ts export function usePdfSearch(doc: MaybeRefOrGetter) ``` -------------------------------- ### usePdfDocument function signature Source: https://github.com/hrynko/vue-pdf-embed/blob/main/_autodocs/api-reference/use-pdf-document.md The composable accepts an options object with source (required) and optional onError, onPasswordRequest, and onProgress callbacks. The source can be a ComputedRef, MaybeRef, or ShallowRef of a Source. ```ts export function usePdfDocument({ onError, onPasswordRequest, onProgress, source, }: { onError?: (e: Error) => unknown onPasswordRequest?: (passwordRequestParams: PasswordRequestParams) => unknown onProgress?: (progressParams: OnProgressParameters) => unknown source: ComputedRef | MaybeRef | ShallowRef }) ``` -------------------------------- ### VuePdfEmbed component with error events Source: https://github.com/hrynko/vue-pdf-embed/blob/main/_autodocs/errors.md Binds the loading-failed, rendering-failed, and password-requested events. Handles PasswordException, ResponseException, and InvalidPDFException from 'pdfjs-dist'. ```Vue ``` -------------------------------- ### useVuePdfEmbed (deprecated) Source: https://github.com/hrynko/vue-pdf-embed/blob/main/_autodocs/api-reference/use-pdf-document.md Deprecated alias for usePdfDocument, kept for backwards compatibility. ```APIDOC ## useVuePdfEmbed (deprecated) ### Description Deprecated alias for usePdfDocument, kept for backwards compatibility. ### Method useVuePdfEmbed ### Parameters None ### Returns Same as usePdfDocument ### Example ```ts import { useVuePdfEmbed } from 'vue-pdf-embed' const { doc, download } = useVuePdfEmbed({ source: 'https://example.com/document.pdf', }) ``` ``` -------------------------------- ### next() / previous() Source: https://github.com/hrynko/vue-pdf-embed/blob/main/_autodocs/api-reference/use-pdf-search.md Re-dispatches the current query with type 'again' and findPrevious set to false (next) or true (previous), moving to the next or previous match, wrapping at document ends. ```APIDOC ## next() / previous() ### Description Re-dispatches the current query with type 'again' and findPrevious set to false (next) or true (previous), moving to the next or previous match, wrapping at document ends. ### Method next / previous ### Parameters None. ### Request Example ```ts next() previous() ``` ### Response No direct return value. The current match position is updated in the reactive refs. ``` -------------------------------- ### Set wasmUrl for JPEG 2000 or JBIG2 Images Source: https://github.com/hrynko/vue-pdf-embed/blob/main/README.md Specify the path to WebAssembly decoders for documents containing JPEG 2000 or JBIG2 images. ```vue ``` -------------------------------- ### internal-link-clicked Source: https://github.com/hrynko/vue-pdf-embed/blob/main/_autodocs/api-reference/vue-pdf-embed.md Emitted when an internal link is clicked, providing the destination page number. ```APIDOC ## Event: internal-link-clicked ### Description Emitted when an internal link is clicked, providing the destination page number. ### Payload - **value** (number) - The destination page number. ### Trigger An internal link was clicked; emitted by the default `PDFLinkService`'s `scrollPageIntoView` viewer hook. Replaced entirely when a custom `linkService` prop is supplied. ``` -------------------------------- ### print function signature Source: https://github.com/hrynko/vue-pdf-embed/blob/main/_autodocs/api-reference/use-pdf-document.md Prints the PDF at the given DPI and optional page range. Creates a hidden iframe, batches rasterization, and injects print styles. Requires the browser print dialog context; no-op when doc.value is null. ```typescript const print = async ( dpi = 300, filename = '', pageNumber?: number | number[] ) => { ... } ``` -------------------------------- ### rendering-failed Source: https://github.com/hrynko/vue-pdf-embed/blob/main/_autodocs/api-reference/vue-pdf-embed.md Emitted when page rendering (canvas, text layer, or annotation layer) fails. ```APIDOC ## Event: rendering-failed ### Description Emitted when page rendering (canvas, text layer, or annotation layer) fails. ### Payload - **value** (Error) - The error that occurred during rendering. ### Trigger Page rendering (canvas, text layer or annotation layer) failed. Page count/scale lists are reset; suppressed for abort/cancellation errors. ``` -------------------------------- ### Deprecated useVuePdfEmbed alias Source: https://github.com/hrynko/vue-pdf-embed/blob/main/_autodocs/api-reference/use-pdf-document.md Deprecated export that re-exports usePdfDocument for backwards compatibility. Use usePdfDocument instead. ```ts /** * @deprecated renamed to {@link usePdfDocument} */ export const useVuePdfEmbed = usePdfDocument ``` -------------------------------- ### password-requested Source: https://github.com/hrynko/vue-pdf-embed/blob/main/_autodocs/api-reference/vue-pdf-embed.md Emitted when a password is required to open the document or when a supplied password is incorrect. ```APIDOC ## Event: password-requested ### Description Emitted when a password is required to open the document or when a supplied password is incorrect. ### Payload - **value** (PasswordRequestParams) - Parameters related to the password request. ### Trigger A password is required to open the document (or a supplied password was wrong). See [errors.md](../errors.md). ``` -------------------------------- ### after-page slot Source: https://github.com/hrynko/vue-pdf-embed/blob/main/_autodocs/api-reference/vue-pdf-embed.md Scoped slot that renders content after each page container. Receives the 1-indexed page number as a scoped prop. ```APIDOC ## Slot: after-page ### Description Content inserted after each page container. Rendered once per displayed page. ### Scoped Props - **page** (number) - The 1-indexed page number. ### Usage Example ```vue ``` ``` -------------------------------- ### download function implementation Source: https://github.com/hrynko/vue-pdf-embed/blob/main/_autodocs/api-reference/use-pdf-document.md Downloads the PDF. If editable form values exist (annotationStorage.size non-zero), it re-serializes via saveDocument(); otherwise fetches raw bytes with getData(). Uses the contentDispositionFilename metadata as default filename. No-op when doc.value is null. ```typescript const download = async (filename?: string) => { if (!doc.value) return const data = doc.value.annotationStorage.size ? await doc.value.saveDocument() : await doc.value.getData() const metadata = await doc.value.getMetadata() const suggestedFilename = filename ?? metadata.contentDispositionFilename ?? '' downloadPdf(data, suggestedFilename) } ``` -------------------------------- ### print Source: https://github.com/hrynko/vue-pdf-embed/blob/main/_autodocs/api-reference/use-pdf-document.md Prints the current PDF document. Optionally specify print resolution, a filename for the print dialog, and specific pages to print. Creates a hidden iframe and rasterizes pages for printing. ```APIDOC ## `print` ### Description Prints the current PDF document. Optionally specify print resolution, a filename for the print dialog, and specific pages to print. Creates a hidden iframe and rasterizes pages for printing. ### Signature ```ts const print = async ( dpi?: number, filename?: string, pageNumber?: number | number[] ) => Promise ``` ### Parameters #### `dpi` (optional) - **Type**: `number` - **Required**: No - **Default**: `300` - **Description**: Print resolution in dots-per-inch. `printUnits = dpi / 72`; page canvases are rendered at `viewport.width * printUnits` with `intent: 'print'` and `AnnotationMode.ENABLE_STORAGE`. #### `filename` (optional) - **Type**: `string` - **Required**: No - **Default**: `''` - **Description**: When non-empty, temporarily replaces `document.title` so the browser's print dialog suggests this name (restored afterwards). #### `pageNumber` (optional) - **Type**: `number` | `number[]` - **Required**: No - **Default**: all pages (`1..numPages`) - **Description**: Pages to print (1-indexed). ### Returns - **Type**: `Promise` - **Description**: Resolves once the hidden print iframe's `print()` was invoked. ### Behavior - Creates a hidden `iframe` (`createPrintIframe`). - Batches page rasterization with `batchSize = Math.max(3, Math.floor(10 * (300 / dpi)))`. - Injects `@page { margin: 3mm; size: pt pt }` print styles (`addPrintStyles`). - Cleans up all generated canvases/containers in a `finally` block. - Requires the browser print dialog context; no-op when `doc.value` is `null`. ``` -------------------------------- ### SearchOptions type for usePdfSearch Source: https://github.com/hrynko/vue-pdf-embed/blob/main/_autodocs/types.md Defines the options object accepted by usePdfSearch(...).find(). All fields are optional; caseSensitive, entireWord, and matchDiacritics default to false, while highlightAll defaults to true. ```ts type SearchOptions = { caseSensitive?: boolean entireWord?: boolean highlightAll?: boolean matchDiacritics?: boolean } ``` -------------------------------- ### download Source: https://github.com/hrynko/vue-pdf-embed/blob/main/_autodocs/api-reference/use-pdf-document.md Downloads the current PDF document. If the document has editable form values, it re-serializes the document; otherwise, it fetches the raw bytes. The file is downloaded using a hidden anchor element. ```APIDOC ## `download` ### Description Downloads the current PDF document. If the document has editable form values (annotationStorage), it re-serializes the document via `saveDocument()`; otherwise, it fetches the raw bytes with `getData()`. The data is written to a Blob and downloaded via a hidden anchor element. ### Signature ```ts const download = async (filename?: string) => Promise ``` ### Parameters #### `filename` (optional) - **Type**: `string` - **Required**: No - **Default**: PDF's `contentDispositionFilename` metadata, else `''` - **Description**: Download file name. ### Returns - **Type**: `Promise` - **Description**: Resolves after the anchor click triggers the browser download. ### Behavior - If `doc.annotationStorage.size` is non-zero, the document is re-serialized via `saveDocument()`; otherwise, raw bytes are fetched with `getData()`. - Data is written to a `Blob(..., { type: 'application/pdf' })` object URL, clicked through a hidden `` element, then revoked after 1 second. - No-op when `doc.value` is `null`. ``` -------------------------------- ### usePdfDocument composable with onError and onPasswordRequest Source: https://github.com/hrynko/vue-pdf-embed/blob/main/_autodocs/errors.md Always pass onError to the composable. Handles PasswordException with INCORRECT_PASSWORD code and provides a password prompt callback. ```TypeScript import { usePdfDocument } from 'vue-pdf-embed' const { doc } = usePdfDocument({ source: url, onError: (e) => { if (e instanceof PasswordException && e.code === PasswordResponses.INCORRECT_PASSWORD) { // retry with another password through onPasswordRequest } }, onPasswordRequest({ callback }) { callback(promptForPassword()) }, }) ``` -------------------------------- ### Source Source: https://github.com/hrynko/vue-pdf-embed/blob/main/_autodocs/types.md The Source type represents the input to the vue-pdf-embed component and usePdfDocument composable. It can be a pdf.js document initialization object, raw data, a URL, an already-loaded PDFDocumentProxy, or null. ```APIDOC ## Source ### Description Represents the source of a PDF document. It can be a pdf.js document initialization object, raw binary data, a URL, an already-loaded PDFDocumentProxy, or null. ### Type `Source` ### Definition ```ts import { getDocument, type PDFDocumentProxy } from 'pdfjs-dist' type DocumentInitParameters = NonNullable[0]> export type Source = | DocumentInitParameters | NonNullable | NonNullable | PDFDocumentProxy | null ``` ### Members - `DocumentInitParameters` - Full pdf.js document initialization object (`url` and `data` both optional; at least one must be present in practice). - `NonNullable` - Raw binary document data (`string | number[] | ArrayBuffer | TypedArray`). A string here means Base64-encoded data. - `NonNullable` - Document URL (`string | URL`). - `PDFDocumentProxy` - Already-loaded document; used as-is without reloading. - `null` - No document; rendering is a no-op. ### Consumers - `` prop - required. - `usePdfDocument({ source })`. - Normalized to `DocumentInitParameters` by `toDocumentInitParams`: string/`URL` → `{ url }`, `ArrayBuffer`/view/`Array` → `{ data }`, proxy → returned directly, other objects → passed through. ``` -------------------------------- ### Password-requested flow in usePdfDocument Source: https://github.com/hrynko/vue-pdf-embed/blob/main/_autodocs/errors.md When a password-protected document is loaded, this callback is invoked with a callback to retry with a new password and a flag indicating whether the previous password was incorrect. If no onPasswordRequest handler is wired, the underlying PasswordException eventually surfaces through the loading error path. ```TypeScript loadingTask.onPassword = (callback, response) => { onPasswordRequest({ callback, isWrongPassword: response === PasswordResponses.INCORRECT_PASSWORD, }) } ```