gpt4 book ai didi

android - 在 phonegap 中将 base64 字符串转换为 pdf

转载 作者:行者123 更新时间:2023-11-30 01:34:31 25 4
gpt4 key购买 nike

在我的应用程序中,我收到了一个表示 PDF 的 base64 字符串。我希望用户能够将 base64 以 pdf 格式保存到他的手机中。我一直在寻找 cordova-file-transfer插件,但这需要一个可以从中下载文件的(服务器)路径,而不是转换 base64 字符串。

有人使用 base64 字符串在 phonegap 中成功下载 pdf 吗?

最佳答案

经过更多的搜索和尝试,我发现了一些有用的东西。

Converting base64 to pdf blob

//Helper function that converts base64 to blob
function b64toBlob(b64Data, contentType, sliceSize) {
var input = b64Data.replace(/\s/g, ''),
byteCharacters = atob(input),
byteArrays = [],
offset, slice, byteNumbers, i, byteArray, blob;

contentType = contentType || '';
sliceSize = sliceSize || 512;

for (offset = 0; offset < byteCharacters.length; offset += sliceSize) {
slice = byteCharacters.slice(offset, offset + sliceSize);

byteNumbers = new Array(slice.length);
for (i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}

byteArray = new Uint8Array(byteNumbers);

byteArrays.push(byteArray);
}

//Convert to blob.
try {
blob = new Blob(byteArrays, { type: contentType });
}
catch (e) {
// TypeError old chrome, FF and Android browser
window.BlobBuilder = window.BlobBuilder ||
window.WebKitBlobBuilder ||
window.MozBlobBuilder ||
window.MSBlobBuilder;
if (e.name == 'TypeError' && window.BlobBuilder) {
var bb = new BlobBuilder();
for (offset = 0; offset < byteArrays.length; offset += 1) {
bb.append(byteArrays[offset].buffer);
}
blob = bb.getBlob(contentType);
}
else if (e.name == "InvalidStateError") {
blob = new Blob(byteArrays, {
type: contentType
});
}
else {
return null;
}
}

return blob;
};

然后下载本身我们需要 cordova-file插件:

var fileToSave= b64toBlob(fileData, 'application/pdf'); 
writeFile();

function writeFile() {
console.log("request file system");
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFileSystemRetrieved, onFileSystemFail);
}

function onFileSystemRetrieved(fileSystem) {
console.log("file system retrieved");
fileSystem.root.getFile(fileName, { create: true }, onFileEntryRetrieved, onFileSystemFail);
}

function onFileEntryRetrieved(fileEntry) {
console.log("file entry retrieved");
fileEntry.createWriter(gotFileWriter, onFileSystemFail);
}

function gotFileWriter(writer) {
console.log("write to file");

writer.onwrite = function (evt) {
alert('done');
}
writer.write(fileToSave);

window.open(fileName, '_blank');
}
function onFileSystemFail(error) {
console.log(error.code);
alert(error.code)
}

关于android - 在 phonegap 中将 base64 字符串转换为 pdf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35273685/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com