如何使用Cordova从设备上的base64字符串中保存PDF

本文概述

  • 要求
  • 实现
  • 保存base64类型1
  • 保存base64类型2
对于某些开发人员而言, 从服务器返回base64字符串的文件很容易。通常, 允许使用简单的window.open函数在桌面浏览器中查看PDF文件:
window.open("data:application/pdf; base64, JVBERi0xLjcKCjEgMCBv...", "_blank");

【如何使用Cordova从设备上的base64字符串中保存PDF】但是, 在Cordova, 这行不通。如果要查看PDF, 则需要将其保存在设备上, 并使用cordova-plugin-fileopener2之类的插件进行查看。
即使你使用inapp-browser插件, Cordova本身也不允许直接在应用程序中进行预览。
要求 在处理文件时, 你需要在项目中安装cordova-file-plugin。要安装此插件, 请使用:
cordova plugin add cordova-plugin-file

如果你对该插件一无所知, 请在此处的官方存储库中了解有关其工作原理的更多信息。
实现 为了将PDF base64字符串作为文件写入设备上, 我们将使用以下两种方法:
/** * Convert a base64 string in a Blob according to the data and contentType. * * @param b64Data {String} Pure base64 string without contentType * @param contentType {String} the content type of the file i.e (application/pdf - text/plain) * @param sliceSize {Int} SliceSize to process the byteCharacters * @see http://stackoverflow.com/questions/16245767/creating-a-blob-from-a-base64-string-in-javascript * @return Blob */ function b64toBlob(b64Data, contentType, sliceSize) { contentType = contentType || ''; sliceSize = sliceSize || 512; var byteCharacters = atob(b64Data); var byteArrays = []; for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) { var slice = byteCharacters.slice(offset, offset + sliceSize); var byteNumbers = new Array(slice.length); for (var i = 0; i < slice.length; i++) { byteNumbers[i] = slice.charCodeAt(i); }var byteArray = new Uint8Array(byteNumbers); byteArrays.push(byteArray); }var blob = new Blob(byteArrays, {type: contentType}); return blob; }/** * Create a PDF file according to its database64 content only. * * @param folderpath {String} The folder where the file will be created * @param filename {String} The name of the file that will be created * @param content {Base64 String} Important : The content can't contain the following string (data:application/pdf; base64). Only the base64 string is expected. */ function savebase64AsPDF(folderpath, filename, content, contentType){ // Convert the base64 string in a Blob var DataBlob = b64toBlob(content, contentType); console.log("Starting to write the file :3"); window.resolveLocalFileSystemURL(folderpath, function(dir) { console.log("Access to the directory granted succesfully"); dir.getFile(filename, {create:true}, function(file) { console.log("File created succesfully."); file.createWriter(function(fileWriter) { console.log("Writing content to file"); fileWriter.write(DataBlob); }, function(){ alert('Unable to save file in path '+ folderpath); }); }); }); }

cordova-file-plugin提供的cordova文件编写器不支持使用base64编写文件, 因此我们将使用一些技巧。 base64字符串将被处理并转换为可写Blob。
使用savebase64AsPDF方法
该代码段中很好地解释了该方法, 要对其进行测试, 可以在项目中测试以下代码, 该方法应在根目录中创建一个hello world PDF。
// Remember to execute this after the onDeviceReady event// If your base64 string contains "data:application/pdf; base64, "" at the beginning, keep reading. var myBase64 = "JVBERi0xLjcKCjEgMCBvYmogICUgZW50cnkgcG9pbnQKPDwKICAvVHlwZSAvQ2F0YWxvZwogIC9QYWdlcyAyIDAgUgo+PgplbmRvYmoKCjIgMCBvYmoKPDwKICAvVHlwZSAvUGFnZXMKICAvTWVkaWFCb3ggWyAwIDAgMjAwIDIwMCBdCiAgL0NvdW50IDEKICAvS2lkcyBbIDMgMCBSIF0KPj4KZW5kb2JqCgozIDAgb2JqCjw8CiAgL1R5cGUgL1BhZ2UKICAvUGFyZW50IDIgMCBSCiAgL1Jlc291cmNlcyA8PAogICAgL0ZvbnQgPDwKICAgICAgL0YxIDQgMCBSIAogICAgPj4KICA+PgogIC9Db250ZW50cyA1IDAgUgo+PgplbmRvYmoKCjQgMCBvYmoKPDwKICAvVHlwZSAvRm9udAogIC9TdWJ0eXBlIC9UeXBlMQogIC9CYXNlRm9udCAvVGltZXMtUm9tYW4KPj4KZW5kb2JqCgo1IDAgb2JqICAlIHBhZ2UgY29udGVudAo8PAogIC9MZW5ndGggNDQKPj4Kc3RyZWFtCkJUCjcwIDUwIFRECi9GMSAxMiBUZgooSGVsbG8sIHdvcmxkISkgVGoKRVQKZW5kc3RyZWFtCmVuZG9iagoKeHJlZgowIDYKMDAwMDAwMDAwMCA2NTUzNSBmIAowMDAwMDAwMDEwIDAwMDAwIG4gCjAwMDAwMDAwNzkgMDAwMDAgbiAKMDAwMDAwMDE3MyAwMDAwMCBuIAowMDAwMDAwMzAxIDAwMDAwIG4gCjAwMDAwMDAzODAgMDAwMDAgbiAKdHJhaWxlcgo8PAogIC9TaXplIDYKICAvUm9vdCAxIDAgUgo+PgpzdGFydHhyZWYKNDkyCiUlRU9G"; // To define the type of the Blob var contentType = "application/pdf"; // if cordova.file is not available use instead : // var folderpath = "file:///storage/emulated/0/"; var folderpath = cordova.file.externalRootDirectory; var filename = "helloWorld.pdf"; savebase64AsPDF(folderpath, filename, myBase64, contentType);

如何使用Cordova从设备上的base64字符串中保存PDF

文章图片
根据你的情况和base64, 你可以使用2种类型的base64字符串:
// The entire base64 string that can be viewed in the browser as pdf var type1 = "data:application/pdf; base64, JVBERi0xLjcKCjEgMCBv......."; // Only the base64 string without specific format var type2 = "JVBERi0xLjcKCjEgMCBv.......";

保存base64类型1 由于此字符串已经包含需要该功能的内容类型, 因此我们只需要处理该字符串并以不同的变量检索内容和内容类型(application / pdf)。
/** Process the type1 base64 string **/ var myBaseString = "data:application/pdf; base64, JVBERi0xLjcKCjEgMCBv......."; // Split the base64 string in data and contentType var block = myBaseString.split("; "); // Get the content type var dataType = block[0].split(":")[1]; // In this case "application/pdf" // get the real base64 content of the file var realData = http://www.srcmini.com/block[1].split(", ")[1]; // In this case "JVBERi0xLjcKCjE...."// The path where the file will be created var folderpath = "file:///storage/emulated/0/"; // The name of the PDF var filename = "mypdf.pdf"; savebase64AsPDF(folderpath, filename, realData, dataType);

保存base64类型2 我们知道PDF的mime类型, 我们不需要从整个base64字符串中检索出来, 因此只需继续使用该方法并保存即可:
// The base64 content var myBase64 = "JVBERi0xLjcKCjE...."; // Define the mimetype of the file to save, in this case a PDF var contentType = "application/pdf"; // The path where the file will be saved var folderpath = "file:///storage/emulated/0/"; // The name of your file var filename = "myPdf.pdf"; savebase64AsPDF(folderpath, filename, myBase64, contentType);

玩得开心 !

    推荐阅读