Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

An angular component for PDFJS and ViewerJS (Supports all versions of angular)

NotificationsYou must be signed in to change notification settings

intbot/ng2-pdfjs-viewer

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

downloadsnpm version

🎉 Thanks a ton to the community - We are talking Downloads in millions now!!!

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 from 2.0. Extremely lightweight, easiest to integrate and use, most reliable, this library has only one dependancy (@angular/core).

What is new?

  1. Direct access to underlying viewer - Exposed PDFViewerApplication and PDFViewerApplicationOptions objects opens a whole world of customizable PDFJS and ViewerJS properties and methods, allowing to change them programmatically; thus producing a unique viewer experience.
  2. Dynamic page number - Getter/Setter added for page number. Change page number after document loaded, or access current page in parent component.
  3. Support for events - You may now register several events such as document load, page change, before print, after print etc. Please make sure to provideviewerId for events to work properly.

Tutorials, Demos & Examples

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

Features

Some of below features are unique to this component, which is unavailable in native viewer or other implementations.
✔️Open pdf in new window 🌐 - Opens pdf viewer in new window. Also, you may set all allowable external window options.
✔️Direct access to underlying viewer 👨‍💻👩‍💻- Exposed PDFViewerApplication and PDFViewerApplicationOptions objects opens a whole world of customizable PDFJS and ViewerJS properties and methods, allowing to change them programmatically; thus producing a unique viewer experience.
✔️Embed pdf 🗎 - Embeds viewer and pdf inside your web page/component.
✔️Blob and byte arrays 🔟 - Have pdf as a byte array? Still works.
✔️Events ⚡ - Catch events such as document loaded, page change, before/after print etc.Please make sure to provideviewerId for events to work properly.
✔️Print preview 🖨️ - You can set the pdf to open in a new tab or another browser window and provide an immediate print preview, A use case will be a 'Print' button opening pdf in new window with print dialog.
✔️Defaults - There are a ton of built in functionality Mozilla's viewer supports; such as print, download, bookmark, fullscreen, open file, zoom, search, pan, spread, navigate, attachments etc which is also available as-is in this viewer. Not mentioning them individually.
✔️Auto download 💾 - This option allows you to download the pdf file to user device automatically without manually invoking the download.
✔️Auto rotate 🔄 - Rotate the documentclockwise oranti-clockwise 90° (+/- 90°) just before displaying. Useful if the document is misaligned.
✔️Language 🌍 - Set the language of your choice to the viewer controls.
✔️Custom error ❌ - Hate the defaults pdfjs errors, use this feature to override or append to it.
✔️Side bar 📎 - Open and show the sidebar with relevant information. E.g. Show attachments.
✔️Smart device friendly zoom 📱 - A better zooming experience on small devices.
✔️Progress spinner ⏳ - An optional spinner which displays before document renders.
✔️Show/Hide controls 👻 - Do not want users to see specific controls (E.g. download button). Use relevant features to remove controls from viewer.
✔️Navigate ⏩ - Navigate the document using page number, section, or even directly jump to last page if you are expecting a signature from user.
✔️Zoom 🔍 - Several zoom methods, auto, percentage (E.g. 150%), page-with/height, fit page etc. with ability to set offset.
✔️Cursor 👆 - Love the age old hand cursor 👆 on your pdf? You got it.
✔️Change file name - You may set the file name of download to a different one, if user chooses to download.
✔️Scroll 📜 - Changes the scroll to your choice. Even wrapped scrolling is supported.
✔️Spread - Allows you to change spread to odd or even.

Open in a new tab/ external window

angular pdfjs viewer in new window

Embed pdf into any angular component/page

angular pdfjs viewer embedded

Installation

Step 1: Installng2-pdfjs-viewer

$ npm install ng2-pdfjs-viewer --save

And then configure it in your AngularAppModule:

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],})exportclassAppModule{}

Step 2: Copy task for pdfjs

For several advanced options to work, you need a copy of pdfjs from this npm package.Edit your project'sangular.json file and useng build as described herehttps://angular.io/guide/workspace-config#assets-configuration

"assets": [  {"glob":"**/*","input":"node_modules/ng2-pdfjs-viewer/pdfjs","output":"/assets/pdfjs" },]

Please note, you must manually Copynode_modules\ng2-pdfjs-viewer\pdfjs to yourpublic orasset folder or use any copy script as part of your build process. Another method could be to useTransferWebpackPlugin if you are using webpack(https://github.com/dkokorev90/transfer-webpack-plugin).
TransferWebpackPlugin Sample code

varTransferWebpackPlugin=require('transfer-webpack-plugin');...plugins:[newTransferWebpackPlugin([{from:'node_modules\ng2-pdfjs-viewer\pdfjs',to:path.join(__dirname,'assets')}])]

Please note if you decide to putpdfjs folder anywhere else other than theassets folder, make sure you also set[viewerFolder] property to help locate the folder.

Options

AttributeDescriptionTypeDefault Value
[pdfSrc]Fully qualified path to pdf file. (For remote pdf urls over http/https, CORS should be enabled)string
PDFViewerApplicationThis 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
PDFViewerApplicationOptionsThis 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 topdfjs'sweb andbuild folders.stringassets folder path
[externalWindow]Open in new tab. Set totrue to open document in a new tabbooleanfalse
externalWindowOptionsExternal window options. For allowed comma separated values, refer tohttps://developer.mozilla.org/en-US/docs/Web/API/Window/openstring
(onDocumentLoad)Event to be invoked once document is fully loaded(Must provideviewerId). 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 provideviewerId). 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 provideviewerId). E.g.(onBeforePrint)="testBeforePrint()"Function
(onAfterPrint)Event to be invoked after document gets printed(Must provideviewerId). E.g.(onAfterPrint)="testAfterPrint()"Function
downloadFileNameSets/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.stringActual name of the document
[page]Show specific page. E.gpage=3. You may also get/set the page number from your component using '.' notation explicitly, after document is loaded. E.g.myPdfViewer.page = 3;number1
[lastPage]Show last page of the document once it is loaded(If set totrue). If you use this option along withpage option, undesired effects might occurbooleanfalse
nameddestGo to a named destination. E.g. To go to section5.1 use like nameddest=5.1. Do not mix this option withpage andlastPage optionsstring
zoomSet zoom level of document. Applicable values areauto,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")stringauto
[print]Show/hide print button. Setfalse to hidebooleantrue
[startPrint]Start print preview of document. This combined withexternalWindow could mimic a print preview functionality just like the one in gmail.boolean
[download]Show/hide download button. Setfalse to hidebooleantrue
[find]Show/hide search button. Setfalse to hidebooleantrue
[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
cursorType of cursor. Available options areHAND/H,SELECT/S,ZOOM/Z. Case is irrelevant.SELECT/S
scrollSets scroll. Available options areVERTICAL/V,HORIZONTAL/H,WRAPPED/W. Case is irrelevant.VERTICAL/V
spreadSets Odd or Even spread. Available options areODD/O,EVEN/E,NONE/N. Case is irrelevant.NONE/N
[fullScreen]Show/hide presentation(full screen) button. Setfalse to hidebooleantrue
cursorType of cursor. Available options areHAND/H,SELECT/S,ZOOM/Z. Case is irrelevant.SELECT/S
pagemodeState of sidebar. Available options arenone,thumbs,bookmarks,attachments. E.g.pagemode=attachments.none
[openFile]Show/hide open file button. Setfalse to hidebooleantrue
[viewBookmark]Show/hide bookmark button. Setfalse to hidebooleantrue
[showSpinner]Show a simple css based spinner/progress before the document loadsbooleantrue
localeSet locale(language) of toolbar/buttons and other viewer elements. E.g. 'de-AT', 'en-GB' etcstringbrowser's default language if present, otherwiseen-US
[useOnlyCssZoom]Instructs the viewer to use css based zoom. This will produce better zoom effect on mobile devices and tablets.booleanfalse
errorMessageCustom error messagestring
[errorAppend]Appends custom error message to the end of other pdfjs error messagestrue
[errorOverride]Overrides all pdfjs error messages and shows only user's custom error messagebooleanfalse
[diagnosticLogs]Turns on all diagnostic logs to the consolebooleantrue

Please note, copy step is mandatory to enjoy all of the different options listed above. You may also avoid this step and could directly usehttps://github.com/mozilla/pdf.js/wiki/Setup-pdf.js-in-a-website if you wish to just use the default viewer

Usage

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-viewerpdfSrc="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><divstyle="width: 800px; height: 400px">  <ng2-pdfjs-viewer    #pdfViewerOnDemand    [externalWindow]="true"    [downloadFileName]="'mytestfile.pdf'"    [openFile]="false"    [viewBookmark]="false"    [download]="false"></ng2-pdfjs-viewer></div><div><divstyle="width: 800px; height: 400px">  <ng2-pdfjs-viewer #pdfViewerAutoLoad></ng2-pdfjs-viewer></div><divstyle="height: 600px">  <ng2-pdfjs-viewerpdfSrc="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';...exportclassMyComponentimplementsOnInit{  @ViewChild('pdfViewerOnDemand')pdfViewerOnDemand;  @ViewChild('pdfViewerAutoLoad')pdfViewerAutoLoad;  ...constructor(privatehttp:HttpClient){leturl="api/document/getmypdf";// Or your urlthis.downloadFile(url).subscribe((res)=>{this.pdfViewerAutoLoad.pdfSrc=res;// pdfSrc can be Blob or Uint8Arraythis.pdfViewerAutoLoad.refresh();// Ask pdf viewer to load/refresh pdf});}privatedownloadFile(url:string):any{returnthis.http.get(url,{responseType:'blob'}).pipe(map((result:any)=>{returnresult;}));}publicopenPdf(){leturl="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.htmlthis.downloadFile(url).subscribe((res)=>{this.pdfViewerOnDemand.pdfSrc=res;// pdfSrc can be Blob or Uint8Arraythis.pdfViewerOnDemand.refresh();// Ask pdf viewer to load/reresh pdf});}

Additional Information

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")]publicIActionResultGetReport(){// var reportObjectList1// var reportObjectList2varreportViewer=newReportViewer{ProcessingMode=ProcessingMode.Local};reportViewer.LocalReport.ReportPath="Reports/MyReport.rdlc";reportViewer.LocalReport.DataSources.Add(newReportDataSource("NameOfDataSource1",reportObjectList1));reportViewer.LocalReport.DataSources.Add(newReportDataSource("NameOfDataSource2",reportObjectList1));Warning[]warnings;string[]streamids;stringmimeType;stringencoding;stringextension;varbytes=reportViewer.LocalReport.Render("application/pdf",null,outmimeType,outencoding,outextension,outstreamids,outwarnings);returnFile(bytes,"application/pdf")}

Use case 2. Return a physical pdf from server

[HttpGet][Route("GetMyPdf")]publicIActionResultGetMyPdf(){varstream=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(){varpdfPath=Path.Combine(Directory.GetCurrentDirectory(),"wwwroot/assets/pdfjs/web/gre_research_validity_data.pdf");byte[]bytes=System.IO.File.ReadAllBytes(pdfPath);returnFile(bytes,"application/pdf");}

E-Signature Support

Original issue -> PDF.JS is not able to load the signature in the pdf if that is done via the anyE-Signature tool.

Resolution of the issue -> To support this feature need to comment/remove the below code from pdf.worker.js file and file path i.e. lib\pdfjs\build\pdf.worker.js

Original issue code

if(data.fieldType==="Sig"){data.fieldValue=null;_this3.setFlags(_util.AnnotationFlag.HIDDEN);}

Resoultion code

if(data.fieldType==="Sig"){data.fieldValue=null;_this3.setFlags(_util.AnnotationFlag.HIDDEN);//remove or comment this line}

Stack Overflow Support

Have a question? Ask questions and find answers on Stack overflow.

Stack Overflow

Looking for old AngularJS? - The below library is quite useful

AngularJSangular-pdfjs-viewer

License

**Apache V2 License -https://www.apache.org/licenses/LICENSE-2.0


[8]ページ先頭

©2009-2025 Movatter.jp