Component Methods
Complete reference for all ng2-pdfjs-viewer component public methods.
Core Methods
triggerDownload()
- Type:
Promise<ActionExecutionResult> - Description: Triggers PDF download
- Returns: Promise with execution result
async downloadPdf() {
try {
const result = await this.pdfViewer.triggerDownload();
console.log('Download triggered successfully:', result);
} catch (error) {
console.error('Download failed:', error);
}
}
triggerPrint()
- Type:
Promise<ActionExecutionResult> - Description: Triggers PDF print dialog
- Returns: Promise with execution result
async printPdf() {
try {
const result = await this.pdfViewer.triggerPrint();
console.log('Print triggered successfully:', result);
} catch (error) {
console.error('Print failed:', error);
}
}
setPage(page: number)
- Type:
Promise<ActionExecutionResult> - Description: Navigate to specific page
- Parameters:
page- Page number (1-based) - Returns: Promise with execution result
async goToPage(pageNumber: number) {
try {
const result = await this.pdfViewer.setPage(pageNumber);
console.log(`Navigated to page ${pageNumber}:`, result);
} catch (error) {
console.error('Navigation failed:', error);
}
}
goToPage(page: number)
- Type:
Promise<ActionExecutionResult> - Description: Alias for
setPage()for backward compatibility - Parameters:
page- Page number (1-based) - Returns: Promise with execution result
async navigateToPage(pageNumber: number) {
try {
const result = await this.pdfViewer.goToPage(pageNumber);
console.log(`Navigated to page ${pageNumber}:`, result);
} catch (error) {
console.error('Navigation failed:', error);
}
}
setZoom(zoom: string)
- Type:
Promise<ActionExecutionResult> - Description: Set zoom level
- Parameters:
zoom- Zoom level ('auto', 'page-width', 'page-height', 'page-fit', 'actual', or percentage like '150%') - Returns: Promise with execution result
async changeZoom(zoomLevel: string) {
try {
const result = await this.pdfViewer.setZoom(zoomLevel);
console.log(`Zoom changed to ${zoomLevel}:`, result);
} catch (error) {
console.error('Zoom change failed:', error);
}
}
goToLastPage()
- Type:
Promise<ActionExecutionResult> - Description: Navigate to the last page
- Returns: Promise with execution result
async goToEnd() {
try {
const result = await this.pdfViewer.goToLastPage();
console.log('Navigated to last page:', result);
} catch (error) {
console.error('Navigation to last page failed:', error);
}
}
setCursor(cursor: string)
- Type:
Promise<ActionExecutionResult> - Description: Set cursor mode
- Parameters:
cursor- Cursor mode ('grab', 'grabbing', 'text', 'crosshair', etc.) - Returns: Promise with execution result
async changeCursor(cursorMode: string) {
try {
const result = await this.pdfViewer.setCursor(cursorMode);
console.log(`Cursor changed to ${cursorMode}:`, result);
} catch (error) {
console.error('Cursor change failed:', error);
}
}
setScroll(scroll: string)
- Type:
Promise<ActionExecutionResult> - Description: Set scroll mode
- Parameters:
scroll- Scroll mode ('vertical', 'horizontal', 'wrapped', 'page') - Returns: Promise with execution result
async changeScroll(scrollMode: string) {
try {
const result = await this.pdfViewer.setScroll(scrollMode);
console.log(`Scroll changed to ${scrollMode}:`, result);
} catch (error) {
console.error('Scroll change failed:', error);
}
}
setSpread(spread: string)
- Type:
Promise<ActionExecutionResult> - Description: Set spread mode
- Parameters:
spread- Spread mode ('none', 'odd', 'even') - Returns: Promise with execution result
async changeSpread(spreadMode: string) {
try {
const result = await this.pdfViewer.setSpread(spreadMode);
console.log(`Spread changed to ${spreadMode}:`, result);
} catch (error) {
console.error('Spread change failed:', error);
}
}
triggerRotation(direction: 'cw' | 'ccw')
- Type:
Promise<ActionExecutionResult> - Description: Rotate the document
- Parameters:
direction- Rotation direction ('cw' for clockwise, 'ccw' for counter-clockwise) - Returns: Promise with execution result
async rotateDocument(direction: 'cw' | 'ccw') {
try {
const result = await this.pdfViewer.triggerRotation(direction);
console.log(`Document rotated ${direction}:`, result);
} catch (error) {
console.error('Rotation failed:', error);
}
}
Utility Methods
refresh()
- Type:
void - Description: Refresh the viewer (useful for external window or when PDF needs to be reloaded)
refreshViewer() {
this.pdfViewer.refresh();
console.log('Viewer refreshed');
}
sendViewerControlMessage(action: string, payload: any)
- Type:
Promise<any> - Description: Send custom control message to the PDF viewer
- Parameters:
action- Action namepayload- Action payload
- Returns: Promise with response
async sendCustomMessage(action: string, data: any) {
try {
const response = await this.pdfViewer.sendViewerControlMessage(action, data);
console.log('Custom message sent:', response);
return response;
} catch (error) {
console.error('Custom message failed:', error);
}
}
Queue Management Methods
getActionStatus(actionId: string)
- Type:
'pending' | 'executing' | 'completed' | 'failed' | 'not-found' - Description: Get the status of a specific action
- Parameters:
actionId- Action identifier - Returns: Action status
checkActionStatus(actionId: string) {
const status = this.pdfViewer.getActionStatus(actionId);
console.log(`Action ${actionId} status:`, status);
return status;
}
getQueueStatus()
- Type:
{ queuedActions: number; executedActions: number } - Description: Get current queue status
- Returns: Object with queue statistics
getQueueInfo() {
const status = this.pdfViewer.getQueueStatus();
console.log(`Queue status - Queued: ${status.queuedActions}, Executed: ${status.executedActions}`);
return status;
}
clearActionQueue()
- Type:
void - Description: Clear all queued actions
clearQueue() {
this.pdfViewer.clearActionQueue();
console.log('Action queue cleared');
}
Security Methods
setUrlValidation(enabled: boolean)
- Type:
Promise<ActionExecutionResult> - Description: Enable or disable URL validation security feature
- Parameters:
enabled- Whether to enable URL validation (default: true)
async toggleSecurity() {
await this.pdfViewer.setUrlValidation(false);
console.log('URL validation disabled');
}
dismissSecurityWarning()
- Type:
void - Description: Dismiss the current security warning
dismissWarning() {
this.pdfViewer.dismissSecurityWarning();
console.log('Security warning dismissed');
}
Template Methods
getErrorTemplateData()
- Type:
any - Description: Get data for error template context
- Returns: Error template data object
getErrorData() {
const errorData = this.pdfViewer.getErrorTemplateData();
console.log('Error template data:', errorData);
return errorData;
}
reloadViewer()
- Type:
void - Description: Reload the viewer (alias for refresh)
reload() {
this.pdfViewer.reloadViewer();
console.log('Viewer reloaded');
}
goBack()
- Type:
void - Description: Go back in browser history
navigateBack() {
this.pdfViewer.goBack();
console.log('Navigated back');
}
closeViewer()
- Type:
void - Description: Close the viewer window
close() {
this.pdfViewer.closeViewer();
console.log('Viewer closed');
}
Complete Usage Example
export class PdfViewerComponent {
@ViewChild('pdfViewer') pdfViewer: any;
// Core functionality
async downloadPdf() {
try {
const result = await this.pdfViewer.triggerDownload();
console.log('Download successful:', result);
} catch (error) {
console.error('Download failed:', error);
}
}
async printPdf() {
try {
const result = await this.pdfViewer.triggerPrint();
console.log('Print successful:', result);
} catch (error) {
console.error('Print failed:', error);
}
}
async navigateToPage(pageNumber: number) {
try {
const result = await this.pdfViewer.setPage(pageNumber);
console.log(`Navigated to page ${pageNumber}:`, result);
} catch (error) {
console.error('Navigation failed:', error);
}
}
async changeZoom(zoomLevel: string) {
try {
const result = await this.pdfViewer.setZoom(zoomLevel);
console.log(`Zoom changed to ${zoomLevel}:`, result);
} catch (error) {
console.error('Zoom change failed:', error);
}
}
async rotateDocument(direction: 'cw' | 'ccw') {
try {
const result = await this.pdfViewer.triggerRotation(direction);
console.log(`Document rotated ${direction}:`, result);
} catch (error) {
console.error('Rotation failed:', error);
}
}
// Utility functions
refreshViewer() {
this.pdfViewer.refresh();
}
async sendCustomMessage(action: string, data: any) {
try {
const response = await this.pdfViewer.sendViewerControlMessage(action, data);
return response;
} catch (error) {
console.error('Custom message failed:', error);
}
}
// Queue management
getQueueInfo() {
const status = this.pdfViewer.getQueueStatus();
console.log(`Queue: ${status.queuedActions} queued, ${status.executedActions} executed`);
return status;
}
clearQueue() {
this.pdfViewer.clearActionQueue();
}
}
<ng2-pdfjs-viewer
#pdfViewer
pdfSrc="assets/sample.pdf"
(onDocumentLoad)="onDocumentLoad()"
(onPageChange)="onPageChange($event)">
</ng2-pdfjs-viewer>
<!-- Control buttons -->
<div class="controls">
<button (click)="downloadPdf()">Download</button>
<button (click)="printPdf()">Print</button>
<button (click)="navigateToPage(5)">Go to Page 5</button>
<button (click)="changeZoom('150%')">Zoom 150%</button>
<button (click)="rotateDocument('cw')">Rotate CW</button>
<button (click)="refreshViewer()">Refresh</button>
<button (click)="clearQueue()">Clear Queue</button>
</div>
Method Categories
Essential Methods
Methods you'll most commonly use:
triggerDownload()- Download PDFtriggerPrint()- Print PDFsetPage()- Navigate pagessetZoom()- Change zoom
Navigation Methods
Methods for document navigation:
goToPage()- Go to specific pagegoToLastPage()- Go to last pagetriggerRotation()- Rotate document
View Methods
Methods for view customization:
setCursor()- Change cursor modesetScroll()- Change scroll modesetSpread()- Change spread mode
Utility Methods
Methods for advanced functionality:
refresh()- Refresh viewersendViewerControlMessage()- Send custom messagesgetActionStatus()- Check action statusgetQueueStatus()- Get queue infoclearActionQueue()- Clear queue
Annotation Persistence
getAnnotations()
- Type:
Promise<any[]> - Description: Serialized state of every annotation created or modified in the editor — JSON-safe, ready to persist server-side
setAnnotations(annotations: any[])
- Type:
Promise<{ restored: number; pending: number; rejected: number }> - Description: Restore annotations previously exported with
getAnnotations(). Annotations for not-yet-rendered pages apply as those pages render (pending); items with an invalidpageIndexare skipped (rejected). Restore is additive — calling twice duplicates
// Persist on save…
const annotations = await this.pdfViewer.getAnnotations();
await this.api.saveAnnotations(docId, annotations);
// …restore on reload
const saved = await this.api.loadAnnotations(docId);
const result = await this.pdfViewer.setAnnotations(saved);
console.log(`${result.restored} restored, ${result.pending} pending`);
getDocumentAsBlob()
- Type:
Promise<Blob> - Description: The current document — including annotation edits and filled form fields — as a Blob, ready for upload or download
Search
search(query: string, options?: SearchOptions)
- Type:
Promise<SearchResult> - Description: Programmatic full-text search. Resolves with totals, per-page match counts and pages containing matches; matches highlight in the viewer
searchNext() / searchPrevious()
- Type:
Promise<ActionExecutionResult> - Description: Step through matches of the active search
clearSearch()
- Type:
Promise<ActionExecutionResult> - Description: Clear the active search and its highlights
Forms
getFormData()
- Type:
Promise<FormDataMap> - Description: Current AcroForm field values (field name → value), reflecting user edits
setFormField(name: string, value: string | boolean | null)
- Type:
Promise<ActionExecutionResult> - Description: Set a single form field programmatically
Text & AI
getDocumentText(from?: number, to?: number)
- Type:
Promise<DocumentPageText[]>({ page, text }[]) - Description: Extracted text per page (1-based, clamped). The foundation for bring-your-own-AI integrations
aiAsk(question: string)
- Type:
Promise<void> - Description: Ask the built-in AI panel a question programmatically. Requires
[aiAssistantConfig]
Read Aloud
startReadAloud(options?: { fromPage?: number; rate?: number })
- Type:
Promise<ActionExecutionResult> - Description: Read the document aloud with browser speech synthesis, sentence by sentence with in-page highlighting, from the given (or current) page
pauseReadAloud() / resumeReadAloud() / stopReadAloud()
- Type:
Promise<ActionExecutionResult> - Description: Pause, resume, or stop reading. Progress arrives via
(onReadAloudStateChange)
Next Steps
- ⚙️ Component Inputs - Configuration options
- 📤 Component Outputs - Event handling
- 📚 Examples - Practical examples
- 🚀 Getting Started - Quick setup guide