Angular 2 how to display .pdf file

后端 未结 9 501
不知归路
不知归路 2020-12-18 18:01

I have an angular2 app, where I want the user to be able to download and open a pdf file in the browser.

Is there an angular2 module or component that I can use?

相关标签:
9条回答
  • 2020-12-18 18:44

    You can use the File Viewer for Angular package.

    this package supported pdf, png, jpeg and mp4 formats.

    Install:

    npm i @taldor-ltd/angular-file-viewer ng2-pdf-viewer
    

    Usage:

    Add AngularFileViewerModule to your module's imports

    import { NgModule } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    
    import { AngularFileViewerModule } from '@taldor-ltd/angular-file-viewer';
    
    import { AppComponent } from './app/app.component';
    
    @NgModule({
      imports: [BrowserModule, AngularFileViewerModule],
      declarations: [AppComponent],
      bootstrap: [AppComponent]
    })
    
    class AppModule {}
    
    platformBrowserDynamic().bootstrapModule(AppModule);
    

    And then use it in your component

    (PDF sample)

    import { Component } from '@angular/core';
    
    import { FileMimeType } from '@taldor-ltd/angular-file-viewer';
    
    @Component({
      selector: 'app-root',
      template: `
        <tld-file-viewer [src]="src" [type]="type"></tld-file-viewer>
      `
    })
    export class AppComponent {
      src = 'http://www.africau.edu/images/default/sample.pdf';
      type = FileMimeType.PDF;
    }
    

    To read more

    0 讨论(0)
  • 2020-12-18 18:47

    It works for me. My error was to put responseType:ResponseContentType.ArrayBuffer in the headers and it is not inside it:

    {
         headers: new Headers({
            "Access-Control-Allow-Origin": "*",
            "Authorization": "Bearer "
         }),
         responseType:ResponseContentType.ArrayBuffer // YOU NEED THIS LINE
    }
    
    0 讨论(0)
  • 2020-12-18 18:48

    try this. Please change the filename.pdf with your actual path and file name

     <object data="filename.pdf" width="100%" height="100%" type='application/pdf'>
       <p>Sorry, the PDF couldn't be displayed :(</p>
       <a href="filename.pdf" target="_blank">Click Here</a>
     </object>
    
    0 讨论(0)
提交回复
热议问题