Home > Article > Web Front-end > How to receive and download PDF in Angular.JS
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');
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
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 })
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(); })
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+.