stephanrauh / ngx-extended-pdf-viewer

A full-blown PDF viewer for Angular 16, 17, and beyond
https://pdfviewer.net
Apache License 2.0
481 stars 182 forks source link

PDFLinkService.navigateTo: "null" is not a valid destination array #71

Closed schnebdreleg closed 5 years ago

schnebdreleg commented 5 years ago

Hello

I followed your installation guide and tried to use this lib in our project. Everything is working fine so far, except for a single error in the console when the pdf viewer is launched for the first time: PDFLinkService.navigateTo: "null" is not a valid destination array, for dest="/xxx" (xxx is the angular router link of the current component). I could not find anything in the doc regarding this error. Do you have an idea what could be the problem? Also, pdf.js warns about the missing default worker Warning: Setting up fake worker. As far as I know, this warning only appears when the default pdf directory is missing?

Thanks in advance

stephanrauh commented 5 years ago

You didn't mention it, but this issue indicates the message might have something to do with the hash symbol in the URL. Do you use the '#' in your URLs?

schnebdreleg commented 5 years ago

Thank you for your answer. Yes, you are right; we use '#' in our routes

stephanrauh commented 5 years ago

OK, I'll investigate the topic. But it seems to be a difficult one. Can you switch to the HTML5 approach to routes? Without the '#'?

stephanrauh commented 5 years ago

The problem is that the PDF viewer assumes that the hash tag is used to navigate to a named destination or a page number within the PDF file. So it's confused by Angular using the hash tag.

This is how it's meant to be used: http://localhost:4200/#page=12 http://localhost:4200/#nameddest=chapter_7

stephanrauh commented 5 years ago

Solved with version 0.9.29. Now the PDF viewer doesn't listen the URL - unless you insists on activating it with listenToURL="true".

schnebdreleg commented 5 years ago

thank you for your effort in this case :)

tanzl88 commented 5 years ago

I still see this error PDFLinkService.navigateTo: "null" is not a valid destination array, for dest="/reports/98" despite using listenToURL flag. I have tried both not setting the flag explicitly and setting explicitly to false. Both show the same error. Interestingly it only happens when the component is loaded for the first time. Creating a new instance after destroyed does not show this error.

tanzl88 commented 5 years ago

@stephanrauh any thought?

stephanrauh commented 5 years ago

@tanzl88 You've posted your question in a closed issue. Luckily, I read the e-mail notifications. Otherwise, I'd have missed it. Actually, that's the reason why I didn't answer your question: before I simply didn't see it.

I'll have a look at it this evening.

tanzl88 commented 5 years ago

Sorry I don't want to create a duplicate issue. Appreciate if you could look at #86 too. We were half way through that.

stephanrauh commented 5 years ago

@tanzl88 Please update to the latest version of ngx-extended-pdf-viewer (if you haven't done so already) and debug the class NgxExtendedPdfViewerComponent. It should look like so:

  private openPDF() {
    NgxExtendedPdfViewerComponent.ngxExtendedPdfViewerInitialized = true;
    this.onResize();
    if (!this.listenToURL) {
      (<any>window).PDFViewerApplication.pdfLinkService.setHash = function() {};
    }

Things to check:

stephanrauh commented 5 years ago

@tanzl88 Did you manage to solve the issue?

tanzl88 commented 5 years ago

Yes. I don't see the error anymore after using the latest version.

stephanrauh commented 5 years ago

OK, let's close the issue, hoping it really was a npm caching problem.

ravimalani86 commented 4 years ago
 private openPDF() {
    NgxExtendedPdfViewerComponent.ngxExtendedPdfViewerInitialized = true;
    this.onResize();
    if (!this.listenT

please share how to use listen To URL . and how to get anchor tag href value in typescript function

Thanks

stephanrauh commented 4 years ago

@ravimalani86 Sorry, I missed your reply. This code is used when pdf.js is run in stand-alone mode. You can add directives like the start page and several more to the link.

I'm not sure if it's possible to use the same approach in Angular. That probably doesn't make much sense because most Angular applications use the URL for their own routing.

luis-cosillo commented 2 years ago

I have the same problem when loading a PDF in angular, DFLinkService.goToDestination: "null" is not a valid destination array, for dest="/online-help/OnlineHelp/CONFPROD/1/1", does anyone know how to fix it? ?

stephanrauh commented 2 years ago

@luis-cosillo It's hard to say with so little information. What did you do, precisely? And is /online-help//OnlineHelp/CONFPROD/1/1 a destination defined by the author of the PDF file?

BTW: If it's easier for you, feel free to answer in Spanish.

luis-cosillo commented 2 years ago

Si mucho más fácil en español, gracias por contestar, pues únicamente estoy cargando un archivo PDF, la única variante es que el control ngx-extended-pdf-viewer lo tengo dentro de un tab,

<div class="tab-pane" 
       id="link04">
       <ngx-extended-pdf-viewer height="50" [listenToURL]="true"
                          [(base64Src)]="valorBase64PDF" 
                          [useBrowserLocale]="true"  
                          [textLayer]="true" 
                          [showHandToolButton]="false" 
                          [showPresentationModeButton]="false"
                          [showOpenFileButton]="true" 
                          (currentZoomFactor)="'100%'"
                          [zoom]="'page-width'" 
                          [showZoomButtons]="false" 
                          [showRotateButton]="false"
                          [showDownloadButton]="false"
                          [showPrintButton]="false"
                          [showBookmarkButton]="false"
                          [showFindButton]="false" 
                          [showSidebarButton]="false"
                          [showScrollingButton]="false" 
                          [showPropertiesButton]="false"
                          [customToolbar]="additionalButtons" 
                          >
      </ngx-extended-pdf-viewer>
      <ng-template #additionalButtons>
          <div id="toolbarViewer">
            <div id="toolbarViewerLeft">
              <pdf-find-button [showFindButton]="true" [textLayer]="true"></pdf-find-button>
              <pdf-paging-area></pdf-paging-area>
            </div>
            <div id="toolbarViewerRight">
              <!-- <button type="button" id="openFile"
                  class="toolbarButton new-tab"
                  title="Abrir archivo" >
                  <mat-icon class="text-info">open_in_browser</mat-icon>
              </button> -->
              <pdf-open-file></pdf-open-file>
              <button type="button"
                  class="toolbarButton new-tab"
                  title="Quitar archivo" 
                  (click)="limpiarPDF()">
                  <mat-icon class="text-info">delete</mat-icon>
              </button>

            </div>
          </div>
        </ng-template>
  </div>

no se si hay que hacer algo mas, adicional quiero limpiar el contenido pero no lo hace

limpiarPDF(){
        console.log('limpiar pdf');
        this.valorBase64PDF = '';
    }

Y tampoco no se algo mal estoy haciendo pero no le he encontrado.

stephanrauh commented 2 years ago

No creo que es relacionado, pero sí el tab no es activo cuando al inicio, ngx-extended-pdf-viewer no puede arrancar. En otro lado, este resulte en un mensaje distinto.

stephanrauh commented 2 years ago

¿Por qué asignas [listenToURL]="true"? En este caso, ngx-extended-pdf-viewer trata la ruta de Angular como un destino de un enlace interno. Y, lógicamente, no existen estas rutas en el archivo PDF.

luis-cosillo commented 2 years ago

fijate que si lo quito de igual forma da el error eso se lo acabo de poner tratando de ver como hago para que funcione, el mismo control lo tengo en un modal y alli si funciona bien, pero en este caso lo tengo en un componente donde tengo 4 pestañas, y en una de esas pestañas tengo el ngx-extended-pdf-viewer, ahorita se lo quite el [listenToURL]="true" y de igual forma da el error

image

stephanrauh commented 2 years ago

Pensé que false es el valor de [listenToUrl] por defecto, pero pruebalo con [listenToUrl]="false". O quizás has encontrado un error.

image

luis-cosillo commented 2 years ago

creo que si encontre un error porque aunque le ponga false da el mismo problema, al igual te explico otro error que tiene, si te das cuenta puse un boton para limpiar el PDF porque el usuario se puede equivocar, y la primera vez funciona, pero si cargas otro PDF, y le das limpiar ya no lo hace, al igual si volves a cargar el mismo PDF ya ni lo muestra.

stephanrauh commented 2 years ago

Otra cosita: el attibuto [height] necesita una unidad. Como "50px" or "50%".

stephanrauh commented 2 years ago

¿Puedes enviarme un reproducer? Una aplicación simple y minimal mostrando el error?

luis-cosillo commented 2 years ago

voy a crearla y te paso el link para que lo puedas descargar

luis-cosillo commented 2 years ago

Este es el link https://github.com/luis-cosillo/testPDF.git, allí te cree el proyecto, básicamente lo que hice agarre el mismo template para que sea lo más parecido al proyecto en el que estoy trabajando. Muchas gracias siempre por el apoyo.

stephanrauh commented 2 years ago

Despues clonar tu proyecto y añadir un fichero PDF, no ví el mensaje. Pero, claro, cuando activé [listenToUrl], aparezca:

image
stephanrauh commented 2 years ago

Si te entiendo bien, ¿siempre ves el mensaje?

La intencion de este atributo es permitir URLs como https://mozilla.github.io/pdf.js/web/viewer.html#page=3&zoom=150. Tambien funciona con ngx-extended-pdf-viewer si configuras el router que no usa hashes:

RouterModule.forRoot(AppRoutes,{
          useHash: false
        }),

Con este configuración, navigar a http://localhost:4200/dashboard#page=4&zoom=30 resulta en

image

http://localhost:4200/dashboard#page=4&zoom=30

luis-cosillo commented 2 years ago

Déjame pedir que nos lo cambien en azure, ya que la aplicación normal la tenemos pegada allí y están registradas las URL con los # para poder probar, por la seguridad que manejan.

  1. Ahora una consulta para limpiar el control que comando se utiliza, que como viste en el que te coloque la primera vez funciona, pero si le das más de una vez ya no funciona

  2. ¿utilice este código para bajar el PDF en base 64, pero una función nativa no tiene el control que no sea Blob??

stephanrauh commented 2 years ago

¿Que tengo que hacer para reproducir el error?

  1. Abro un PDF del backend, de formato BASE64 o Blob --> no mensaje
  2. Hago un click en "limpiar"
  3. Abro otro PDF del backend --> el mensaje esta aqui

¿Correcto?

Intenté con estas lineas de codigo:

   valorURLPDF: string = "/assets/a.pdf";
    limpiarPDF(){
        console.log('limpiar pdf');

        this.valorURLPDF = '';
        setTimeout(() => this.valorURLPDF = "/assets/b.pdf", 4000)
    }
luis-cosillo commented 2 years ago

si pues tendria que tener un PDF x defecto para poder limpiarlo entonces, y los pasos son asi:

  1. cargo un pdf con nombre test.pdf
  2. le doy limpiar ( en este momento lo hace)
  3. vuelvo a cargar test.pdf solo para efectos de prueba y en ese momento ya no lo hace
  4. entonces digo cargo otro pdf con otro nombre totalmente diferente y lo carga
  5. vuelvo a limpiar y alli otra vez ya no lo hace

Te coloqué un video para que veas https://github.com/luis-cosillo/testPDF/blob/main/ejemplos/2022-02-09_16-50-35.mp4

stephanrauh commented 2 years ago

¿Que pasa en segundo 0:12 de tu video? Un PDF blanco esta cargado automáticamente - antes de seleccionar un archivo. ¿Como es posible? Nunca he visto antes. ¿Quiza tienes que limpiar el cache del browser?

Hablando del limpiar - el methodo functiona unicamente una vez por que no hay cambios. valorURLPDF no cambia si abres un otro archivo usando el menú. Hay una solución temporal:

 limpiarPDF(){
      console.log('limpiar pdf');

      if (this.valorURLPDF === undefined) {
        this.valorURLPDF = "";
      } else {
        this.valorURLPDF = undefined;
      }
  }

Ademas, puedes intentar desactivar el LocalStore:

constructor() {
  pdfDefaultOptions.disableHistory=false;
}
luis-cosillo commented 2 years ago

Lo del PDF en blanco tú me pasaste esta linea setTimeout(() => this.valorURLPDF = "/assets/b.pdf", 4000) entonces para que no saliera error en la consola porque ese b.pdf no existe, hice un PDF con ese nombre en blanco. Pero voy a probar lo que me dices en limpiar lo que pasa que no puedo desactivar el localStorage porque allí guardo información que guarda el IDP de azure.

stephanrauh commented 2 years ago

Oops, sorry! No quería confundirte. :)