1

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.

ozer
  • 241
  • 2
  • 12
  • 2
    Start here: https://developer.mozilla.org/en-US/docs/Web/API/File/Using_files_from_web_applications – Randy Casburn Dec 19 '20 at 15:35
  • You can’t load something directly from the filesystem, this would be a massive security issue. So Randy is right, you have to use a file input and then you can use the fileReader API to load it. – MikeOne Dec 19 '20 at 17:26
  • When user clicked button, in my server side , I am creating pdf file. So in angular side, I should show this pdf file and also it must be printable. Is there a way without user selection option ? Thank you. – ozer Dec 19 '20 at 19:56

1 Answers1

1

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]);
  }
}
progm
  • 2,782
  • 3
  • 14
  • 32
  • I want to show pdf located like C:\Users\xx\Desktop\xyz.pdf.I want to upload from my local. – ozer Dec 19 '20 at 16:43
  • Actually I have tried what you posted but for the path like C:\Users\xx\Desktop\xyz.pdf it does not worked. – ozer Dec 19 '20 at 16:44
  • Thanks for your answer, Is there a way, doing it without input select option ? – ozer Dec 19 '20 at 19:54