js 文件流application/pdf 转为blob
时间: 2023-07-29 10:12:10 浏览: 101
可以使用 XMLHttpRequest 对文件进行加载并转换为 Blob 对象。下面是一个简单的示例代码:
```javascript
function getFileBlob(url, success) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.responseType = "blob";
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
success(xhr.response);
}
};
xhr.send();
}
getFileBlob("example.pdf", function(blob) {
// 处理 blob 对象
});
```
在上面的代码中,我们通过 XMLHttpRequest 发送一个 GET 请求,设置 responseType 为 "blob",以获取 PDF 文件的 Blob 对象。然后使用回调函数将 Blob 对象传递给另一个函数进行处理。
注意:在调用 getFileBlob 函数时,需要将 URL 参数替换为实际的文件 URL。
相关问题
将非pdf文件类型转为pdf的blob
将非PDF文件转换成PDF Blob(二进制大对象)通常涉及两步:首先需要读取源文件内容,然后使用适合的库(如JavaScript的html2canvas、Node.js的pdfmake等)将其转换为PDF格式,最后保存为Blob对象。
例如,在JavaScript环境中,你可以这样做:
```javascript
// 假设srcFile是你的非PDF文件的URL或File对象
const fs = require('fs');
const html2pdf = require('html2pdf');
async function convertToPdf(srcFile) {
// 读取源文件内容(这里假设是HTML)
const sourceHtml = await fetch(srcFile).then(res => res.text());
// 使用html2pdf生成PDF
const pdfBuffer = await html2pdf.create().toBuffer(sourceHtml);
// 创建一个Blob对象
const blob = new Blob([pdfBuffer], {type: 'application/pdf'});
return blob;
}
// 调用函数并处理返回的Blob对象
convertToPdf('yourSourceFileUrl').then(pdfBlob => {
// 现在pdfBlob就是一个可以下载或进一步处理的PDF Blob了
});
```
JS PDF文件流base64字符串转为文件
你可以使用以下代码将base64字符串转换为PDF文件:
```javascript
function base64ToPDF(base64String, fileName) {
var byteCharacters = atob(base64String);
var byteNumbers = new Array(byteCharacters.length);
for (var i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
var pdfBlob = new Blob([byteArray], {type: 'application/pdf'});
saveAs(pdfBlob, fileName);
}
// 调用示例
base64ToPDF('base64字符串', '文件名.pdf');
```
其中,`atob()` 函数用于将base64字符串解码为二进制数据,`Blob` 对象用于创建一个PDF文件的二进制数据,`saveAs()` 函数用于将Blob对象保存为PDF文件。注意,如果你使用的是浏览器环境,需要先引入 `FileSaver.js` 库才能使用 `saveAs()` 函数。
阅读全文
相关推荐
















