【问题标题】:Angular 2 how to display .pdf fileAngular 2如何显示.pdf文件
【发布时间】:2017-09-02 09:44:12
【问题描述】:

我有一个 angular2 应用程序,我希望用户能够在浏览器中下载并打开一个 pdf 文件。

有我可以使用的 angular2 模块或组件吗?

【问题讨论】:

  • 你试过<object></object>
  • 我已经开始收集pdfviewer.net/alternatives 上的所有可用选项。诚然,目前,该网站的大部分内容都专门用于我自己的库(ngx-extended-pdf-viewer)。我将很快深入介绍替代方案。

标签: angular pdf


【解决方案1】:

你看过这个模块https://www.npmjs.com/package/ng2-pdf-viewer吗?

记得在模块中这样声明

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 { }

【讨论】:

  • 是的。但它不工作。当我在 html 文件上使用此组件的选择器名称时,它会出错。他们还有其他组件或模块吗??
  • 能否请您发布代码 sn-p 和您收到的错误?
  • 错误是:“pdf-viewer”元素不是 angular2 组件。
  • 您是否在模块声明中添加了“pdf-viewer”?
  • 好的,我刚刚在本地设置并让它工作。所以我很确定这个模块可以工作。我很高兴用一个示例 pdf 来推动这个例子。或者,您是否可以共享组件和模块的代码的 sn-p?
【解决方案2】:

ng2-pdf-viewer 工作得很好,但我想要像这个页面上的 pdf 显示:https://pdfobject.com/static.html

遗憾的是,我有一个 pdf 流,而不是直接的 pdf(链接末尾没有 .pdf) 喜欢:https://***********.idshost.fr/ws/********xfer/ws/download/3ca3dfa2-e89d-4f98-bcf2-55ad62bacfc6

回复是这样的(只贴了一部分):

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

这样的标题

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

我听说将内容处置更改为内联而不是附件会使浏览器尝试打开它而不是下载,我无权访问服务器所以没有尝试。

我的 pdf 不显示、出现空白视图或错误“加载失败 pdf 文档”。(但它适用于一些罕见的 pdf whit ,但不适用于

终于设法找到了一些有用的东西,也许它可以帮助一些人,这里是代码(angular2):

.ts 文件


    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 文件(其中任何一个都可以,iframe 对我来说有更多的功能,比如 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>

希望对某人有所帮助!

【讨论】:

  • 这比 pdf 查看器要好得多。对我来说,所有 3 种解决方案都提供打印。很高兴知道它们之间的利弊。
  • 我收到以下错误错误:资源 URL 上下文中使用的不安全值。谁能帮帮我
  • 不安全值通常与消毒有关,您没有忘记使用此功能this.domSanitizer.bypassSecurityTrustResourceUrl()? @MPPNBD
  • @AmbroiseRabier,嗨!我按照你说的做了,但是在构建项目后出现错误“无法加载 PDF 文档”
  • @Pantera 也许您的 pdf 文件已损坏,回复看起来像我粘贴的吗?
【解决方案3】:

试试这个:

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

嵌入标签可以放置在模板中的任何位置。 根据需要更改样式 attrs 和 src。

【讨论】:

    【解决方案4】:

    试试 ng2-pdfjs-viewer (https://www.npmjs.com/package/ng2-pdfjs-viewer)。恕我直言,它被证明是迄今为止最简单和最可靠的使用 - 同时构建了一个 pdf 密集型应用程序。您可以获得完整的图形查看器和许多附加功能 - 打印预览、自动下载、在新选项卡中打开、缩放、滚动、转到页面/命名目标、旋转文档等。它适用于 pdf 流和物理 pdf 文件。如果您正在通过网络浏览器在 Angular 上提供 pdf 服务;这个包很有帮助。

    1. 安装它
      $ npm install ng2-pdfjs-viewer --save

    2. 添加到应用模块

    import { PdfJsViewerModule } from 'ng2-pdfjs-viewer'; // <-- Import PdfJsViewerModule module
    
    @NgModule({
      imports: [
        PdfJsViewerModule // <-- Add to declarations
      ],
      bootstrap: [AppComponent]
    })
    export class AppModule { }
    
    1. 使用它。
      &lt;ng2-pdfjs-viewer pdfSrc="mydoc.pdf"&gt;&lt;/ng2-pdfjs-viewer&gt;

    【讨论】:

    • 当我在我的 html 组件中使用第 3 行时,我收到一条错误消息,显示为 ng2-pdfjs-viewer' is not a known element。你能多展示一些你的例子吗?
    【解决方案5】:

    我使用 ng2-pdf-viewer 库来查看 PDF 文件内容,但是当我们部署在 Intranet 环境中时,它无法连接链接 https://cdn.jsdelivr.net/npm/pdfjs-dist@2.5.207/es5/build/pdf.worker.js 来获取许可证,并且这个库在 Apache 许可证下获得许可 不是免费的商业

    我决定使用 object tagdata 属性,从服务器读取 base64 格式的 PDF 数据。

    我为关心的人分享。

    从 API 读取 PDF 内容为

    let content = DataHelper.getDataFromAPI();
    

    点击显示内容按钮时使用

     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);
      }
    

    在 HTML 文件中使用对象标签作为

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

    https://stackblitz.com/edit/angular-ivy-tdmieb链接演示

    【讨论】:

      【解决方案6】:

      试试这个。 请用您的实际路径和文件名更改filename.pdf

       <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>
      

      【讨论】:

        【解决方案7】:

        如果您想要带有优雅工具栏的 PDF 查看器,请使用ngx-extended-pdf-viewer。 它具有所有需要的选项,例如打印、下载、页面导航等。

        如何使用库:

        1. 使用 npm i ngx-extended-pdf-viewer --save 安装库
        2. 将以下脚本添加到您的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. 将“NgxExtendedPdfViewerModule”添加到模块文件的导入部分

        4. 像这样在你的组件中显示它:

        &lt;ngx-extended-pdf-viewer src="'assets/example.pdf'" useBrowserLocale="false"&gt; &lt;/ngx-extended-pdf-viewer&gt;

        【讨论】:

          【解决方案8】:

          您可以使用 File Viewer for Angular 包。

          此软件包支持 pdfpngjpegmp4 格式。

          安装:

          npm i @taldor-ltd/angular-file-viewer ng2-pdf-viewer
          

          用法:

          AngularFileViewerModule 添加到模块的导入中

          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);
          

          然后在你的组件中使用它

          (PDF 样本)

          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

          【讨论】:

            【解决方案9】:

            它对我有用。我的错误是将responseType:ResponseContentType.ArrayBuffer 放在标题中,但它不在里面:

            {
                 headers: new Headers({
                    "Access-Control-Allow-Origin": "*",
                    "Authorization": "Bearer "
                 }),
                 responseType:ResponseContentType.ArrayBuffer // YOU NEED THIS LINE
            }
            

            【讨论】:

              【解决方案10】:

              如果您想显示 base 64 pdf,可以使用我的组件 https://www.npmjs.com/package/ng2-image-viewer

              它适用于 angular 2+,它可以渲染 Base 64 图像、URL 图像和 Base 64 PDF,它很容易实现,您只需:

              1) 运行npm install ng2-image-viewer --save

              2) 在 angular-cli.json 文件中添加这些代码:

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

              3) 导入 ImageViewerModule

              @NgModule({
                declarations: [
                  AppComponent
                ],
                imports: [
                  BrowserModule,
              
                  // Specify your library as an import
                  ImageViewerModule
                ],
                providers: [],
                bootstrap: [AppComponent]
              })
              export class AppModule { }
              

              4) 现在你可以随心所欲地使用它了:

              <!-- 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>
              

              这是它的演示Ng2-Image-Viewer Showcase

              有关更多信息,您可以查看上面的链接:)

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 2016-08-30
                • 2018-03-26
                • 1970-01-01
                • 2019-02-15
                • 1970-01-01
                • 2020-02-11
                • 2016-07-13
                • 2017-02-18
                相关资源
                最近更新 更多