简体   繁体   中英

How to Show PDF file from local in Angular?

I have angular web application and I need to show and print PDF which located in my computer. How to show PDF file with print options? I want to show pdf located like C:\Users\xx\Desktop\xyz.pdf.

<iframe
    src="https://drive.google.com/viewerng/viewer?embedded=true&url=http://infolab.stanford.edu/pub/papers/google.pdf#toolbar=0&scrollbar=0"
    frameBorder="0"
    scrolling="auto"
    height="100%"
    width="100%"
></iframe>

I have tried iframe and other tools, but as I have to show from my local, it gives an error.

You can use ng2-pdf-viewer package.

Steps:

Import PdfViewerModule to your module:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app/app.component';

import { PdfViewerModule } from 'ng2-pdf-viewer';
 
@NgModule({
  imports: [BrowserModule, PdfViewerModule],
  declarations: [AppComponent],
  bootstrap: [AppComponent]
})

class AppModule {}

After use this component in your tempalte:

import { Component } from '@angular/core';
 
@Component({
  selector: 'example-app',
  template: `
  <pdf-viewer [src]="pdfSrc"
              [render-text]="true"
              style="display: block;"
  ></pdf-viewer>
  `
})
export class AppComponent { }

Render local PDF file

In your html template add input:

<input (change)="onFileSelected()" type="file" id="file">

and then add onFileSelected method to your component:

onFileSelected() {
  let $img: any = document.querySelector('#file');

  if (typeof (FileReader) !== 'undefined') {
    let reader = new FileReader();

    reader.onload = (e: any) => {
      this.pdfSrc = e.target.result;
    };

    reader.readAsArrayBuffer($img.files[0]);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM