Static
LicenseProduct license key.
<script>
// Add your license
DsPdfViewer.LicenseKey = 'XXX';
// Add your code
const viewer = new DsPdfViewer("#viewer");
viewer.addDefaultPanels();
</script>
Sets of toggles sidebar's panels visibility
Optional
show: booleanStatic
findGets the viewer instance using the host element or host element selector
var viewer = DsPdfViewer.findControl("#root");
Add annotation to document. Requires SupportApi.
// Add the Square annotation to the first page when you open the document:
viewer.onAfterOpen.register(function() {
viewer.addAnnotation(0, {
annotationType: 5, // AnnotationTypeCode.SQUARE
subtype: "Square",
borderStyle: { width: 5, style: 1 },
color: [0, 0, 0],
interiorColor: [255, 0, 0],
rect: [0, 0, 200, 200]
});
});
// Below is the sample how to copy field with name "field1" and put it to the second page programmatically:
// Find field widget with name field1:
var resultData = await viewer.findAnnotation("field1", {findField: 'fieldName'});
// Clone field:
var clonedField = viewer.cloneAnnotation(resultData[0].annotation);
// Change field name property:
clonedField.fieldName = "field1Copy";
// Add cloned field to the second page.
viewer.addAnnotation(1, clonedField);
// Add the FileAttachment annotation to the first page when you open the document:
viewer.onAfterOpen.register(function() {
viewer.addAnnotation(0, {
annotationType: 17, // AnnotationTypeCode.FILEATTACHMENT
subtype: "FileAttachment",
file: {
filename: 'attachment.png',
content: new Uint8Array([137,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,0,0,0,45,0,0,0,32,8,6,0,0,0,134,132,241,68,0,0,0,4,103,65,77,65,0,0,177,143,11,252,97,5,0,0,7,56,73,68,65,84,88,9,205,88,11,112,92,85,25,254,255,115,179,129,148,36,155,190,147,187,91,228,49,64,25,99,181,105,169,117,176,149,34,99,113,80,65,165,162,118,168,15,44,3,42,99,55,125,8,29,59,221,90,29,132,38,187,43,56,162,22,5,161,206,240,24,64,40,130,15,156,138,226,3,147,14,118,74,219,41,157,102,138,238,166,155,180,105,246,238,210,144,108,238,158,223,239,44,189,233,110,186,217,172,54,64,239,204,206,61,143,255,241,157,255,156,255,251,207,93,166,183,243,185,185,211,55,125,246,69,239,177,136,166,176,150,92,86,185,201,190,244,238,30,10,47,113,79,199,45,159,142,114,41,221,192,93,125,65,62,203,183,92,136,174,99,226,185,144,57,171,80,14,227,57,22,249,155,102,218,46,110,238,177,195,107,38,191,94,56,95,73,123,194,64,207,220,146,156,81,229,171,217,196,164,110,130,99,31,145,116,144,208,14,210,178,155,20,245,137,102,75,20,53,50,211,249,36,124,53,49,205,133,115,87,72,111,29,146,236,247,142,134,166,31,174,4,176,145,153,16,208,118,52,213,194,108,61,13,144,141,48,248,184,43,58,150,108,245,255,179,28,8,187,189,111,150,178,170,215,65,231,102,44])
},
rect: [0, 0, 20, 20]
});
});
Optional
args: { skipPageRefresh?: boolean }Optional
skipAdds document list panel to the Viewer with available document array specified in documentslist.json file (URL specified by documentListUrl option), located in the root directory of your application. You can specify service at the end point for documentListUrl option. The service should return JSON string with available documents array, e.g.: ["pdf1.pdf", "pdf2.pdf"]
Example content for the documentslist.json file:
["file1.pdf", "file2.pdf"].
var viewer = new DsPdfViewer("#root", { documentListUrl: "/documentslist.json" });
viewer.addDocumentListPanel();
var viewer = new DsPdfViewer("#root");
// Add document list panel and specify documentListUrl option:
viewer.addDocumentListPanel('/documentslist.json');
var viewer = new DsPdfViewer("#root");
// Add document list panel and specify documentListUrl option using DATA URI:
viewer.addDocumentListPanel('data:,[{"path": "doc1.pdf"}, {"path": "doc2.pdf", "name": "Hello doc 2", "title": "title 2"}]');
Optional
documentListUrl: string | DocumentListItem[]Optional. Document list service URL or predefined list of document list items.
Enable the Text Annotation Reply Tool. Note, in order to enable ability to edit/remove or add existing replies you need to configure SupportApi, otherwise the Reply Tool will be in read-only mode.
viewer.addReplyTool('expanded');
pass 'expanded' value if you wish the Reply tool to be expanded initially. Default value is collapsed.
Add a panel with a list of shared documents.
var viewer = new DsPdfViewer("#root");
viewer.addSharedDocumentsPanel();
Add stamp annotation.
// Add Graphical signature to the PDF using external image
function addStampFromUrl(imageUrl, viewer) {
* fetch(imageUrl)
.then(response => response.blob())
.then(blob => blob.arrayBuffer())
.then(arrayBuffer => {
const fileId = new Date().getTime() + ".png";
const fileName = fileId;
const pageIndex = 0;
const imageData = new Uint8Array(arrayBuffer);
const rect = [0, 0, 200, 200];
viewer.storage.setItem(fileId, imageData);
viewer.addStamp(
imageData,
{
fileId,
fileName,
pageIndex,
rect,
select: false,
subject: "",
rotate: 0,
convertToContent: false
});
});
}
// Usage:
addStampFromUrl("http://localhost/image.png", viewer);
Uint8Array, binary image data.
Optional
convertOptional
fileOptional
rotate?: numberOptional
select?: booleanOptional
subject?: stringAdd sticky note to the document. Requires SupportApi.
viewer.addStickyNote(viewer.toViewPortPoint({x: 50, y: 50, pageIndex: 0}));
page relative point. Origin is top/left. Note, pageIndex must be specified.
Call this method in order to apply changes in @see:toolbarLayout. *
key: 'custom-add-stamp',
icon: { type: "svg", content: '<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="24" height="24" viewBox="0 0 24 24"><path style="fill: #205F78;" d="M20.25 12l-2.25 2.25 2.25 2.25-3.75 3.75-2.25-2.25-2.25 2.25-2.25-2.25-2.25 2.25-3.75-3.75 2.25-2.25-2.25-2.25 2.25-2.25-2.25-2.25 3.75-3.75 2.25 2.25 2.25-2.25 2.25 2.25 2.25-2.25 3.75 3.75-2.25 2.25 2.25 2.25z"></path></svg>' },
title: 'Open your document to add a stamp',
checked: false, enabled: false,
action: function () {
alert("Implement your action here.");
},
onUpdate: function (args) {
var hasDoc = viewer.hasDocument && args.state.session.pageCount > 0;
return {
enabled: hasDoc,
checked: false,
title: hasDoc ? 'Add stamp' : 'Open your document to add a stamp'
}
}
This method changes coordinate system origin for rectangle given by parameter bounds and returns converted rectangle value;
var pageIndex = 0;
var topLeftBounds = [0, 0, 200, 40];
// Convert the topLeftBounds from TopLeft origin to BottomLeft origin
// taking into account the viewport from the first page and store
// the result in the bottomLeftBounds variable:
var bottomLeftBounds = viewer.changeBoundsOrigin(pageIndex, topLeftBounds, 'TopLeft', 'BottomLeft');
// Gets the bounds of the annotation relative to the viewport:
const pageIndex = 0;
const viewPort = viewer.getViewPort(pageIndex);
const annotationRect = (await viewer.findAnnotation('10R'))[0].annotation.rect;
const invertedRect = viewer.changeBoundsOrigin(pageIndex, annotationRect, 'BottomLeft', 'TopLeft');
const annotationX1 = invertedRect[0] * viewPort.scale;
const annotationY1 = invertedRect[1] * viewPort.scale;
const annotationX2 = invertedRect[2] * viewPort.scale;
const annotationY2 = invertedRect[3] * viewPort.scale;
Page index (Zero based).
bounds array: [x1, y1, x2, y2]
Source coordinate system origin. Possible values are: 'TopLeft' or 'BottomLeft'.
Destination coordinate system origin. Possible values are: 'TopLeft' or 'BottomLeft'.
Optional. Default is true. Normalize rectangle [x1, y1, x2, y2] so that (x1,y1) < (x2,y2).
This method changes coordinate system origin for y coordinate given by parameter y and returns converted value.
var pageIndex = 0;
var y = 0;
// Convert from TopLeft origin to BottomLeft origin
// taking into account the viewport from the first page:
var yBottom = viewer.changeOrigin(pageIndex, y, 'TopLeft', 'BottomLeft');
Converts the origin of the Y coordinate to the bottom.
var pageIndex = 0;
var y = 0;
// Convert y value from TopLeft origin to BottomLeft origin
// taking into account the viewport from the first page:
var yBottom = viewer.changeOriginToBottom(pageIndex, y);
Converts the origin of the Y coordinate to the top.
var pageIndex = 0;
var y = 0;
// Convert y value from BottomLeft origin to TopLeft origin
// taking into account the viewport from the first page:
var yTop = viewer.changeOriginToTop(pageIndex, y);
Clone annotation or field given by parameter annotation. Requires SupportApi.
// Below is the sample how to copy field with name "field1" and put it to the second page programmatically:
// Find field widget with name field1:
var resultData = await viewer.findAnnotation("field1", {findField: 'fieldName'});
// Clone field:
var clonedField = viewer.cloneAnnotation(resultData[0].annotation);
// Change field name property:
clonedField.fieldName = "field1Copy";
// Add cloned field to the second page.
viewer.addAnnotation(1, clonedField);
Annotation to clone.
Display confirmation dialog.
const confirmResult = await viewer.confirm("Apply changes?", "info", "Confirm action", ["Yes", "No", "Cancel"]);
if (confirmResult === "Yes") {
// put your code here
} else if (confirmResult === "No") {
// put your code here
} else {
// put your code here
}
Optional
confirmationText: string | ElementOptional
level: "error" | "info" | "warning"Optional
title: stringOptional
buttons: ConfirmButton[]Starts long-running operation and displays progress window while operation is running.
Optional
settings: TaskSettingsFind annotation(s) within opened document. Returns promise which will be resolved with search results.
// Find annotation with id '2R':
viewer.findAnnotations("2R").then(function(dataArray) {
if(dataArray[0])
alert(`Annotation ${dataArray[0].annotation.id} found on page with index ${dataArray[0].pageIndex}.`);
else
alert('Annotation not found.');
});
// find all fields with name field1:
viewer.findAnnotations("field1", {findField: 'fieldName', findAll: true}).then(function(dataArray) {
});
Find query.
Optional
findParams: { findAll?: boolean; findField?: string; pageIndexConstraint?: number }Find parameters. By default annotation will be searched by id without page index constraint.
Optional
findOptional
findOptional
pageReturns position of the page view relative to the browser window.
var pageLocation = viewer.getPageLocation(0);
console.log('The first page location is ' + location.x + ', ' + location.y);
// Draws a red rectangle over the annotation with id "10R".
(async function(viewer, annotationId) {
const pageLocation = viewer.getPageLocation(0), viewPort = viewer.getViewPort(0),
scale = viewPort.scale, viewBox = viewPort.viewBox;
const rect = (await viewer.findAnnotation(annotationId))[0].annotation.rect;
const x1 = rect[0] * scale + pageLocation.x, x2 = rect[2] * scale + pageLocation.x,
y1 = (viewBox[3] - rect[3]) * scale + pageLocation.y, y2 = (viewBox[3] - rect[1]) * scale + pageLocation.y;
const div = document.createElement('div');
div.style.position = 'absolute';
div.style.left = `${x1}px`; div.style.top = `${y1}px`;
div.style.width = `${x2 - x1}px`; div.style.height = `${y2 - y1}px`;
div.style.border = '1px solid red';
document.body.appendChild(div);
})(viewer, "10R");
// Add text annotation on mouse click
document.addEventListener("click", (e) => {
const target = (e["path"] || (e["composedPath"] && e["composedPath"]()) || [])[0] || e.target, page = target.closest(".page");
if(target.closest(".gc-annotation"))
return;
if(page) {
const pageIndex = page.getAttribute("data-index") * 1, pageLoc = viewer.getPageLocation(pageIndex), scale = viewer.getViewPort(pageIndex).scale;
const x = (e.clientX - pageLoc.x) / scale, y = (e.clientY - pageLoc.y) / scale;
const rect = viewer.changeBoundsOrigin(pageIndex, [x, y, x + 20, y + 20], "TopLeft", "BottomLeft");
viewer.addAnnotation(pageIndex, { annotationType: 1 , contents: "Text annotation content", rect });
}
});
Get the page rotation value.
// Get the first page rotation value:
var rotation = viewer.getPageRotation(0);
Include view rotation, default is true.
Returns the page size. By default, return size without scale, pass true for the includeScale argument if you want to get the scaled value.
// Get first page size:
var pageSize = viewer.getPageSize(0);
Page index (Zero based).
Optional
includeScale: booleanOptional. If true, the method will return scaled value.
Get page annotations tabs order. A name specifying the tab order that shall be used for annotations on the page. Possible values are: R - Row order. C - Column order. S - Structure order (not supported by DsPdfViewer). A - Annotations order. This order refers to the order of annotation in the annotations collection. W - Widgets order . This order uses the same ordering as "Annotations" order, but two passes are made, the first only picking the widget annotations and the second picking all other annotations.
Returns a list of shared documents available to the current user.
var sharedDocuments = await viewer.getSharedDocuments();
Get information about signature used in document.
// Example: check if the current document is signed and show information about signature:
var viewer = DsPdfViewer.findControl("#root");
const signatureInfo = await viewer.getSignatureInfo();
if(signatureInfo.signed) {
const signatureValue = signatureInfo.signedByFields[0].signatureValue;
const signerName = signatureValue.name;
const location = signatureValue.location;
const signDate = viewer.pdfStringToDate(signatureValue.modificationDate);
alert("The document was signed using digital signature. Signed by: " + signerName + ", location: " + location + ", sign date: " + signDate.toString());
} else {
alert("The document is not signed.");
}
Returns PDF page view port information.
Object containing following fields: { viewBox: // Original page bounds: [x1, y1, x2, y2]. // If you want to know original page's width/height, you can get it using viewBox values: // var pageWidth = viewBox[2] - viewBox[0]; // var pageHeight = viewBox[3] - viewBox[1]; width: // Current width of the page in user space (scale and rotation values are applied), height: // Current height of the page in user space (scale and rotation values are applied) scale: // Active scale value rotation: // Active rotation value }
// Get the viewport object for the first page:
var viewPort = viewer.getViewPort(0);
Page index (Zero based).
Go to the page with the specific page number (numbering starts at 1).
Method goToPageNumber deprecated since version 2.3.1, use goToPage method or pageIndex property instead.
// Go to the second page:
viewer.goToPageNumber(2);
Ensures that all visual child elements of the viewer are properly updated for layout. Call this method to update the size of the inner content when the viewer is dynamically resized.
viewer.eventBus.on("viewersizechanged", function() {
// Make viewer height equal to content height of inner pages, including the margins:
document.querySelector("#root").style.height = viewer.pageCount * 50 + viewer.pageCount * viewer.getPageSize(0, true).height + "px";
// Invalidate layout:
viewer.invalidate();
});
The method loads the page at the index specified by the pageIndex parameter, and scrolls the page into the view.
Returns the boolean promise that resolves when the page is fully loaded (including text and annotation layers) and scrolled. A promise is resolved with false value when the page does not exist or an error occurs, otherwise the promise is resolved with true value.
// Load and display the first page:
viewer.loadAndScrollPageIntoView(0);
Destination page index.
Optional
destArray: any[]Array with destination information. destArray[0] // not used, can be null, pdf page reference (for internal use only). destArray[1] // contains destination view fit type name: { name: 'XYZ' } - Destination specified as top-left corner point and a zoom factor (the lower-left corner of the page is the origin of the coordinate system (0, 0)). { name: 'Fit' } - Fits the page into the window { name: 'FitH' } - Fits the widths of the page into the window { name: 'FitV' } - Fits the height of the page into a window. { name: 'FitR' } - Fits the rectangle specified by its top-left and bottom-right corner points into the window. { name: 'FitB' } - Fits the rectangle containing all visible elements on the page into the window. { name: 'FitBH' } - Fits the width of the bounding box into the window. { name: 'FitBV' } - Fits the height of the bounding box into the window. destArray[2] // x position offset destArray[3] // y position offset (note, the lower-left corner of the page is the origin of the coordinate system (0, 0)) destArray[4] // can be null, contains bounding box width when view name is FitR, contains scale when view name is XYZ, destArray[5] // can be null, contains bounding box height when view name is FitR
Optional
scrollIntoViewOptions: boolean | ScrollPageIntoViewOptionsOptional scroll options. Used when the destArray parameter is not specified. If true, the top of the element will be aligned to the top of the visible area of the scrollable ancestor. Corresponds to scrollIntoViewOptions: {block: "start", inline: "nearest"}. This is the default value. If false, the bottom of the element will be aligned to the bottom of the visible area of the scrollable ancestor. Corresponds to scrollIntoViewOptions: {block: "end", inline: "nearest"}.
Load an updated document list into document list panel.
viewer.loadDocumentList();
// Load document list using DATA URI:
viewer.loadDocumentList('data:,[{"path": "doc1.pdf"}, {"path": "doc2.pdf", "name": "doc 2", "title": "title 2"}]');
Optional
documentListUrl: string | DocumentListItem[]Optional. Document list service URL or array with the document list items.
Loads the updated list of shared documents into the shared documents panel.
viewer.loadSharedDocuments();
Lock annotation for editing.
annotation id
Creates and opens a new blank document. Requires SupportApi.
// Create a new blank document, name the file "test.pdf",
// display a confirmation dialog if the active document has been modified.
viewer.newDocument({ fileName: "test.pdf", confirm: true});
Optional
params: string | { confirm?: boolean; fileName?: string }Parameters object: fileName - name of the file for a new document, confirm - show confirmation dialog if there are changes in the document.
Adds a blank page to the document. Requires SupportApi.
// Create a new blank page and insert it in the second position.
viewer.newPage({pageIndex: 1});
Optional
params: { height?: number; pageIndex?: number; width?: number }parameters object: width - page width in points, height - page height in points, pageIndex - target page index.
Optional
height?: numberOptional
pageOptional
width?: numberOpen PDF document.
viewer.open("Documents/HelloWorld.pdf");
// Specify Basic Access authentication headers:
viewer.open("http://localhost:5005/api/pdf-viewer/GetPdf?file=HelloWorld.pdf", {
headers: {
"Authorization": "Basic " + btoa(unescape(encodeURIComponent("USERNAME:PASSWORD"))),
"CustomHeader": "Custom header value"
}
});
Optional
file: anyURL to PDF document(string) or binary data(Typed array - Uint8Array).
Optional
openParameters: OpenParametersLoading parameters object.
Opens the side panel.
const layersPanelHandle = viewer.addLayersPanel();
viewer.open("house-plan.pdf").then(()=> {
viewer.openPanel(layersPanelHandle);
});
Panel handle or panel id to open.
Open shared document by it's id.
Open shared document using document index:
async function openSharedDocByIndex(viewer, sharedDocIndex) {
const sharedDocuments = await viewer.getSharedDocuments();
viewer.openSharedDocument(sharedDocuments[sharedDocIndex].documentId);
}
// Open first shared document:
openSharedDocByIndex(DsPdfViewer.findControl("#viewer"), 0);
Open shared document using document’s file name. Note, a document with the same name can be shared multiple times. In the example below, we open the first found document with the given fileName.
async function openSharedDocByName(viewer, fileName) {
const sharedDocuments = await viewer.getSharedDocuments();
const index = sharedDocuments.findIndex(d=>d.fileName === fileName);
if(index !== -1)
viewer.openSharedDocument(sharedDocuments[index].documentId);
}
// Open the first available shared document named "financial-report.pdf":
openSharedDocByName(DsPdfViewer.findControl("#viewer"), "financial-report.pdf");
unique shared document identifier.
Open shared document using document index.
Open second shared document:
viewer.openSharedDocumentByIndex(1);
Open shared document using document’s file name. Note, a document with the same name can be shared multiple times. The openSharedDocumentByName opens the first found document with the given fileName.
// Open the first available shared document named "sample.pdf":
viewer.openSharedDocumentByName("sample.pdf");
Remove annotation from document. Requires SupportApi.
// Remove annotation with id '2R' located on the first page:
viewer.removeAnnotation(0, '2R');
Optional
args: { skipPageRefresh?: boolean }Optional
skipRepaint pages. This method also redraws the page annotations.
// Redraw content and annotations for visible pages:
viewer.repaint();
// Redraw content and annotations for pages with indexes 0 and 3:
viewer.repaint([0, 3]);
Optional
indicesToRepaint: number[]If specified, page indices to be redrawn, otherwise, this method redraws visible pages.
Resolve page index using PDF page reference.
const openAction = (await viewer.viewerPreferences).openAction;
if(openAction && openAction.dest) {
const pageRef = openAction.dest[0];
const targetPageIndex = await viewer.resolvePageIndex(pageRef);
}
Save the modified PDF document to the local disk. Requires SupportApi.
Specify destination file name
viewer.save('Test.pdf');
Optional
fileName: stringDestination file name.
Optional
settings: SaveSettingsAdditional save settings.
Saves the pages of the current PDF document as PNG images, zips the result images, and downloads the result zip archive. Requires SupportApi.
// Save the pages of the current PDF document as PNG images and specify destination zip file name:
viewer.saveAsImages('Test.zip');
// Save the pages of the current PDF document as PNG images,
// and specify destination view zoom factor:
viewer.saveAsImages("sample.pdf", { zoomFactor: 1.5 });
Optional
fileName: stringoptional, destination zip archive file name.
Optional
settings: SaveSettingsAdditional save settings.
Scroll annotation into view.
// Scroll the annotation located on the second page into view.
viewer.scrollAnnotationIntoView(1, annotation);
// Scroll annotation into view by id.
viewer.scrollAnnotationIntoView("2R");
// Scroll annotation into view by id using smooth scroll behavior.
viewer.scrollAnnotationIntoView("2R", { behavior: "smooth" });
Optional
annotationOrScrollOptions: string | AnnotationBase | ScrollPageIntoViewOptionsOptional
scrollOptions: ScrollBehavior | ScrollPageIntoViewOptionsScroll page into view.
Method scrollPageIntoView deprecated since v2.3.1 use methods goToPage, scrollAnnotationIntoView instead.
object. Scroll parameters: pageNumber - number. Page number. destArray - Array with destination information: destArray[0] // not used, can be null, pdf page reference (for internal use only). destArray[1] // contains destination view fit type name: { name: 'XYZ' } - Destination specified as top-left corner point and a zoom factor (the lower-left corner of the page is the origin of the coordinate system (0, 0)). { name: 'Fit' } - Fits the page into the window { name: 'FitH' } - Fits the widths of the page into the window { name: 'FitV' } - Fits the height of the page into a window. { name: 'FitR' } - Fits the rectangle specified by its top-left and bottom-right corner points into the window. { name: 'FitB' } - Fits the rectangle containing all visible elements on the page into the window. { name: 'FitBH' } - Fits the width of the bounding box into the window. { name: 'FitBV' } - Fits the height of the bounding box into the window.
contains scale when view name is XYZ,
Optional
allowOptional
destSearches currently opened document for the text.
Optional
progressFn: ((progress: { pageCount: null | number; pageIndex: number }) => void)Optional
cancel: CancellationTokenSelect the annotation to edit. Requires SupportApi.
// Select an annotation with id 2R:
viewer.selectAnnotation("2R");
// Select an annotation with id 9R located on the last page:
viewer.selectAnnotation(viewer.pageCount - 1, "9R");
Page index (zero based) or annotation id.
Optional
annotation: string | AnnotationBaseAnnotation id or annotation object itself.
Use the setAnnotationBounds method to set the position and / or size of the annotation.
// Set the location of the annotation to the top / left corner:
viewer.setAnnotationBounds('1R', {x: 0, y: 0});
// Set the location of the annotation to the bottom / left corner:
viewer.setAnnotationBounds('1R', {x: 0, y: 0}, 'BottomLeft');
// Set the annotation size to 40 x 40 points:
viewer.setAnnotationBounds('1R', {w: 40, h: 40});
// Set the annotation position to x=50, y=50 (origin top / left) and size to 40 x 40 points:
viewer.setAnnotationBounds('1R', {x: 50, y: 50, w: 40, h: 40});
annotation object or annotation id.
Destination bounds - x, y, width and height are optional.
Source coordinate system origin. Default is TopLeft
Select annotation after editing. Default is false.
Set the absolute page rotation in degrees. Valid values are 0, 90, 180, and 270 degrees. Requires SupportApi.
// Set the first page rotation to 180 degrees:
await viewer.setPageRotation(0, 180);
Set page size. Requires SupportApi.
// Set new page size for the first page:
viewer.setPageSize(0, { width: 300, height: 500 } );
Set page annotations tabs order. A name specifying the tab order that shall be used for annotations on the page. Possible values are: R - Row order. C - Column order. S - Structure order (not supported by DsPdfViewer). A - Annotations order. This order refers to the order of annotation in the annotations collection. W - Widgets order . This order uses the same ordering as "Annotations" order, but two passes are made, the first only picking the widget annotations and the second picking all other annotations.
Shows the message for the user.
// Show warning message
viewer.showMessage("Warning message text", "", "warn");
Executes "Submit A Form action" to send filled form data to a web server or email. Form data is submitted as HTML form using HTML submit method.
Submit form to a web server using absolute URL:
viewer.submitForm("http://myhost.local/AcceptHtmlForm");
Submit form to a web server using relative URL:
viewer.submitForm("/CustomFormHandler");
Submit form to an email address:
viewer.submitForm("mailto:myform@example.com");
Destination URI.
Optional
options: SubmitFormOptionsOptional, submit form options.
Trigger event.
// Listen CustomEvent:
viewer.getEvent("CustomEvent").register(function(args) {
console.log(args);
});
// Trigger CustomEvent:
viewer.triggerEvent("CustomEvent", { arg1: 1, arg2: 2});
Optional
args: EventArgs | BeforeOpenEventArgs | ThemeChangedEventArgsUnlock annotation for editing.
annotation id
Update annotation. Requires SupportApi.
Promise, resolved by updated annotation object.
// Update annotation on the first page (page index is 0):
viewer.updateAnnotation(0, annotation1);
Optional
changedOptional
prevOptional
skipUpdate multiple annotations at the same time. Requires SupportApi.
Promise, resolved by updated annotation objects.
// Update annotations on the second page (page index is 1):
var annotationsToUpdate = [annotation1, annotation2];
viewer.updateAnnotations(1, annotationsToUpdate);
Optional
args: { skipPageRefresh?: boolean }Optional
skipUpdate radio buttons group given by parameter fieldName with new field value.
Promise resolved by boolean value, true - radio buttons updated, false - an error occurred.
viewer.updateGroupFieldValue("radiogroup1", "3", { skipPageRefresh: true } );
viewer.updateGroupFieldValue("radiogroup1", "3", { propertyName: "alternativeText", skipPageRefresh: true } );
Grouped radio buttons field name
New fieldValue
Optional
args: { propertyName?: string; skipPageRefresh?: boolean }skipPageRefresh boolean - set to true if you don't need to update page display. Default is false. propertyName string - property name to update. Default is "fieldValue".
Optional
propertyOptional
skipUse this method to validate an active form and get the validation result.
Returns true if validation was successful, false, or a string with a validation error message when validation is failed.
// Validate all form fields, each field must have the value "YES" or "NO".
viewer.validateForm((fieldValue, field) => { return (fieldValue === "YES" || fieldValue === "NO") ? true : "Possible value is YES or NO."; });
Optional
validator: ((fieldValue: string | string[], field: WidgetAnnotation) => string | boolean)Optional. The validator function which will be called for each field in the form. You can return a string value with message about validation error, this message will be shown in UI. Return true or null for success result.
Optional
silent: booleanOptional. Pass true if you don't want to display any messages to the user, but just want to get the final validation result.
Optional
ignoreValidationAttrs: booleanOptional. Pass true to skip validation using field attributes such as required, min, max, minLength, maxLength, email and pattern, these attributes will be ignored.
Static
i18nGets i18next instance which can be used to add viewer translations. See https://www.i18next.com for details about i18next framework.
function loadPdfViewer(selector) {
// You can load translations from any source (see en-pdf-viewer.json for an example):
var myTranslations = {
"toolbar": {
"open-document": "Open MY document",
"pan": "My Pan tool",
}
};
// Initialize translations:
DsPdfViewer.i18n.init({
resources: { myLang: { viewer: myTranslations } },
defaultNS: 'viewer'
}).then(function(t) {
// New translations initialized and ready to go!
// Now create PDF viewer:
var viewer = new DsPdfViewer(selector, { language: 'myLang' });
viewer.addDefaultPanels();
//viewer.open("sample.pdf");
});
}
loadPdfViewer('#root');
Activated editor mode name.
Gets all document annotations. *
for(var i = 0; i < data.length; i++){
var pageAnnotationsData = data[i];
var pageIndex = pageAnnotationsData.pageIndex;
var annotations = pageAnnotationsData.annotations;
console.log("Page with index " + pageIndex + " contains " + annotations.length + " annotation(s)");
}
Gets or sets viewer background color, default value = 'transparent'
Ask the user if he want to leave the page when document is modified. Requires SupportApi.
var viewer = new DsPdfViewer('#root', { supportApi: 'api/pdf-viewer' } );
viewer.addDefaultPanels();
viewer.addAnnotationEditorPanel();
viewer.addFormEditorPanel();
viewer.beforeUnloadConfirmation = true;
Ask the user if he want to leave the page when document is modified. Requires SupportApi.
var viewer = new DsPdfViewer('#root', { supportApi: 'api/pdf-viewer' } );
viewer.addDefaultPanels();
viewer.addAnnotationEditorPanel();
viewer.addFormEditorPanel();
viewer.beforeUnloadConfirmation = true;
Indicates whether the open document can be edited using SupportApi. Requires SupportApi.
if(viewer.canEditDocument) {
alert("Document editing features enabled.");
} else {
alert("Document editing features disabled.");
}
Specifies the current user name. The property is used by Annotation Editor as default value for 'author' field.
viewer.currentUserName = "John";
alert("The current user name is " + viewer.currentUserName);
Specifies the current user name. The property is used by Annotation Editor as default value for 'author' field. Note, current user name is saved in the browser's local storage and it will be used on the next page reload if userName option is not set.
viewer.currentUserName = "John";
alert("The current user name is " + viewer.currentUserName);
PDF document meta data loader. Used by some sidebar panels.
Gets the current document
Indicates the selected editing tool for the Annotation editor or Form editor. Requires SupportApi.
// Set the layout mode to "Annotation editor"
viewer.layoutMode = 1;
// Set the edit mode to "Square".
viewer.editMode = 4;
Indicates the selected editing tool for the Annotation editor or Form editor. Requires SupportApi.
// Set the layout mode to "Annotation editor"
viewer.layoutMode = 1;
// Set the edit mode to "Square".
viewer.editMode = 4;
Gets or sets callback that is invoked when an error occurs in the process of displaying the report
Internal event bus. Available event names are: outlineloaded, attachmentsloaded, namedaction, pagemode, fileattachmentannotation, pagerendered, pagecancelled, scalechange, pagesinit, pagesloaded, documentchanged, rotationchanging, updateviewarea, undostorechanged, show-custom-layout, hide-custom-layout, annotationeditstarted, unselectannotation, annotation-bounds-change, pagechange, mousemodechange, request-answer, textlayerready, viewersizechanged, articlebeadnavigate, error, open, pagelabels, documentload.
// Example: listen annotation selected/unselected event.
var viewer = DsPdfViewer.findControl("#root");
viewer.eventBus.on("annotationeditstarted", (args)=> {
console.log("Annotation selected, annotation id: " + args.annotationId);
});
viewer.eventBus.on("unselectannotation", (args)=> {
console.log("Annotation unselected, annotation id: " + args.annotationId);
});
Gets the file data. Available when keepFileData option is set to true.
var viewer = new DsPdfViewer('#root', { keepFileData: true });
viewer.open('Test.pdf');
viewer.onAfterOpen.register(function() {
var pdfFileData = viewer.fileData;
});
Gets the file name that was used to open the document. The file name is determined as follows:
var viewer = new DsPdfViewer('#root');
viewer.onAfterOpen.register(function() {
alert("The document is opened, the fileName is " + viewer.fileName);
});
viewer.open('MyDocuments/Test.pdf');
Gets the PDF document file size in bytes.
const fileSizeBytes = await viewer.fileSize;
Gets the URL that was used to open the document. Returns an empty string when the document was opened from binary data.
var viewer = new DsPdfViewer('#root');
viewer.onAfterOpen.register(function() {
alert("The document is opened, the fileUrl is " + viewer.fileUrl);
});
viewer.open('MyDocuments/Test.pdf');
An unique document identifier.
var viewer = new DsPdfViewer('#root');
viewer.onAfterOpen.register(function() {
alert("The document opened, an unique document identifier is "+ viewer.fingerprint);
});
viewer.open('Test.pdf');
Gets the GcPdf library version used by the SupportApi, if available.
Indicates whether the document has been modified by the user.
if(viewer.hasChanges) {
alert("The document has been changed.");
}
Indicates whether the copy buffer contains any data.
if(viewer.hasCopyData) {
viewer.execPasteAction();
}
Indicates whether the document is loaded into view.
if(!viewer.hasDocument) {
viewer.open("sample.pdf");
}
Gets a value indicating whether the active document has any form fields.
if(viewer.hasForm) {
viewer.showFormFiller();
}
Gets a value indicating whether the viewer has a persistent connection to the server.
Gets a value indicating whether the pdf viewer can redo document changes. Requires SupportApi.
if(viewer.hasRedoChanges) {
viewer.redoChanges();
}
Indicates whether the Reply Tool has been added.
var viewer = new DsPdfViewer('#root');
if(viewer.hasReplyTool) {
alert("The Reply Tool has not been added to the viewer.");
} else {
alert("The Reply Tool has been added to the viewer.");
}
viewer.open('Test.pdf');
Gets a value indicating whether the pdf viewer can undo document changes. Requires SupportApi.
if(viewer.hasUndoChanges) {
viewer.undoChanges();
}
Determines whether the annotation layer is hidden.
// Hide annotations:
viewer.hideAnnotations = true;
Determines whether the annotation layer is hidden.
// Hide annotations:
viewer.hideAnnotations = true;
Gets the main window's host element
Gets a value indicating whether the active document is open in shared mode. Requires SupportApi.
if(viewer.isDocumentShared) {
alert("The document is open in shared mode.");
}
Returns true if the active edit mode is sticked by the user. Indicates that the stickyBehavior for the active edit button is enabled and the button is checked. See the toolbarLayout.stickyBehavior property for details.
Gets a value indicating whether the editor mode is currently active.
let isInEditorMode = viewer.isInEditorMode;
// Detect the start/end of edit mode
var isEdit = false;
viewer.onViewerStateChange.register(function () {
if (viewer.isInEditorMode !== isEdit) {
isEdit = viewer.isInEditorMode;
console.log(isEdit ? "Editor Mode activated." : "Editor Mode deactivated.");
}
});
Returns true if notifications suspended by calls to @see:beginUpdate.
var isUpdatingFlag = viewer.isUpdating;
language - A property that retrieves the standardized language key based on the provided language option.
The language key is determined by the options.language
setting.
Standardized language key (e.g., 'en', 'ja').
Gets or sets the layout mode (0 - Viewer, 1 - AnnotationEditor or 2 - FormEditor).
0
// Set the layout mode to "Form editor"
viewer.layoutMode = 2;
Gets or sets the layout mode (0 - Viewer, 1 - AnnotationEditor or 2 - FormEditor).
0
// Set the layout mode to "Form editor"
viewer.layoutMode = 2;
Left sidebar API.
viewer.leftSidebar.hide();
Gets current log level. Available log levels are: 'None', 'Critical', 'Error', 'Warning', 'Information', 'Debug', 'Trace'. Default level is 'None'.
Sets current log level. Available log levels are: 'None', 'Critical', 'Error', 'Warning', 'Information', 'Debug', 'Trace'. Default level is 'None'.
Gets modifications state for active document. Requires SupportApi.
var modificationsState = viewer.modificationsState;
console.log(modificationsState);
After add annotation event.
viewer.onAfterAddAnnotation.register(function(args) {
console.log(args);
});
The event raised when the user changes the viewer theme.
var viewer = new DsPdfViewer('#root');
viewer.onAfterOpen.register(function() {
alert("The document opened.");
});
viewer.open('Test.pdf');
After remove annotation event.
viewer.onAfterRemoveAnnotation.register(function(args) {
console.log(args);
});
After update annotation event.
viewer.onAfterUpdateAnnotation.register(function(args) {
console.log(args);
});
Before add annotation event. The event is cancelable.
viewer.onBeforeAddAnnotation.register(function(args) {
console.log(args);
args.cancel = true; // set the cancel flag to cancel event.
});
Occurs immediately before the document opens.
var viewer = new DsPdfViewer('#root');
viewer.onBeforeOpen.register(function(args) {
alert("A new document will be opened,\n payload type(binary or URL): " + args.type +",\n payload(bytes or string): " + args.payload);
});
viewer.open('Test.pdf');
Before remove annotation event. The event is cancelable.
viewer.onBeforeRemoveAnnotation.register(function(args) {
console.log(args);
args.cancel = true; // set the cancel flag to cancel event.
});
Before update annotation event. The event is cancelable.
viewer.onBeforeUpdateAnnotation.register(function(args) {
console.log(args);
args.cancel = true; // set the cancel flag to cancel event.
});
The event indicating document was changed (new document opened, drilled or "back to parent" is issued)
The event indicating document load progress
The event indicating document view was changed (new document opened, refreshed, toggled etc)
The event indicating error.
var viewer = new DsPdfViewer('#root');
viewer.addDefaultPanels();
viewer.onError.register(handleError);
viewer.open('Test.pdf');
function handleError(eventArgs) {
var message = eventArgs.message;
if (message.indexOf("Invalid PDF structure") !== -1) {
alert('Unable to load pdf document, pdf document is broken.');
} else {
alert('Unexpected error: ' + message);
}
}
Occurs when the viewer theme changed by user.
var viewer = new DsPdfViewer(selector, {
requireTheme: localStorage.getItem('demo_theme') || 'viewer'
});
viewer.addDefaultPanels();
viewer.onThemeChanged.register(function(args) {
localStorage.setItem('demo_theme', args.theme);
});
Indicates the viewer state was changed.
Default optional content config. An optional content is a collection of graphics that can be made visible or invisible dynamically.
// Use the optionalContentConfig property to print information about all available layers
const config = await viewer.optionalContentConfig;
console.table(config.getGroups());
const config = await viewer.optionalContentConfig;
// Turn off optional content group with id "13R":
config.setVisibility("13R", false);
// Repaint visible pages:
viewer.repaint();
The viewer options.
viewer.options.zoomByMouseWheel = { always: true };
viewer.applyOptions();
PDF viewer options.
Gets pages count.
var viewer = new DsPdfViewer('#root');
viewer.onAfterOpen.register(function() {
alert("The document opened. Total number of pages: " + viewer.pageCount);
});
viewer.open('Test.pdf');
Gets or sets page view decoration mode.
Gets/sets the active page index.
var viewer = new DsPdfViewer('#root');
viewer.onAfterOpen.register(function() {
// Navigate page with index 9:
viewer.pageIndex = 9;
});
viewer.open('Test.pdf');
Gets/sets the active page index.
var viewer = new DsPdfViewer('#root');
viewer.onAfterOpen.register(function() {
// Navigate page with index 9:
viewer.pageIndex = 9;
});
viewer.open('Test.pdf');
Gets the required SupportApi version that is compatible with the current version of the DsPdfViewer.
Gets right sidebar object. Use this object if you want to manipulate the right sidebar.
viewer.rightSidebar.show('expanded', 'reply-tool');
viewer.rightSidebar.toggle();
viewer.rightSidebar.hide();
viewer.rightSidebar.expand();
viewer.rightSidebar.collapse();
Specifies the rotation in degrees.
var viewer = new DsPdfViewer('#root');
// Register an onAfterOpen event handler:
viewer.onAfterOpen.register(function() {
// Apply 90 degree clockwise rotation:
viewer.rotation = 90;
});
// Open document:
viewer.open('Test.pdf');
Specifies the rotation in degrees.
var viewer = new DsPdfViewer('#root');
// Register an onAfterOpen event handler:
viewer.onAfterOpen.register(function() {
// Apply 90 degree clockwise rotation:
viewer.rotation = 90;
});
// Open document:
viewer.open('Test.pdf');
Gets the scroll view HTML element. Note, the left scroll position is calculated by the viewer automatically - so, usually, you don't need to change left scroll position.
// Scroll to the top of the document:
viewer.scrollView.scrollTop = 0;
Document search worker instance. Searches currently opened document for a text.
// Highlight all search results without opening SearchPanel.
const searchIterator = viewer.searcher.search({ Text: "test", MatchCase: true, HighlightAll: true });
searchIterator.next();
searcher.applyHighlight();
// Iterate all search results
const searcher = viewer.searcher;
var searchResults = [];
const searchIterator = searcher.search({ Text: textToSearch, MatchCase: true });
var searchResult = await searchIterator.next();
if (searchResult.value)
searcher.highlight(searchResult.value)
while (searchResult.value && !searchResult.done) {
const searchResultValue = searchResult.value;
searchResults.push(`index: ${searchResultValue.ItemIndex}, text: ${searchResultValue.DisplayText}, pageIndex: ${searchResultValue.PageIndex}`);
searchResult = await searchIterator.next();
}
console.log("Search results: " + (searchResults.length ? searchResults.join("; ") : "No search results"));
// Open the document, find the text 'wildlife' and highlight the first result:
async function loadPdfViewer(selector) {
var viewer = new DsPdfViewer(selector, { restoreViewStateOnLoad: false });
viewer.addDefaultPanels();
var afterOpenPromise = new Promise((resolve)=>{ viewer.onAfterOpen.register(()=>{ resolve(); }); });
await viewer.open('wetlands.pdf');
await afterOpenPromise;
var findOptions = { Text: 'wildlife' };
var searchIterator = await viewer.searcher.search(findOptions);
var searchResult = await searchIterator.next();
viewer.searcher.cancel();
viewer.searcher.highlight(searchResult.value);
}
loadPdfViewer('#root');
// Open the document, find the text 'wildlife' and print search results to the console:
async function loadPdfViewer(selector) {
var viewer = new DsPdfViewer(selector);
viewer.addDefaultPanels();
await viewer.open('wetlands.pdf');
await (new Promise((resolve)=>{
viewer.onAfterOpen.register(()=>{
resolve();
});
}));
var findOptions = {
Text: 'wildlife',
MatchCase: true,
WholeWord: true,
StartsWith: false,
EndsWith: false,
Wildcards: false,
Proximity: false,
SearchBackward: false,
HighlightAll: true
};
var searcher = viewer.searcher;
var searchIterator = await searcher.search(findOptions);
var resultsCount = 0;
var searchResult;
do {
searchResult = await searchIterator.next();
if (searchResult.value) {
// this could be either result or progress message (ItemIndex < 0)
if(searchResult.value.ItemIndex >= 0) {
console.log('next search result:');
console.log(searchResult.value);
resultsCount++;
} else {
const pageCount = _doc.pageCount.totalPageCount || _doc.pageCount.renderedSoFar;
console.log('search progress, page index is ' + searchResult.value.PageIndex);
}
}
else {
console.log("Search completed");
break;
}
}
while(!searchResult.done);
console.log('Total results count is ' + resultsCount);
}
Second toolbar API.
Second toolbar layout. Use the secondToolbarLayout property to configure available tools.
Second toolbar layout. Use the secondToolbarLayout property to configure available tools.
Returns data storage which can be used to store and retrieve current signature tool settings and images. Please, note, the storage data depends on current user name, @see:currentUserName property
Data storage for the active document.
const fileData = viewer.storage.getItem(annotation.fileId);
viewer.storage.setItem(fileId, bytes);
Add Stamp annotation programatically using storage API
viewer.newDocument().then(function() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://localhost/sample.jpg', true);
xhr.responseType = 'arraybuffer';
xhr.onload = function(e) {
var arrayBuffer = this.response;
if (arrayBuffer) {
// Add Stamp annotation programatically:
viewer.storage.setItem("sample_file_id_1", new Uint8Array(arrayBuffer));
var pageSize = viewer.getPageSize(0);
viewer.addAnnotation(0, {annotationType: 13, fileId: "sample_file_id_1", rect: [0, pageSize.height - 144, 144, pageSize.height]});
}
};
xhr.send();
});
Structure tree data.
const viewer = new DsPdfViewer(selector);
await viewer.open("sample.pdf");
const structureTree = await viewer.structureTree;
if(structureTree) {
console.log(structureTree);
}
A promise that is resolved with a
[] objects that represents the page's structure tree,
or null
when no structure tree is present for the page.
Gets the SupportApi client. Requires SupportApi.
var viewer = new DsPdfViewer('#root', { supportApi: 'api/pdf-viewer' } );
// Contact server and get Support API version.
viewer.serverVersion.then(function(ver) {
alert("The SupportApi version is " + ver);
});
Gets the connected version of the SupportApi, if available.
Temporary expose event, which occurs on panel change
Defines the layout of the toolbar for different viewer modes: viewer, annotationEditor, formEditor.
The full list of the viewer specific toolbar items:
'open', '$navigation', '$split', 'text-selection', 'pan', 'zoom', '$fullscreen', '$split', 'text-tools', 'draw-tools', 'attachment-tools',
'form-tools', 'page-tools', '$split', 'rotate', 'search', 'view-mode', 'theme-change', 'download', 'print', 'save', 'save-images', 'hide-annotations', 'form-filler',
'doc-title', 'doc-properties', 'about', 'share', 'single-page', 'continuous-view', '$history', '$mousemode', 'show-edit-tools', 'show-form-editor'
The full list of the annotationEditor specific toolbar items:
'edit-select', 'save', 'share', 'edit-text', 'edit-free-text', 'edit-ink', 'edit-square',
'edit-circle', 'edit-line', 'edit-polyline', 'edit-polygon', 'edit-stamp', 'edit-file-attachment', 'edit-sound', 'edit-link', 'edit-highlight', 'edit-underline', 'edit-squiggly', 'edit-strike-out'.
'edit-redact', 'edit-redact-apply', 'edit-erase', 'edit-undo', 'edit-redo', 'new-document', 'new-page', 'delete-page', '$split', 'pdf-organizer'
The full list of the formEditor specific toolbar items:
'edit-select-field', 'save', 'share',
'edit-widget-tx-field', 'edit-widget-tx-password', 'edit-widget-tx-text-area', 'edit-widget-btn-checkbox', 'edit-widget-btn-radio',
'edit-widget-btn-push', 'edit-widget-ch-combo', 'edit-widget-ch-list-box', 'edit-widget-tx-comb', 'edit-widget-btn-submit', 'edit-widget-btn-reset',
'edit-erase-field', 'edit-undo', 'edit-redo', 'new-document', 'new-page', 'delete-page', '$split', 'pdf-organizer'
// Customize the toolbar layout:
viewer.toolbarLayout.viewer.default = ["open", "save", "share"];
viewer.toolbarLayout.annotationEditor.default = ["open", "save", "share", "$split", "new-document", "edit-ink", "edit-text"];
viewer.toolbarLayout.formEditor.default = ["open", "save", "share", "$split", "edit-widget-tx-field", "edit-widget-tx-password"];
viewer.applyToolbarLayout();
// Show only Open and Redact buttons:
var viewer = new DsPdfViewer('#root', { supportApi: 'api/pdf-viewer' });
// Add annotation editor panel:
viewer.addAnnotationEditorPanel();
// Change toolbar layout:
viewer.toolbarLayout = { viewer: { default: ["open", 'show-edit-tools']},
annotationEditor: { default: ["open", 'edit-redact', 'edit-redact-apply']} };
// Activate 'Annotation Editor' layout mode:
viewer.layoutMode = 1;
// Make square, circle and line buttons sticky:
viewer.toolbarLayout.stickyBehavior = ["edit-square", "edit-circle", "edit-line"];
viewer.applyToolbarLayout();
Defines the layout of the toolbar for different viewer modes: viewer, annotationEditor, formEditor.
The full list of the viewer specific toolbar items:
'text-selection', 'pan', 'open', 'save', 'share', 'download', 'print', 'rotate', 'theme-change', 'doc-title', 'view-mode', 'single-page', 'continuous-view',
'$navigation' '$refresh', '$history', '$mousemode', 'zoom', '$fullscreen', '$split', 'show-edit-tools', 'show-form-editor'
The full list of the annotationEditor specific toolbar items:
'edit-select', 'save', 'share', 'edit-text', 'edit-free-text', 'edit-ink', 'edit-square',
'edit-circle', 'edit-line', 'edit-polyline', 'edit-polygon', 'edit-stamp', 'edit-file-attachment', 'edit-sound', 'edit-link', 'edit-highlight', 'edit-underline', 'edit-squiggly', 'edit-strike-out'.
'edit-redact', 'edit-redact-apply', 'edit-erase', 'edit-undo', 'edit-redo', 'new-document', 'new-page', 'delete-page', '$split', 'pdf-organizer'
The full list of the formEditor specific toolbar items:
'edit-select-field', 'save', 'share',
'edit-widget-tx-field', 'edit-widget-tx-password', 'edit-widget-tx-text-area', 'edit-widget-btn-checkbox', 'edit-widget-btn-radio',
'edit-widget-btn-push', 'edit-widget-ch-combo', 'edit-widget-ch-list-box', 'edit-widget-tx-comb', 'edit-widget-btn-submit', 'edit-widget-btn-reset',
'edit-erase-field', 'edit-undo', 'edit-redo', 'new-document', 'new-page', 'delete-page', '$split', 'pdf-organizer'
// Customize the toolbar layout:
viewer.toolbarLayout.viewer.default = ["open", "save", "share"];
viewer.toolbarLayout.annotationEditor.default = ["open", "save", "share", "$split", "new-document", "edit-ink", "edit-text"];
viewer.toolbarLayout.formEditor.default = ["open", "save", "share", "$split", "edit-widget-tx-field", "edit-widget-tx-password"];
viewer.applyToolbarLayout();
// Show only Open and Redact buttons:
var viewer = new DsPdfViewer('#root', { supportApi: 'api/pdf-viewer' });
// Add annotation editor panel:
viewer.addAnnotationEditorPanel();
// Change toolbar layout:
viewer.toolbarLayout = { viewer: { default: ["open", 'show-edit-tools']},
annotationEditor: { default: ["open", 'edit-redact', 'edit-redact-apply']} };
// Activate 'Annotation Editor' layout mode:
viewer.layoutMode = 1;
Gets the number of levels(commands) on the undo stack. Requires SupportApi.
alert("Undo levels count is " + viewer.undoCount);
Gets the index of the current Undo level (command). This is the Undo command that will be executed on the next call to redoChanges(). Requires SupportApi.
alert("The current Undo level index is " + viewer.undoIndex);
The current state of the undo store. Note that this property is read-only, do not programmatically change the elements of the collection. Use the Undo API methods to change the viewer's editor state. Undo API properties: hasUndoChanges, hasRedoChanges, undoIndex, undoCount Undo API methods: undoChanges(), redoChanges()
Returns the current version of the GcDocs PDF viewer.
alert("The DsPdfViewer version is " + viewer.version);
Gets or sets view mode (single page or continuous).
Gets initial viewer preferences.
Gets currently viewed document state
Gets/sets the current zoom node. Accepted values are: 0 - Value, 1 - PageWidth, 2 - WholePage.
// Set zoom mode to 'WholePage'
viewer.zoomMode = 2;
Gets/sets the current zoom node. Accepted values are: 0 - Value, 1 - PageWidth, 2 - WholePage.
// Set zoom mode to 'WholePage'
viewer.zoomMode = 2;
Gets/sets target element for zoom transformation. If 'page' is set, each page will be transformed individually (default behavior). If 'viewport' is set, entire viewport element will be transformed instead. This is added to prevent issues in some specific cases, see ARJ-4340. *
Gets/sets the current zoom percentage level.
// Set zoom value to 150%
viewer.zoomValue = 150;
Gets/sets the current zoom percentage level.
// Set zoom value to 150%
viewer.zoomValue = 150;
root container element or selector pattern used to select the root container element.
Viewer options.
GcPdfViewer component is a fast JavaScript based client-side PDF Viewer that runs in all major browsers.
Note that DsPdfViewer is the new name for GcPdfViewer, with the same API.
During this transition period we are publishing both versions, but it is recommended that you switch to using DsPdfViewer when possible.