pdf流文件的展示、下载、打印

背景:合同(后台返回pdf流文件)展示、下载、打印,基于angular4

场景区分:

1、checkout页面 —— post接口,入参为offering、shippingInfo、invoice等(body),返回生成合同的pdf流文件;

2、orderList、orderDetail页面 —— get接口,入参contentId(生成合同在内容管理保存对应的id,url),返回对应合同的pdf流文件。

需求补充说明:

在一个弹出dialog,合同展示在中间部分,footer部分为 下载、打印等按钮。

实现核心:

1、展示:

1> package.json中

  "dependencies": {

   "ng2-pdf-viewer": "^3.0.8",

   "pdfjs-dist": "^1.9.426" 

}

2> html

展示:

  <pdf-viewer *ngIf ="contract.stc" [src]="contract.src" [render-text]="true"  (after-load-complete)="afterLoadComplete($event)" (error)="loadContractError($event)" ></pdf-viewer>

下载:

  <a id="contract_download" class="fl mar1d5r mat6" [href]=‘sanitize(contract.src)‘ [download]="contract.name" *ngIf="contract.isLoadSuccess" >
    <svg class="hlds-icon fillWhite icon2r">
      <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="./assets/theme/default/icons/omniIcon-sprite/svg/symbols.svg#downLoad"></use>
    </svg>
  </a>

打印:
  <a class="fl mat6" (click)="print()" *ngIf="contract.isLoadSuccess">
    <svg class="hlds-icon fillWhite icon2r" >
      <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="./assets/theme/default/icons/omniIcon-sprite/svg/symbols.svg#print"></use>
    </svg>
  </a>
  <iframe #iframe [src]="contract.url" style=‘display:none;‘ *ngIf="contract.isLoadSuccess" ></iframe>

3>ts文件

  import { Component, Input, Output, EventEmitter, OnInit, OnChanges, SimpleChanges, ViewChild, ElementRef } from ‘@angular/core‘;
  import { DomSanitizer, SafeResourceUrl } from ‘@angular/platform-browser‘;
  import { Router, ActivatedRoute, ParamMap } from ‘@angular/router‘;

  import { ConstantService } from ‘../../../../service/constant.service‘;
  import { MessageService } from "../../../../service/message.service";
  import { NormalHttpService } from "../../../../service/normal-http.service";

  import { SmartrecCommonService } from ‘../../../bizcommon/service/smartrec.service‘;
  import { OrderService } from ‘../../service/order.service‘;

  declare var $: any;

  @Component({
    selector: ‘app-order-contract‘,
    templateUrl: ‘./contract.component.html‘,
    styleUrls: [‘./contract.component.css‘]
   })
  export class ContractComponent implements OnInit, OnChanges {
    /*contractInfo : any = {
      isGenerated : true,
      orderId: ‘‘,
      orderInfo : {} //the param that generate contract
    }*/
  @ViewChild(‘iframe‘) iframe: ElementRef;
  @Input() contractInfo : any ;
  @Output() acceptContractState = new EventEmitter<any>();

  contract : any = {
    src : ‘‘,
    url : ‘‘,
    totalPage : 1,
    page : 1,
    isLoading : true,
    isLoadSuccess: false
  }

  constructor(
   private router: Router,
   private sanitizer: DomSanitizer,
   private messageService: MessageService,
   private normalHttpService: NormalHttpService,
   private smartrecCommonService: SmartrecCommonService,
   private orderService: OrderService
  ) { }

  ngOnInit() {
  }

  ngOnChanges(change: SimpleChanges) {
    if(this.contractInfo && this.contractInfo.isGenerated && change.contractInfo.currentValue.orderInfo){
     this.contract.isLoadSuccess = false;
     this.generateContract();
      }
    if(this.contractInfo && !this.contractInfo.isGenerated && this.contractInfo.orderId) {
      this.queryContract();
    }
  }

  generateContract() {
   if(!this.contract.isLoadSuccess){
    this.contract.src = ‘‘;
    this.contract.isLoading = true;
    let header = this.normalHttpService.expandHeader({}, true);
    let url = this.normalHttpService.makeRequestUrl(`/order/order/${ConstantService.API_VERSION}/contract`);
    let xhr = new XMLHttpRequest();
    xhr.open("POST", url, true);
    xhr.responseType = "blob";
    for(let key in header) {
      xhr.setRequestHeader(key, header[key]);
    }
    xhr.send(JSON.stringify(this.contractInfo.orderInfo));
    xhr.onreadystatechange = function () {
    if (xhr.readyState == 4 && xhr.status == 200) {
      let blob = new Blob([xhr.response], {type: ‘application/pdf‘});
      this.contract.src = URL.createObjectURL(blob);
      this.contract.name = ‘contract.pdf‘;
      this.contract.url = this.sanitizer.bypassSecurityTrustResourceUrl(this.contract.src);
    }
  }.bind(this);
  }
}

  queryContract() {
   this.contract.src = ‘‘;
   this.orderService.queryContractId(this.contractInfo.orderId).then((res) => {
    if (res.code !== 0) {
      this.messageService.errorAlert(‘Query contractId is failed !‘);
      return;
    }
    if (res.data.contentId) {
      this.contract.src = this.smartrecCommonService.getContentUrlById(res.data.contentId);
    }
   })
  }

  afterLoadComplete(pdf: any) {
    this.contract.totalPage = pdf.pdfInfo.numPages;
    this.contract.isLoading = false;
    this.contract.isLoadSuccess = true;
  }

  loadContractError(event: any) {
    this.contract.isLoading = false;
    this.contract.isLoadSuccess = false;
    this.messageService.errorAlert(‘Contract failed to load !‘);
  }

  agree() {
    this.acceptContractState.emit({
      isAgree : true,
      isLoadSuccess : this.contract.isLoadSuccess
    })
  }

  disAgree() {
    this.acceptContractState.emit({
      isAgree : false,
      isLoadSuccess : this.contract.isLoadSuccess
    })
  }

  print() {
    let getMyFrame = this.iframe.nativeElement.contentWindow || this.iframe.nativeElement.contentDocument;
    getMyFrame.print();
  }

  changePage(event) {
   const pageHeight = $(‘.ng2-pdf-viewer-container‘).height() / this.contract.totalPage;
   this.contract.page = Math.ceil($(event.target).scrollTop()/pageHeight);
  }

  sanitize(url:string){
    return this.sanitizer.bypassSecurityTrustUrl(url);
  }
}

参考:
1.https://github.com/VadimDez/ng2-pdf-viewer //展示打印思路

2.https://stackoverflow.com/questions/38457662/iframe-inside-angular2-component-property-contentwindow-does-not-exist-on-typ/50508477 //pdf局部打印思路

3.http://kriscan.oschina.io/blog/2017/05/26/20170526/  //链接安全问题解决




原文地址:https://www.cnblogs.com/lyue1404/p/9342518.html

时间: 2024-08-21 18:31:50

pdf流文件的展示、下载、打印的相关文章

在.net Core 使用PDF模板文件生成PDF文件,代替WEB打印控件!

这几天找WEB打印控件,要么收费的,要么免费的只能在IE里用! 我只想简单的打个标签纸!百度2天,看到一老兄说可以用PDF,然后又开始百度..找到了一篇文章 http://www.jianshu.com/p/d518d0988621    本文代码全部摘抄至这篇文章,发文只为记录! 不同的是我导入的库是iTextSharp.LGPLv2.Core.Fix 开始 一.先用word制作好模板文件,标签打印的话注意页边距,然后另存为PDF格式文件 二.然后下载adobe acrobat pro,创建时

184、HTML中,PDF版报告的展示和下载

HTML中,PDF版报告的展示和下载 相关搜索:脚本编辑器:$scope.r_g_company.reportPage:文件上传中... 1.展示,在HTML中,划定一个区域,用做PDF版报告的展示 (1)封面内容:一个单独的HTML,内有动态数据插入 (2)展示内容:另一个单独的HTML,内有动态数据插入 (3)前端将配置的动态数据和起止时间参数传给后台(步骤一),后台将接收到的数据和自己过滤出来的数据插入到(1)和(2)里,然后将它俩拼成一个PDF文件返给前端.供前端下载,同时还将这个PDF

java文本、表格word转换生成PDF加密文件代码下载

原文:java文本.表格word转换生成PDF加密文件代码下载 代码下载地址:http://www.zuidaima.com/share/1550463239146496.htm 这个实现了PDF加密功能,和一些基本的问题. java文本.表格word转换生成PDF加密文件代码下载,布布扣,bubuko.com

java读取某个目录下所有文件并通过el表达式将相关文件信息展示出来,js提供页面搜索及查看下载功能

从服务器上读取某个目录下的文件  将文件名 文件修改日期   及文件 大小展示在前台  并可以查看及下载 第一步:读取文件目录下的文件,并将文件按时间由大到小排列 public ArrayList<File> getLogs() { // TODO Auto-generated method stub ArrayList<File>  tomcatLogs = new ArrayList<File>(); File path = new File(""

SpringMVC文件上传下载

在Spring MVC的基础框架搭建起来后,我们测试了spring mvc中的返回值类型,如果你还没有搭建好springmvc的架构请参考博文->http://www.cnblogs.com/qixiaoyizhan/p/5819392.html 今天我们来讲讲spring mvc中的文件上传和下载的几种方法. 首先附上文件目录->我们需要配置的我做了记号-> 一.文件上传 首先为了方便后续的操作,以及精简代码,我们在Utils包下封装一个文件上传下载的帮助类: Files_Helper

iOS网络-NSURLSessionDataTask大文件离线断点下载

什么叫离线断点下载,就是用户下载中关闭程序重新打开可以继续下载 代码实现如下: #import "ViewController.h" @interface ViewController ()<NSURLSessionDataDelegate> //输出流 @property (nonatomic, strong) NSOutputStream *stream ; //Task对象 @property (nonatomic, strong) NSURLSessionDataT

28、java文件上传下载、邮件收发

文件上传下载 前台: 1. 提交方式:post 2. 表单中有文件上传的表单项: <input type="file" /> 3. 指定表单类型: 默认类型:enctype="application/x-www-form-urlencoded" 文件上传类型:multipart/form-data FileUpload 文件上传功能开发中比较常用,apache也提供了文件上传组件! FileUpload组件: 1. 下载源码 2. 项目中引入jar文件

怎么修改PDF文件、PDF格式文件怎么修改!

PDF格式文件虽然使用起来是非常的方便简单,但是这种文件却非常的难编辑,这是为什么呢.原因是PDF文件的格式比较特殊,编辑这种文件需要使用到专业的软件,下面我们就一起来学习了解一下怎么修改PDF这种文件吧! 迅捷PDF编辑器可以对PDF文件进行图片替换.文字修改.绘画标注.页面旋转.输出与打印等.是PDF编辑器果较好的一款PDF编辑器工具,并且安装运行不需要繁琐的设置过程. 1.网上搜索,找到相关资源下载迅捷pdf编辑器,安装后打开至主界面. 2.通过点击栏目上方工具栏中的"文件-打开"

最详细的文件上传下载

在Web应用系统开发中,文件上传和下载功能是非常常用的功能,今天来讲一下JavaWeb中的文件上传和下载功能的实现. 对于文件上传,浏览器在上传的过程中是将文件以流的形式提交到服务器端的,如果直接使用Servlet获取上传文件的输入流然后再解析里面的请求参数是比较麻烦,所以一般选择采用apache的开源工具common-fileupload这个文件上传组件.这个common-fileupload上传组件的jar包可以去apache官网上面下载,也可以在struts的lib文件夹下面找到,stru