Home > Web Front-end > JS Tutorial > body text

How to receive and download PDF in Angular.JS

高洛峰
Release: 2016-12-05 11:13:52
Original
1772 people have browsed it

Introduction

jsPDF is an open source library that uses Javascript language to generate PDF. You can use it in Firefox plug-ins, server-side scripts or browser scripts.

Client Safari and iPhone Safari are the best supported, followed by Opera and Firefox 3 under Windows. IE does not support it yet.

Sample code:

var doc = new jsPDF();
doc.text(20, 20, 'Hello world.');
doc.save('Test.pdf');
Copy after login

The server side works perfectly.

jsPDF is easy to use, but it does not support Chinese.

pdfmake supports Chinese, but because it also needs to introduce font files, the file size can reach more than ten MB, which is not suitable for the front end.

pdfmake is a client-server-based PDF printing solution, developed entirely based on JavaScript. Provide a powerful typesetting engine

Installation:

client-version bower install pdfmake
server-version npm install pdfmake
Copy after login

Finally, the backend is used to generate PDF, the frontend requests through the interface, the backend returns PDF Stream, and finally the frontend generates PDF through Blob and downloads it.

Solutions in AngularJS

$http.get('/receivePDFUrl', {responseType: 'arraybuffer'}) // 设置$http get请求的responseType为arraybuffer
 .success(function(data){
  var file = new Blob([data], {type: 'application/pdf'}); // 使用Blob将PDF Stream 转换为file
  var fileUrl = URL.createOjectURL(file);
  window.open(fileUrl); // 在新的页面中打开PDF
 })
Copy after login

How to set the file name of PDF

$http.get('/receivePDFUrl', {responseType: 'arraybuffer'}) // 设置$http get请求的responseType为arraybuffer
 .success(function(data){
  var file = new Blob([data], {type: 'application/pdf'}); // 使用Blob将PDF Stream 转换为file
  var fileUrl = URL.createOjectURL(file);
  var a = document.createElement('a');
  a.href = fileURL;
  a.target = '_blank';
  a.download = 'yourfilename.pdf';  
  document.body.appendChild(a);  
   a.click();
 })
Copy after login

Problems encountered

The backend uses reset api to write the interface. The front-end framework uses AngularJS, so $resouce is used to call the interface. ResponseType: arraybuffer is also set, but the generated PDF cannot be opened. In the end, just use the $http.get() method.

Compatibility issues

Due to the use of HTML5 API: Bolb, it can only support IE10+.


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!