31

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?

YakovL
  • 7,557
  • 12
  • 62
  • 102
Ricky
  • 693
  • 3
  • 12
  • 20
  • did you tried `` – Devidas Kadam Apr 07 '17 at 06:55
  • I've started to collect all available options on https://pdfviewer.net/alternatives. Granted, at the moment, the majority of this website is devoted to my own library (ngx-extended-pdf-viewer). I'm going to cover the alternatives in depth soon. – Stephan Rauh Jul 01 '19 at 19:51

10 Answers10

29

Have you taken a look at this module https://www.npmjs.com/package/ng2-pdf-viewer?

remember to declare it in the module like so

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms'; 
import { HttpModule } from '@angular/http';

import { PdfViewerComponent } from 'ng2-pdf-viewer'; 
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent,
    PdfViewerComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
Benji Lees
  • 815
  • 6
  • 12
  • Yes. but it is not working. it gives error while i use selector name of this coponent on html file. is their any another component or module?? – Ricky Apr 07 '17 at 06:21
  • Could you please post a code snippet and the error that you are receiving? – Benji Lees Apr 07 '17 at 08:11
  • error is : "pdf-viewer" element is not a angular2 component. – Ricky Apr 07 '17 at 10:11
  • Have you added "pdf-viewer" into the module declarations? – Benji Lees Apr 07 '17 at 11:12
  • Ok I have just set it up locally and have it working. So I am pretty sure the module works. I am happy to push the example up with a sample pdf. Or alternatively would it be possible for you to share a snippet of the code for the component and module? – Benji Lees Apr 07 '17 at 11:22
  • here you go https://github.com/benjaminlees/angular-pdf. Just pull and run npm install. Then make sure you have angular-cli installed globally before running `ng-serve` and going to port 4200 – Benji Lees Apr 07 '17 at 11:43
  • a quick look inside the `node_modules/ng-pdf-viewer/dist` folder and the file `index` made clear this has been renamed into PdfViewerModule. So your code needs to be `import { PdfViewerModule } from 'ng2-pdf-viewer';` and dont forget to add it to your imports inside the module. – BigPenguin Nov 15 '17 at 12:48
  • Is is possible to download the pdf with this lib? I'm trying but there is no option for download. When I put the pdf on an iframe it shows me the download button. – GustavoA Mar 14 '18 at 15:47
25

ng2-pdf-viewer work quite good, but i wanted the pdf display like on this page : https://pdfobject.com/static.html

Sadly, i had a pdf stream, and not a direct pdf (no .pdf at the end of the link) like : https://***********.idshost.fr/ws/********xfer/ws/download/3ca3dfa2-e89d-4f98-bcf2-55ad62bacfc6

the response was like that (only pasted a part):

%PDF-1.3 %Äåòåë§ó ÐÄÆ 4 0 obj << /Length 5 0 R /Filter /FlateDecode >> stream xTÍÛ6¼û)æØE[²ì89$i½=°×Ë@"µ"e}ôÉKõY:¬,]§k©ùfæwø;,÷^@yÄQ²é>Ù£ÿ¼â£1l ¶Ñj-âTßâ1üJ,>à æ{Ü©¦Ô6@¢

whit headers like that

HTTP/1.1 200 OK
Date: Fri, 05 May 2017 11:00:32 GMT
Server: Apache-Coyote/1.1
Content-Disposition: attachment; filename="1/B_FILENAME*****.pdf"
Content-Type: application/pdf
Content-Length: 34723
Keep-Alive: timeout=5, max=96
Connection: Keep-Alive

i heard that changing content-disposition to inline instead of attachment make the browser try to open it instead of downloading, i don't have access to server so didn't tried.

My pdf would not show, getting blank view, or error "failed to load pdf document". (but it worked on some rare pdf whit <object> and <embed>, but not <iframe> for unknow reason)

finnaly managed to find something that work, maybe it help some people, here is the code (angular2):

.ts file


    import {DomSanitizer,SafeResourceUrl} from '@angular/platform-browser'
    import {Headers} from "@angular/http/src/headers";
    import {ResponseContentType} from "@angular/http/index";

        //somewhere...
        this.getConsultationDocumentPDF(this.inputDataFile.hash).subscribe(
                        (data:any) => { // data type is Response, but since _body is private field i changed it to any

                            var file3 = new Blob([data._body], {type: 'application/pdf'});
                            this.dataLocalUrl = this.domSanitizer.bypassSecurityTrustResourceUrl(window.URL.createObjectURL(file3));


                        },
                        error => {
                            console.log(error);
                        }
                    );

        public getConsultationDocumentPDF (pHash:string):Observable<Response> {
            return this.http.get(
                "https://***********.idshost.fr/ws/********xfer/ws/download/"+pHash,
                {
                    headers: new Headers({
                        "Access-Control-Allow-Origin": "*",
                        "Authorization": "Bearer "
                    }),
                    responseType:ResponseContentType.ArrayBuffer // YOU NEED THAT
                }
            );

        }

.html file (any of them work, iframe has more fonctionnality for me, like print )

    <div *ngIf="dataLocalUrl != undefined">
        <h5>iframe whit local url</h5>
        <iframe width="500" height="600" [attr.src]="dataLocalUrl" type="application/pdf"></iframe>
        <h5>object whit local url</h5>
        <object [attr.data]="dataLocalUrl" type="application/pdf" width="100%" height="100%"></object>
        <h5>embed whit local url</h5>
        <embed [attr.src]="dataLocalUrl" type="application/pdf" width="100%" height="100%">
    </div>

Hope it help somebody !

Ambroise Rabier
  • 3,636
  • 3
  • 27
  • 38
  • Ty this is way better than the pdf viewer. For me all 3 solutions offer printing. Would be good to know the pros and cons between them. – Doomenik Jun 23 '17 at 12:28
  • 1
    I am getting the following error Error: unsafe value used in a resource URL context. Could anyone help me – MPPNBD Aug 10 '18 at 14:50
  • Unsafe value usually has to do with sanitization, you haven't forgotten to use this function `this.domSanitizer.bypassSecurityTrustResourceUrl()` ? @MPPNBD – Ambroise Rabier Aug 12 '18 at 11:49
  • 1
    @AmbroiseRabier, Hi! I did it like you said, but have error "The PDF document could not be loaded" after building project – Pantera Jul 01 '19 at 13:19
  • @Pantera Maybe your pdf is corrupted, does the response look alike what I have pasted? – Ambroise Rabier Jul 01 '19 at 17:38
  • I tried bypassSecurityTrustResourceUrl(url), the unsafe warning is gone but the PDF file is rejected. – Haifeng Zhang Jul 17 '20 at 06:52
6

Try this:

<embed src="/assets/pdf/pr.pdf" 
    style="width: 100%;height: 500px" 
    type="application/pdf">

The Embed tag can be place anywhere in your template. Change the style attrs and src as needed.

IC4L173
  • 166
  • 1
  • 6
  • 1
    `` is deprecated. This W3 resource recommends `` https://www.w3docs.com/snippets/html/which-tag-is-better-to-use-embed-or-object.html. – James May 25 '22 at 21:31
4

Try ng2-pdfjs-viewer (https://www.npmjs.com/package/ng2-pdfjs-viewer). IMHO, it proved to be the easiest and most reliable to use so far - while building a pdf intense application. You get a full figure viewer and a lot of additional functionalities - print preview, auto download, open in new tab, zoom, scroll, go to page/named destination, rotate document etc. It works with pdf streams and physical pdf files alike. If you are building around serving pdf through web browser on angular; this package is of great help.

enter image description here

  1. Install it
    $ npm install ng2-pdfjs-viewer --save

  2. Add to app module

import { PdfJsViewerModule } from 'ng2-pdfjs-viewer'; // <-- Import PdfJsViewerModule module

@NgModule({
  imports: [
    PdfJsViewerModule // <-- Add to declarations
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }
  1. Use it.
    <ng2-pdfjs-viewer pdfSrc="mydoc.pdf"></ng2-pdfjs-viewer>
James
  • 169
  • 7
  • When I use line 3 in my html component, I get an error that says `ng2-pdfjs-viewer' is not a known element`. Can you show a bit more of your example please? – CatarinaRuna Sep 08 '21 at 10:00
3

I used ng2-pdf-viewer library to view PDF file content but when we deploy in intranet environment it can not connect link https://cdn.jsdelivr.net/npm/pdfjs-dist@2.5.207/es5/build/pdf.worker.js to get license and this library Licensed under the Apache License is not free for commercial.

I decided to use object tag with data attribute, PDF data read from server with base64 format.

I shared for whom concerned.

Read PDF content from API as

let content = DataHelper.getDataFromAPI();

When click show content button use

 showData() {
    let content = DataHelper.getDataFromAPI();

    this.pdfContent =
      URL.createObjectURL(this.b64toBlob(content, 'application/pdf')) +
      '#toolbar=0&navpanes=0&scrollbar=0&view=FitH';

    this.pdfview.nativeElement.setAttribute('data', this.pdfContent);
  }

In HTML file use object tag as

<button (click)="showData()">Show PDF Content</button>
<object #pdfview
[data]=''
type="application/pdf"
width="100%"
height="800px"
>
</object>

Link demo at https://stackblitz.com/edit/angular-ivy-tdmieb

Hien Nguyen
  • 24,551
  • 7
  • 52
  • 62
2

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>
Devidas Kadam
  • 944
  • 9
  • 19
2

If you want PDF viewer with a classy toolbar, then use ngx-extended-pdf-viewer. It has all needed options such as print, download, page navigation etc.

How to use the library:

  1. Install the library with npm i ngx-extended-pdf-viewer --save
  2. Add following scripts to your angular.json

    "scripts": [ "node_modules/ngx-extended-pdf-viewer/assets/pdf.js", "node_modules/ngx-extended-pdf-viewer/assets/pdf.worker.js", "node_modules/ngx-extended-pdf-viewer/assets/viewer.js" ]

  3. Add "NgxExtendedPdfViewerModule" to the import section of your module file

  4. Display it in your component like this:

<ngx-extended-pdf-viewer src="'assets/example.pdf'" useBrowserLocale="false"> </ngx-extended-pdf-viewer>

Dertsaf
  • 27
  • 8
0

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
}
user1438038
  • 5,821
  • 6
  • 60
  • 94
0

If you want do display a base 64 pdf you can use my component https://www.npmjs.com/package/ng2-image-viewer

It works with angular 2+ and it renders Base 64 images, URL Images and Base 64 PDFs, it's easy to implement, you just have to:

1) Run npm install ng2-image-viewer --save

2) Add these codes on your angular-cli.json file:

"styles": [
     "../node_modules/ng2-image-viewer/imageviewer.scss"
],
"scripts": [
     "../node_modules/ng2-image-viewer/imageviewer.js"
],

3) Import ImageViewerModule

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,

    // Specify your library as an import
    ImageViewerModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

4) Now you can use it as you wish:

<!-- You can now use your library component in app.component.html -->
<h1>
  Image Viewer
</h1>
<app-image-viewer [images]="['iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==', 'https://picsum.photos/900/500/?random']"
[idContainer]="'idOnHTML'"
[loadOnInit]="true"></app-image-viewer>

Here is a demo of it Ng2-Image-Viewer Showcase

For more info you can check the link above :)

Breno Prata
  • 712
  • 5
  • 10
0

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

Mahdi
  • 307
  • 6
  • 19