HarmonyOS鸿蒙Next中如何将base64字符串转成pdf文件保存到手机并供用户查看
HarmonyOS鸿蒙Next中如何将base64字符串转成pdf文件保存到手机并供用户查看
import { BusinessError, systemDateTime } from "@kit.BasicServicesKit"
import { buffer } from "@kit.ArkTS"
import fs from '@ohos.file.fs';
import { picker } from "@kit.CoreFileKit";
export class FileUtil {
static async saveBase64Image(fileName: string,base64ImageData: string, context: Context): Promise<Boolean> {
try {
let base64Result = FileUtil.dealBase64Str(base64ImageData)
let file = FileUtil.createFile(context,fileName)
let bufferImage = buffer.from(base64Result, 'base64')
await fs.write(file.fd, bufferImage.buffer)
fs.closeSync(file.fd)
const documentSaveOptions = new picker.DocumentSaveOptions(); // 创建文件管理器选项实例
documentSaveOptions.newFileNames = [fileName]; // 保存文件名(可选)
documentSaveOptions.fileSuffixChoices = ['']; // 保存文件类型(可选)
let uris: Array<string> = [];
const documentViewPicker = new picker.DocumentViewPicker(); // 创建文件选择器实例
documentViewPicker.save(documentSaveOptions).then((documentSaveResult: Array<string>) => {
uris = documentSaveResult;
console.info('documentViewPicker.save to file succeed and uris are:' + uris);
let uri = uris[0];
let file2 = fs.openSync(uri, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
let writeLen2 = fs.writeSync(file2.fd, bufferImage.buffer);
fs.closeSync(file2);
}).catch((err: BusinessError) => {
console.error(`Invoke documentViewPicker.save failed, code is ${err.code}, message is ${err.message}`);
})
return Promise.resolve(true)
} catch (e) {
throw new Error(e)
}
}
private static dealBase64Str(base64Data: string): string {
let imageData: string
if (base64Data.startsWith("data")) {
const base64Split: string[] = base64Data.split(",")
if (base64Split.length !== 2) {
throw new Error(`ImageUtils: Illegal base64 data`)
}
imageData = base64Split[1].trim()
} else {
imageData = base64Data
}
return imageData
}
private static createFile(context: Context,fileName: string) {
let pathDir = context.filesDir
let filePath = `${pathDir}/${fileName}`
let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE)
return file
}
}
更多关于HarmonyOS鸿蒙Next中如何将base64字符串转成pdf文件保存到手机并供用户查看的实战教程也可以访问 https://www.itying.com/category-93-b0.html
不错,加油
更多关于HarmonyOS鸿蒙Next中如何将base64字符串转成pdf文件保存到手机并供用户查看的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在HarmonyOS鸿蒙Next中,将base64字符串转换为PDF文件并保存到手机供用户查看,可以按照以下步骤进行:
-
解码Base64字符串:首先,使用
Base64
类提供的解码方法将Base64字符串解码为字节数组。鸿蒙系统提供了Base64
工具类,可以直接使用Base64.decode()
方法进行解码。 -
创建文件并写入数据:使用鸿蒙的文件系统API,创建一个PDF文件,并将解码后的字节数组写入该文件。可以使用
File
类来创建文件,并通过FileOutputStream
将数据写入文件。 -
保存文件到指定路径:将生成的PDF文件保存到手机的指定目录中。可以使用鸿蒙的
Context
类获取应用的文件存储路径,或者使用Environment
类获取外部存储路径。 -
提供文件查看功能:使用鸿蒙的
Intent
机制,调用系统默认的PDF查看器或应用内嵌的PDF查看组件,打开并显示生成的PDF文件。可以通过Intent.ACTION_VIEW
来启动查看操作。
以下是一个简化的代码示例:
import { Base64 } from '@ohos.util';
import { fileIo } from '@ohos.fileio';
import { featureAbility } from '@ohos.ability.featureAbility';
// Base64字符串
const base64String = "your_base64_string_here";
// 解码Base64字符串
const byteArray = Base64.decode(base64String);
// 创建文件路径
const filePath = "your_file_path_here.pdf";
// 写入文件
const file = fileIo.openSync(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.WRITE_ONLY);
fileIo.writeSync(file.fd, byteArray);
fileIo.closeSync(file.fd);
// 打开PDF文件
const intent = {
action: "ohos.intent.action.VIEW",
uri: "file://" + filePath,
type: "application/pdf"
};
featureAbility.startAbility(intent);
这段代码展示了如何将Base64字符串解码为PDF文件,并保存到手机中,最后通过系统默认的PDF查看器打开该文件。
在HarmonyOS鸿蒙Next中,将Base64字符串转换为PDF文件并保存到手机,可以按照以下步骤进行:
- Base64解码:使用
Base64
工具类将字符串解码为字节数组。 - 文件保存:使用
File
和FileOutputStream
将字节数组写入到指定路径的PDF文件中。 - 文件查看:使用
Intent
启动系统默认的PDF查看器打开文件。
示例代码:
import ohos.global.resource.Base64;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.image.common.PixelFormat;
import ohos.media.image.common.Size;
import ohos.utils.zson.ZSONObject;
import ohos.utils.zson.ZSONType;
import ohos.utils.zson.ZSONUtils;
import ohos.utils.zson.ZSONWriter;
import ohos.utils.zson.ZSONReader;
import ohos.utils.zson.ZSONException;
import ohos.utils.zson.ZSONArray;
import ohos.utils.zson.ZSONElement;
import ohos.utils.zson.ZSONParser;
import ohos.utils.zson.ZSONSerializer;
public class Base64ToPDF {
private static final HiLogLabel LABEL = new HiLogLabel(HiLog.LOG_APP, 0x00201, "Base64ToPDF");
public void saveBase64AsPDF(String base64Str, String filePath) {
try {
// Base64解码
byte[] pdfBytes = Base64.decode(base64Str, Base64.DEFAULT);
// 保存到文件
File file = new File(filePath);
FileOutputStream fos = new FileOutputStream(file);
fos.write(pdfBytes);
fos.close();
HiLog.info(LABEL, "PDF文件保存成功: " + filePath);
} catch (Exception e) {
HiLog.error(LABEL, "保存PDF文件失败: " + e.getMessage());
}
}
public void openPDF(Context context, String filePath) {
File file = new File(filePath);
if (file.exists()) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "application/pdf");
context.startActivity(intent);
} else {
HiLog.error(LABEL, "PDF文件不存在: " + filePath);
}
}
}
调用saveBase64AsPDF
方法保存PDF文件,然后使用openPDF
方法打开文件供用户查看。