jsPDF生成pdf文件

需求:前端从服务器获取图片信息,然后将图片插入到pdf中并下载

使用的是jsPDF.js  官方文档地址:https://rawgit.com/MrRio/jsPDF/master/docs/module-addImage.html#~addImage

需要解释的是myloadImageFile 这个方法,这个是jsPDF提供的一个方法,但是他的if判断如果有跨域请求就不去获取文件了

因为我是本地调试协议是file:// 所以把这个方法拉出来重写了下。

<!DOCTYPE html>
<html>
<head lang="en"><meta charset="UTF-8">
</head>
<body><script type="text/javascript" src="../disk/jspdf.debug.js"></script>
<button id="export-pdf">export pdf</button><form class="form"><label>Page size </label><select id="format"><option value="a0">A0 (slow)</option><option value="a1">A1</option><option value="a2">A2</option><option value="a3">A3</option><option value="a4" selected>A4</option><option value="a5">A5 (fast)</option></select></form>
<script type="text/javascript">myloadImageFile = function (path, sync, callback) {sync = sync || true;callback = callback || function () {};var isNode = Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]';var xhrMethod = function xhrMethod(url, sync, callback) {var req = new XMLHttpRequest();var byteArray = [];var i = 0;var sanitizeUnicode = function sanitizeUnicode(data) {var dataLength = data.length;var StringFromCharCode = String.fromCharCode;//Transform Unicode to ASCIIfor (i = 0; i < dataLength; i += 1) {byteArray.push(StringFromCharCode(data.charCodeAt(i) & 0xff));}return byteArray.join("");};req.open('GET', url, !sync);// XHR binary charset opt by Marcus Granado 2006 [http://mgran.blogspot.com]req.overrideMimeType('text\/plain; charset=x-user-defined');if (sync === false) {req.onload = function () {return sanitizeUnicode(this.responseText);};}req.send(null);if (req.status !== 200) {console.warn('Unable to load file "' + url + '"');return;}if (sync) {return sanitizeUnicode(req.responseText);}};//we have a browser and probably no CORS-Problem
//if ((typeof window === 'undefined' ? 'undefined' : _typeof(window)) !== undefined && (typeof location === 'undefined' ? 'undefined' : _typeof(location)) === "object" && location.protocol.substr(0, 4) === "http") {return xhrMethod(path, sync, callback);//	}};var dims = {a0: [1189, 841],a1: [841, 594],a2: [594, 420],a3: [420, 297],a4: [297, 210],a5: [210, 148]};var exportButton = document.getElementById('export-pdf');exportButton.addEventListener('click', function() {exportButton.disabled = true;document.body.style.cursor = 'progress';var dim = dims[format];var pdf = new jsPDF('p', 'mm', format); // p是竖向;l横向打印var imgData = myloadImageFile('http://image/a.png', 'true');console.info("super:" + imgData);pdf.setProperties({title: '制图',subject: 'http://www.eqxiu.com/h2/visit',author: 'eqxiu',keywords: 'eqxiu',creator: 'eqxiu'});pdf.addImage(imgData, 'JPEG', 0, 0);pdf.save('map.pdf');exportButton.disabled = false;});</script>
</body>
</html>

 

Published by

风君子

独自遨游何稽首 揭天掀地慰生平

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注