Abrir una incidencia
Chatee con nosotros

ASP.NET Core PDF Viewer - Ejemplos de JavaScript

Distintos ejemplos sobre cómo usar ASP.NET Core PDF Viewer desde JavaScript

Evento de iniciación del visor y eventos de visores personalizados

Antes de utilizar la instancia JS del visor, este tiene que haber sido iniciado.
Cuando esto ocurre, el evento twWiewerInitialized se activa.
Ese es el sitio recomendado a la hora de añadir disparadores para los eventos personalizados del visor.

El componente viewer muestra algunos eventos personalizados de JavaScript.
Cada uno de estos eventos tiene una propiedad detail.

Nombre de los eventos personalizados y propiedades de su propiedad detail:
pageRendered: pageNum, doc
allVisiblePagesRendered: doc
allPagesInitialized: doc
loadDocumentError: reason, url, file, evt
documentReleased
pageRenderedForPrint: pageNum, doc
allPagesRenderedForPrint: doc
printingCanceled: doc
pageRenderedForPrint: pageNum, doc

document.addEventListener("twWiewerInitialized", function (evt) { const viewerApp = event.detail.app; viewerApp.viewerDiv.addEventListener("pageRendered", function (evt) { console.log(`page number:${evt.detail.pageNum} for document ${evt.detail.doc} has been rendered.`); }); viewerApp.viewerDiv.addEventListener("allVisiblePagesRendered", function (evt) { console.log("allVisiblePagesRendered", evt); }); viewerApp.viewerDiv.addEventListener("allPagesInitialized", function (evt) { console.log("allPagesInitialized", evt); }); viewerApp.viewerDiv.addEventListener("documentReleased", function (evt) { console.log("documentReleased", evt); }); viewerApp.viewerDiv.addEventListener("pagePrinted", function (evt) { console.log("pagePrinted", evt.detail); }); });

Recuperar instancia JS del visor web por id

const viewerId = 'yourViewerId'; const viewer = window.TWPdfViewerUtil.getViewer(viewerId); if (!viewer) { console.log(`viewer with id ${viewerId} not found.`); } else { console.log(`viewer with id ${viewerId} found.`); }

NOTA la instancia del visor está preparada para un uso seguro tras el evento twWiewerInitialized.

Recuperar todas las instancias JS del visor web

const viewers = window.TWPdfViewerUtil.getActiveViewers(); for(let i=0; i < viewers.length;i++) { console.log(`viewer with id ${viewers[i].id}`); }

NOTA la instancia del visor está preparada para un uso seguro tras el evento twWiewerInitialized.

Cargar documento después de que la página web esté completamente renderizada

Si el PDF es muy grande, puede llevar algún tiempo cargar dicho PDF y afectar negativamente al posicionamiento en Google Page Speed Insight.
Si este es el caso, podrás ejecutar este código para cargar tu documento tras el evento DOMContentLoaded.

document.addEventListener("twWiewerInitialized", function (event) { const viewer = event.detail.app; viewer.addEventListener("pageRendered", function (evt) { console.log(`page number:${evt.detail.pageNum} for document ${evt.detail.doc} has been rendered.`); }); // optional custom load document events viewer.addEventListener("allVisiblePagesRendered", function (evt) { console.log("allVisiblePagesRendered", evt.detail.doc); }); viewer.addEventListener("allPagesInitialized", function (evt) { console.log("allPagesInitialized", evt.detail.doc); }); viewer.addEventListener("loadDocumentError", function (evt) { console.log("loadDocumentError", evt.detail.url, evt.detail.reason, evt.detail.file, evt.detail.evt); }); viewer.loadDocumentFromUrl("test-pdf/pdfprint-manual.pdf"); // alternatives for load: // viewer.loadDocumentFromFile(file, password, viewer); // viewer.openThroughDialog(); //if you want to hide open document button from the toolbar viewer.toolbar.isOpenVisible = false; });

Cerrar documento PDF

const viewer = window.TWPdfViewerUtil.getViewer('yourViewerId'); viewer.releasePdfDoc(); //if you want to hide open document button from the toolbar viewer.toolbar.isCloseVisible = false;1

Descargar documento PDF

const viewer = window.TWPdfViewerUtil.getViewer('yourViewerId'); viewer.downloadDocument(); //if you want to hide download document button from the toolbar viewer.toolbar.isDownloadVisible = false;

Obtén todos los temas incorporados disponibles

const themes = window.TWPdfViewerUtil.getBuiltInThemes(); for(let i=0; i< themes.length; i++) { console.log(`theme name:${themes[i]}`); }

Cambiar el tema del visor por nombre incorporado

window.TWPdfViewerUtil.changeThemeByName('blue-circle');

Cambiar el tema del visor por URL

window.TWPdfViewerUtil.changeThemeBySrcUrl('your_custom_theme_url');

NOTA Al cambiar el tema del visor, se alteran todas las instancias del visor en la página.

Navegación de página

const viewer = window.TWPdfViewerUtil.getViewer('yourViewerId'); // let assume that you have already loaded a document with at least 3 pages console.log(`Number of pages:${viewer.pdfDocument.pages.length}'); console.log(`Current page number:${viewer.currentPageNumber}'); viewer.gotoPage(2); viewer.nextPage(); // it will go to page 3 viewer.previousPage(); // it will go to page 2 viewer.prevVisited(); // it will go to page 3 viewer.nextVisited(); // it will go to page 2 //if you want to hide some or all page navigation from the toolbar viewer.toolbar.isNextPageVisible = false; viewer.toolbar.isPreviousPageVisible = false; viewer.toolbar.isNextVisitedVisible = false; viewer.toolbar.isPreviousVisitedVisible = false; viewer.toolbar.isPageNumberVisible = false;

Configuración de las opciones de búsqueda

const viewer = window.TWPdfViewerUtil.getViewer('yourViewerId'); viewer.toolbar.findOptions.wholeWord = true; viewer.toolbar.findOptions.caseSensitive = true; viewer.toolbar.findOptions.highlightAll = true; //if you want to hide search field on the toolbar viewer.toolbar.isSearchVisible = false;

NOTA En la versión actual, no es posible ejecutar “encontrar directamente” a partir de JS o ir a búsqueda anterior o posterior.
Si tu situación lo requiere, contacta con nosotros y proporcionanos información sobre tu caso concreto, de este modo podremos intentar añadirla.

Imprimir documento

const viewer = window.TWPdfViewerUtil.getViewer('yourViewerId'); //optional available print events viewer.addEventListener('pageRenderedForPrint', function(event) { console.log(`Page rendered for print. Document:${event.detail.doc} page number:${event.detail.pageNum}`); }); viewer.addEventListener('allPagesRenderedForPrint', function(event) { console.log(`All pages rendered for print. Document:${event.detail.doc}`); }); viewer.addEventListener('printingCanceled', function(event) { console.log(`Printing cancelled. Document:${event.detail.doc}`); }); // we assume that you have already loaded a PDF document viewer.print(); // it will open a new window and execute the print // if you want to hide print button from the toolbar viewer.toolbar.isPrintVisible = false;

Marcadores

const viewer = window.TWPdfViewerUtil.getViewer('yourViewerId'); // available bookmarks options viewer.bookmarkLayer.bookmarksFullyExpanded = true; viewer.bookmarkLayer.showBookmarksOnOpen = false; viewer.bookmarkLayer.preserveBookmarksState = true; // we assume that you have already loaded a PDF document and that document has bookmarks console.log('All bookmarks:', viewer.bookmarkLayer.allBookmarks); viewer.bookmarkLayer.show(true); // if you want to hide to the visitor show bookmarks button set this to false viewer.toolbar.isBookmarksVisible = false;

Propiedades de información del documento

const viewer = window.TWPdfViewerUtil.getViewer('yourViewerId'); viewer.showDocumentProperties(); // ... viewer.closeDocumentProperties(); // if you want to hide to the visitor show document info button set this to false viewer.toolbar.isDocumentInfoVisible = false;

NOTA En la versión actual, no es posible ver las propiedades del documento directamente desde JS./> Sin embargo, si tu situación lo requiere, contacta con nosotros y proporcionanos información sobre tu caso concreto, de este modo podremos intentar añadirla.

Rotación de la página

const viewer = window.TWPdfViewerUtil.getViewer('yourViewerId'); viewer.rotateClockwise(); // rotate for 90 degrees viewer.rotateCounterClockwise(); // rotate for -90 degrees // you can hide rotation buttons from the toolbar viewer.toolbar.isRotateClockwiseVisible = false; viewer.toolbar.isRotateCounterClockwiseVisible = false;

Vista de página única VS. multipágina

const viewer = window.TWPdfViewerUtil.getViewer('yourViewerId'); viewer.activateSinglePageView(); // ... viewer.activateMultiPageView(); // you can hide view buttons from the toolbar viewer.toolbar.isSingleViewVisible = false; viewer.toolbar.isMultiViewVisible = false;

Zoom

const viewer = window.TWPdfViewerUtil.getViewer('yourViewerId'); //available zoom levels for the loaded document are based //on the size of the PDF document console.log(viewer.zoomService.zoomLevels); //max zoom value for the loaded document console.log(viewer.zoomService.getMaxZoomValue()); //increases zoom level viewer.zoomService.zoomIn(); //decreases zoom level viewer.zoomService.zoomOut(); //set zoom value to specific value viewer.zoomService.setZoomValue(65); console.log('Current scale', viewer.zoomService.currentScale); // you can hide zoom functionality from the toolbar viewer.toolbar.isZoomInVisible = false; viewer.toolbar.isZoomOutVisible = false; viewer.toolbar.isZoomDropDownVisible = false;

Extracción y selección del texto en la página

const viewer = window.TWPdfViewerUtil.getViewer('yourViewerId'); //disable text selection viewer.disableSelection(true); // extract all text from the 1st page const pageText = viewer.getPageTextContent(1);

NOTA En la versión actual, no es posible obtener el texto seleccionado o seleccionar texto directamente desde JS.
Sin embargo, si tu situación lo requiere, contacta con nosotros y proporcionanos información sobre tu caso concreto, de este modo podremos intentar añadirlo.

Recuperar visor por ID

const viewer = window.TWPdfViewerUtil.getViewer(viewerId); if (!viewer) { console.log(`viewer with id ${viewerId} not found.`); } else { console.log(`viewer with id ${viewerId} found.`); }

Recuperar todos los visores

const viewers = window.TWPdfViewerUtil.getActiveViewers(); for (let i = 0; i < viewers.length; i++) { console.log(`viewer with id ${viewers[i].id}`); }

Cargar eventos del documento

const viewer = window.TWPdfViewerUtil.getViewer(viewerId); viewer.viewerDiv.addEventListener("pageRendered", function (evt) { console.log( `page number:${evt.detail.pageNum} for document ${evt.detail.doc} has been rendered.` ); }); // optional custom load document events viewer.viewerDiv.addEventListener("allVisiblePagesRendered", function (evt) { console.log("allVisiblePagesRendered", evt.detail.doc); }); viewer.viewerDiv.addEventListener("allPagesInitialized", function (evt) { console.log("allPagesInitialized", evt.detail.doc); }); viewer.viewerDiv.addEventListener("loadDocumentError", function (evt) { console.log( "loadDocumentError", evt.detail.url, evt.detail.reason, evt.detail.file, evt.detail.evt ); }); viewer.loadDocumentFromUrl("test-pdf/pdfprint-manual.pdf"); // alternatives for load: // viewer.loadDocumentFromFile(file, password, viewer); // viewer.openThroughDialog(); // if you want to hide open document button from the toolbar viewer.toolbar.isOpenVisible = false;

Volver al inicio
Copyright © 2024 Terminalworks. Todos los Derechos Reservados