| | |
| | | import FileSaver from 'file-saver'; |
| | | |
| | | /** |
| | | * 将base64格式图片转换为ArrayBuffer |
| | | * @param {string} base64Str - base64格式图片字符串(可包含data URL前缀) |
| | | * @returns {ArrayBuffer} 转换后的ArrayBuffer对象 |
| | | */ |
| | | function base64ToArrayBuffer(base64Str) { |
| | | // 移除data URL前缀(如果存在) |
| | | const base64Content = base64Str.replace(/^data:image\/\w+;base64,/, ''); |
| | | |
| | | // 处理URL安全的base64字符 |
| | | const safeBase64 = base64Content.replace(/-/g, '+').replace(/_/g, '/'); |
| | | |
| | | // 解码base64字符串 |
| | | const binaryStr = atob(safeBase64); |
| | | |
| | | // 转换为Uint8Array |
| | | const byteLength = binaryStr.length; |
| | | const uint8Array = new Uint8Array(byteLength); |
| | | |
| | | for (let i = 0; i < byteLength; i++) { |
| | | uint8Array[i] = binaryStr.charCodeAt(i); |
| | | } |
| | | |
| | | // 返回ArrayBuffer |
| | | return uint8Array.buffer; |
| | | } |
| | | |
| | | /** |
| | | * 等比例缩放图片 |
| | | * 根据图片的长宽比进行不同方式的缩放 |
| | | * 如果宽度大于高度(横拍图片),则按照设定高度等比缩放; |
| | |
| | | getImage(tagValue) { |
| | | // In this case tagValue will be a URL tagValue = "https://docxtemplater.com/puffin.png" |
| | | return new Promise(function (resolve, reject) { |
| | | if (tagValue.indexOf('http') == 0) { |
| | | JSZipUtils.getBinaryContent(tagValue, function (error, content) { |
| | | if (error) { |
| | | return reject(error); |
| | | } |
| | | return resolve(content); |
| | | }); |
| | | } else if (tagValue.indexOf('data:image') == 0) { |
| | | const buffer = base64ToArrayBuffer(tagValue); |
| | | return resolve(buffer); |
| | | } |
| | | }); |
| | | }, |
| | | |