This project is currently maintained by a single developer on his spare time. Inviting contributors and pull requests to pick-up momentum, and handle the expansive userbase and feature requests.
This is a super simple angular component for displaying pdfs inline(embedded) OR in a new tab along with a feature rich viewer. It uses mozilla's pdfjs viewer(v2.2.171) behind the scenes and supports angular version above 2.0. Extremely lightweight, easiest to integrate and use, most reliable, this library has only one dependancy (@angular/core).
viewerId
for events to work properly.Hosted Demo app showing unique use cases: https://ng2-pdfjs-viewer.azurewebsites.net
Minimalistic angular sample app: https://github.com/intbot/ng2-pdfjs-viewer/tree/master/SampleApp
Source code for the demo here : https://github.com/intbot/ng2-pdfjs-viewer/tree/master/Demo
Some of below features are unique to this component, which is unavailable in native viewer or other implementations.
viewerId
for events to work properly.
ng2-pdfjs-viewer
$ npm install ng2-pdfjs-viewer --save
And then configure it in your Angular AppModule
:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { PdfJsViewerModule } from 'ng2-pdfjs-viewer'; // <-- Import PdfJsViewerModule module
@NgModule({
declarations: [
AppComponent,
],
imports: [
BrowserModule,
PdfJsViewerModule // <-- Add to declarations
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
For several advanced options to work, you need a copy of pdfjs from this npm package.Edit your project's angular.json
file and use ng build
as described here https://angular.io/guide/workspace-config#project-asset-configuration
"assets": [
{ "glob": "**/*", "input": "node_modules/ng2-pdfjs-viewer/pdfjs", "output": "/assets/pdfjs" },
]
Please note, you may manually Copy node_modules\ng2-pdfjs-viewer\pdfjs
to your public
or asset
folder or use any copy script as part of your build process. Another method could be to use TransferWebpackPlugin
if you are using webpack(https://github.com/dkokorev90/transfer-webpack-plugin).TransferWebpackPlugin
Sample code
var TransferWebpackPlugin = require('transfer-webpack-plugin');
...
plugins: [
new TransferWebpackPlugin([
{ from: 'node_modules\ng2-pdfjs-viewer\pdfjs', to: path.join(__dirname, 'assets') }
])
]
Please note if you decide to put pdfjs
folder anywhere else other than the assets
folder, make sure you also set [viewerFolder]
property to help locate the folder.
Attribute | Description | Type | Default Value |
---|---|---|---|
[pdfSrc] |
Fully qualified path to pdf file. (For remote pdf urls over http/https, CORS should be enabled) | string |
|
PDFViewerApplication |
This public property exposes underlying PDFViewerApplication object. Make sure to access it after document is loaded. Opens up the whole world of underlying PDFJS properties and methods. Use it to customize the viewer and document experience. | object |
|
PDFViewerApplicationOptions |
This public property exposes underlying PDFViewerApplicationOptions object. Make sure to access it after document is loaded. Opens up the whole world of underlying PDFJS options. Use it to customize the viewer and document experience. | object |
|
[viewerFolder] |
Set path to pdfjs's web and build folders. |
string |
assets folder path |
[externalWindow] |
Open in new tab. Set to true to open document in a new tab |
boolean |
false |
externalWindowOptions |
External window options. For allowed comma separated values, refer to https://developer.mozilla.org/en-US/docs/Web/API/Window/open | string |
|
(onDocumentLoad) |
Event to be invoked once document is fully loaded(Must provide viewerId ). Also returns number of pages in the $event parameter. E.g. (onDocumentLoad)="testPagesLoaded($event)"" |
Function |
|
(onPageChange) |
Event to be invoked when user scrolls through pages(Must provide viewerId ). Also returns current page number user is at in the $event parameter. E.g. (onPageChange)="testPageChange($event)"" |
Function |
|
(onBeforePrint) |
Event to be invoked before document gets printed(Must provide viewerId ). E.g. (onBeforePrint)="testBeforePrint()" |
Function |
|
(onAfterPrint) |
Event to be invoked after document gets printed(Must provide viewerId ). E.g. (onAfterPrint)="testAfterPrint()" |
Function |
|
downloadFileName |
Sets/Changes the name of document to be downloaded. If the file name does not ends in .pdf , the component will automatically add it for you. |
string |
Actual name of the document |
[page] |
Show specific page. E.g page=3. You may also get/set the page number from your component using '.' notation explicitly, after document is loaded. E.g. myPdfViewer.page = 3; |
number |
1 |
[lastPage] |
Show last page of the document once it is loaded(If set to true ). If you use this option along with page option, undesired effects might occur |
boolean |
false |
nameddest |
Go to a named destination. E.g. To go to section 5.1 use like nameddest=5.1. Do not mix this option with page and lastPage options |
string |
|
zoom |
Set zoom level of document. Applicable values are auto , page-width , page-height , page-fit , 200 (As a zoom percentage), left offset (As in "auto,18,827"), top offset (As in "auto,18,127") |
string |
auto |
[print] |
Show/hide print button. Set false to hide |
boolean |
true |
[startPrint] |
Start print preview of document. This combined with externalWindow could mimic a print preview functionality just like the one in gmail. |
boolean |
|
[download] |
Show/hide download button. Set false to hide |
boolean | true |
[find] |
Show/hide search button. Set false to hide |
boolean | true |
[startDownload] |
Download document as soon as it opens. You may put this to good use. | boolean |
|
[rotatecw] |
Rotate document clock wise 90° | boolean |
|
[rotateccw] |
Rotate document anti-clock wise 90° | boolean |
|
cursor |
Type of cursor. Available options are HAND /H , SELECT /S ,ZOOM /Z . Case is irrelevant. |
SELECT /S |
|
scroll |
Sets scroll. Available options are VERTICAL /V , HORIZONTAL /H ,WRAPPED /W . Case is irrelevant. |
VERTICAL /V |
|
spread |
Sets Odd or Even spread. Available options are ODD /O , EVEN /E ,NONE /N . Case is irrelevant. |
NONE /N |
|
[fullScreen] |
Show/hide presentation(full screen) button. Set false to hide |
boolean |
true |
cursor |
Type of cursor. Available options are HAND /H , SELECT /S ,ZOOM /Z . Case is irrelevant. |
SELECT /S |
|
pagemode |
State of sidebar. Available options are none , thumbs ,bookmarks ,attachments . E.g. pagemode=attachments . |
none |
|
[openFile] |
Show/hide open file button. Set false to hide |
boolean | true |
[viewBookmark] |
Show/hide bookmark button. Set false to hide |
boolean | true |
[showSpinner] |
Show a simple css based spinner/progress before the document loads | boolean | true |
locale |
Set locale(language) of toolbar/buttons and other viewer elements. E.g. 'de-AT', 'en-GB' etc | string | browser's default language if present, otherwise en-US |
[useOnlyCssZoom] |
Instructs the viewer to use css based zoom. This will produce better zoom effect on mobile devices and tablets. | boolean | false |
errorMessage |
Custom error message | string | |
[errorAppend] |
Appends custom error message to the end of other pdfjs error messages | true |
|
[errorOverride] |
Overrides all pdfjs error messages and shows only user's custom error message | boolean | false |
[diagnosticLogs] |
Turns on all diagnostic logs to the console | boolean | true |
Please note, copy step is mandatory to enjoy all of the different options listed above. You may also avoid this step and could directly use https://github.com/mozilla/pdf.js/wiki/Setup-pdf.js-in-a-website if you wish to just use the default viewer
For your convenience a sample app using angular is available under this repository, if you would like to see it in action (Folder SampleApp). It shows many ways to configure this component for different needs.
Once your PdfJsViewerComponent is imported you can use it in your Angular application like this:
<!-- You can now use your library component in app.component.html -->
<h1>
{{title}}
</h1>
<ng2-pdfjs-viewer pdfSrc="your pdf file path"></ng2-pdfjs-viewer>
Here is a use case to download and open the pdf as byte array and open in new tab/window:Please note, pdfSrc can be a Blob or Uint8Array as wellFor [externalWindow]="true" to work, pop-ups needs to be enabled at browser level
<!-- your.component.html -->
<button (click)="openPdf();">Open Pdf</button>
<div style="width: 800px; height: 400px">
<ng2-pdfjs-viewer
#pdfViewerOnDemand
[externalWindow]="true"
[downloadFileName]="'mytestfile.pdf'"
[openFile]="false"
[viewBookmark]="false"
[download]="false"></ng2-pdfjs-viewer>
</div>
<div>
<div style="width: 800px; height: 400px">
<ng2-pdfjs-viewer #pdfViewerAutoLoad></ng2-pdfjs-viewer>
</div>
<div style="height: 600px">
<ng2-pdfjs-viewer pdfSrc="gre_research_validity_data.pdf" viewerId="MyUniqueID" (onBeforePrint)="testBeforePrint()" (onAfterPrint)="testAfterPrint()" (onDocumentLoad)="testPagesLoaded($event)" (onPageChange)="testPageChange($event)">
</ng2-pdfjs-viewer>
</div>
<!-- your.component.ts-->
import { Component, ViewChild } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
...
export class MyComponent implements OnInit {
@ViewChild('pdfViewerOnDemand') pdfViewerOnDemand;
@ViewChild('pdfViewerAutoLoad') pdfViewerAutoLoad;
...
constructor(private http: HttpClient) {
let url = "api/document/getmypdf"; // Or your url
this.downloadFile(url).subscribe(
(res) => {
this.pdfViewerAutoLoad.pdfSrc = res; // pdfSrc can be Blob or Uint8Array
this.pdfViewerAutoLoad.refresh(); // Ask pdf viewer to load/refresh pdf
}
);
}
private downloadFile(url: string): any {
return this.http.get(url, { responseType: 'blob' })
.pipe(
map((result: any) => {
return result;
})
);
}
public openPdf() {
let url = "url to fetch pdf as byte array"; // E.g. http://localhost:3000/api/GetMyPdf
// url can be local url or remote http request to an api/pdf file.
// E.g: let url = "assets/pdf-sample.pdf";
// E.g: https://github.com/intbot/ng2-pdfjs-viewer/tree/master/sampledoc/pdf-sample.pdf
// E.g: http://localhost:3000/api/GetMyPdf
// Please note, for remote urls to work, CORS should be enabled at the server. Read: https://enable-cors.org/server.html
this.downloadFile(url).subscribe(
(res) => {
this.pdfViewerOnDemand.pdfSrc = res; // pdfSrc can be Blob or Uint8Array
this.pdfViewerOnDemand.refresh(); // Ask pdf viewer to load/reresh pdf
}
);
}
Given below are examples of writing server apis(In aspnetcore c#) which returns pdfs as byte array. You can choose any server side technology as long as pdf is returned as byte array
Use case 1. As a RDLC local report viewer
[HttpGet]
[Route("MyReport")]
public IActionResult GetReport()
{
// var reportObjectList1
// var reportObjectList2
var reportViewer = new ReportViewer {ProcessingMode = ProcessingMode.Local};
reportViewer.LocalReport.ReportPath = "Reports/MyReport.rdlc";
reportViewer.LocalReport.DataSources.Add(new ReportDataSource("NameOfDataSource1", reportObjectList1));
reportViewer.LocalReport.DataSources.Add(new ReportDataSource("NameOfDataSource2", reportObjectList1));
Warning[] warnings;
string[] streamids;
string mimeType;
string encoding;
string extension;
var bytes = reportViewer.LocalReport.Render("application/pdf", null, out mimeType, out encoding, out extension, out streamids, out warnings);
return File(bytes, "application/pdf")
}
Use case 2. Return a physical pdf from server
[HttpGet]
[Route("GetMyPdf")]
public IActionResult GetMyPdf()
{
var stream = await {{__get_stream_here__}}
return File(stream, "application/pdf")); // FileStreamResult
// OR
// var bytes = await {{__get_bytes_here__}}
// return File(bytes, "application/pdf")
}
OR
[HttpGet]
[Route("GetMyPdf")]
public IActionResult GetMyPdf()
{
var pdfPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/assets/pdfjs/web/gre_research_validity_data.pdf");
byte[] bytes = System.IO.File.ReadAllBytes(pdfPath);
return File(bytes, "application/pdf");
}
Have a question? Ask questions and find answers on Stack overflow.
AngularJS angular-pdfjs-viewer
MIT © Code Hippie
最近项目中有一个需求,要打开某编辑界面的时候,默认打开pdf已设置过得页码,百度的时候有几个答案是直接改viewer.js的源码来实现这个需求,也有的是通过canvas来实现的,但今天我发现了一个最简单的方法来实现: 就是直接在地址后面加上#page=指定的页码 就可以了 <iframe ref="iframe" v-if="pdfSrc != ''" :src="'/static/pdf/web
pdfjs-dist 是一个通用的 PDF.js 构建库。这是 PDF.js 源码的预先构建版本,可以通过构建脚本自动生成PDF.js。 pdf.js 是一个技术原型主要用于在 HTML5 平台上展示 PDF 文档,无需任何本地技术支持。我们的目标是创建一个通用的基于 web 标准的平台,并支持分析和展示 PDFs。
Ember PDFJS Addon This addon will provide some useful components for viewing and interacting with PDF documents to your ember-cli project. This addon unites the Ember framework ecosystem and the PDFJS
Angular 5+ PDF Viewer PDF Viewer Component for Angular 5+ Demo page https://vadimdez.github.io/ng2-pdf-viewer/ Stackblitz Example https://stackblitz.com/edit/ng2-pdf-viewer Blog post https://medium.co
�� ng2-tree �� Usage �� Demo �� API tree [tree] Load children asynchronously Load children using ngrx (or any redux-like library) Configure node via TreeModelSettings [settings] Tree class events (nod
Angular 2 Drag-and-Drop Angular 2 Drag-and-Drop without dependencies. Follow me to be notified about new releases. Some of these APIs and Components are not final and are subject to change! Transpilat
ng2-translate 是 Angular 2 的 i18n 库。 简单示例:https://stackblitz.com/github/ngx-translate/example