HarmonyOS 鸿蒙Next使用filePreview打开文件问题
HarmonyOS 鸿蒙Next使用filePreview打开文件问题
let uuid:string = creatUuid()
let uiContext = getContext(this);
let displayInfo: filePreview.DisplayInfo = {
x: 100,
y: 100,
width: 800,
height: 800
};
let fileInfo: filePreview.PreviewInfo = {
title: '1.txt',
uri: 'xxx/2.pdf',
mimeType: 'application/pdf'
};
filePreview.openPreview(uiContext, fileInfo, displayInfo).then(() => {
console.info('Succeeded in openPreview');
}).catch((err: BusinessError) => {
console.error(`Failed to openPreview, err.code = ${err.code}, err.message = ${err.message}`);
});
如上代码,使用filePreview来预览代码项目rawfile目录中的2.pdf文件,其中fileInfo中的uri怎么填写
2 回复
HarmonyOS 鸿蒙Next使用filePreview打开文件问题可以参考demo:
//index.ets
import fs from '@ohos.file.fs';
import router from '@ohos.router';
import picker from '@ohos.file.picker';
import { BusinessError } from '@ohos.base';
import common from '@ohos.app.ability.common';
const TAG = '[PDFView_LOG_TAG]';
function getCurrentDateFormatted(): string {
const now = new Date();
const year = now.getFullYear();
// getMonth() 返回的月份是从0开始的,因此需要+1
// padStart(2, '0') 确保月份和日期始终是两位数
const month = (now.getMonth() + 1).toString().padStart(2, '0');
const date = now.getDate().toString().padStart(2, '0');
return `${year}-${month}-${date}`;
}
async function copyResourceFileAndJump(): Promise<void> {
try {
let context = getContext() as common.UIAbilityContext;
let dir = context.filesDir
let filePath = dir + "/input.pdf";
let res = fs.accessSync(filePath);
if (res) {
console.info(TAG, "file exists 0");
} else {
console.info(TAG, "file not exists");
let content = context.resourceManager.getRawFileContentSync('rawfile/test.pdf'); //pdf_reference
let fdSand = fs.openSync(filePath, fs.OpenMode.WRITE_ONLY | fs.OpenMode.CREATE | fs.OpenMode.TRUNC);
fs.writeSync(fdSand.fd, content.buffer);
fs.closeSync(fdSand.fd);
}
let result = filePath;
console.info(TAG, "file exists");
router.pushUrl({
url: 'pages/PDFPreview',
params: {
src: result,
}
})
} catch (e) {
let err = e as BusinessError;
console.error(TAG, `Get exception: ${e}`);
}
}
@Entry
@Component
struct Index {
@State message: string = 'Hello World'
aboutToAppear(): void {
let context = getContext() as common.UIAbilityContext;
const dir = context.filesDir + `/${getCurrentDateFormatted()}/`
fs.mkdir(dir)
let filePath = dir + "pdf.log";
}
// 将资源文件中的演示PDF文件写入沙盒中并进入下个页面
private async copy_uri_and_jump(uri: string) {
try {
let dir = getContext().filesDir
let file = dir + "/temp.pdf";
console.log(TAG, "[rawfile_copy_to_sandbox] 路径为 :" + file);
let sourceFile = fs.openSync(uri, fs.OpenMode.READ_ONLY);
fs.copyFile(sourceFile.fd, file).then(() => {
console.info(TAG, "copyFile succeed");
router.pushUrl({
url: 'pages/PDFPreview',
params: {
src: file,
}
})
}).catch((err: BusinessError) => {
console.info(TAG, "copyFile failed with error:" + err);
});
} catch (error) {
console.info(TAG, "[rawfile_copy_to_sandbox] getRawFileDescriptor api 运行失败" + error);
console.log(TAG, "[rawfile_copy_to_sandbox] 未能成功将资源文件拷贝到应用沙箱下");
}
}
build() {
Row() {
Column() {
Button("打开电脑里的PDF文件")
.fontSize(20)
.fontWeight(FontWeight.Bold)
.onClick(() => {
// 拷贝文件到沙盒中,并push到下一个pdfViewer页面,展示功能
const documentSelectOptions = new picker.DocumentSelectOptions();
documentSelectOptions.maxSelectNumber = 1; // 选择文档的最大数目(可选)
// documentSelectOptions.defaultFilePathUri = "file://docs/storage/Users/currentUser/test"; // 指定选择的文件或者目录路径(可选)
documentSelectOptions.fileSuffixFilters = ['.pdf']; // 选择文件的后缀类型,若选择项存在多个后缀名,则每一个后缀名之间用英文逗号进行分隔(可选)
let uris: Array<string> = [];
const documentViewPicker = new picker.DocumentViewPicker(); // 创建文件选择器实例
documentViewPicker.select(documentSelectOptions).then((documentSelectResult: Array<string>) => {
uris = documentSelectResult;
let uri = uris[0]
this.copy_uri_and_jump(uri)
console.info(TAG, 'documentViewPicker.select to file succeed and uri are:' + uri);
}).catch((err: BusinessError) => {
console.error(TAG, `Invoke documentViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
})
})
Button("打开资源PDF文件")
.fontSize(20)
.fontWeight(FontWeight.Bold)
.onClick(() => {
copyResourceFileAndJump()
}).margin({ top: 15 })
}
.width('100%')
}
.height('100%')
}
}
//PDFPreview .ets
import { pdfService } from '@kit.PDFKit';
import { fileIo as fs, fileUri as fileuri } from '@kit.CoreFileKit';
import { image } from '@kit.ImageKit';
import { font, router } from '@kit.ArkUI';
const TAG = '[PDFKit_LOG_TAG]';
@Entry
@Component
struct PDFPreview {
@State filePath: string = (router.getParams() as Record<string, string>)['src']
@State pageCount: number = 0
@State pageIndex: number = 0
@State _pixelMap: image.PixelMap | undefined = undefined;
private document: pdfService.PdfDocument = new pdfService.PdfDocument;
//打开选择的PDF文件
openFile() {
let t0 = Date.now();
this.document.loadDocument(this.filePath, '');
let t1 = Date.now();
console.log(TAG, "loadDocument time:" + (t1 - t0))
}
//提示框
showDialog(title: string, msg: string) {
AlertDialog.show(
{
title: title,
message: msg,
autoCancel: true,
alignment: DialogAlignment.Bottom,
offset: { dx: 0, dy: -20 },
gridCount: 3,
confirm: {
value: '关闭',
action: () => {
console.info('Button-clicking callback')
}
},
})
}
aboutToAppear() {
this.openFile(); //打开文件
let page: pdfService.PdfPage = this.document.getPage(0); //默认第一页
this._pixelMap = page.getPagePixelMap(); //设置Image组件参数
}
aboutToDisappear() {
this.document.releaseDocument();
}
build() {
Column() {
Row() {
// 显示内容
Image(this._pixelMap)
.width(480)
.height(600)
.objectFit(ImageFit.Contain)
.border({ width: 1, color: Color.Blue })
}
Row() {
Button("返回")
.fontSize(12)
.onClick(() => {
router.back({ url: 'pages/Index' });
})
Button("PDF转图片")
.fontSize(12)
.onClick(async () => {
let uri = 'file://docs/storage/Users/currentUser' + '/outputImg'; //图片存储路径
let fileUri: fileuri.FileUri = new fileuri.FileUri(uri);
let path = fileUri.path;
fs.mkdir(path);
const result: boolean = this.document.convertToImage(path, 0); //将PDF文件转为图片
if (result) {
this.showDialog('PDF转图片成功', '存储路径为:用户目录/outputImg');
} else {
this.showDialog('PDF转图片失败', '');
}
}).margin({ left: 15 })
Button("上一页")
.fontSize(12)
.onClick(async () => {
this.pageIndex--;
if (this.pageIndex < 0) {
this.showDialog('提示', '已是第一页');
this.pageIndex++;
return;
}
let page: pdfService.PdfPage = this.document.getPage(this.pageIndex); //设置页面为上一页
this._pixelMap = page.getPagePixelMap(); //设置Image组件参数
}).margin({ left: 15 })
Button("下一页")
.fontSize(12)
.onClick(async () => {
this.pageIndex++;
if (this.pageIndex >= this.document.getPageCount()) {
this.showDialog('提示', '已是最后一页');
this.pageIndex--;
return;
}
let page: pdfService.PdfPage = this.document.getPage(this.pageIndex); //设置页面为上一页
this._pixelMap = page.getPagePixelMap(); // 设置Image组件参数
}).margin({ left: 15 })
Button("添加示例文字")
.fontSize(12)
.onClick(async () => {
let page: pdfService.PdfPage = this.document.getPage(this.pageIndex);
let textStyle: pdfService.TextStyle = new pdfService.TextStyle;
let fontList: Array<string> = font.getSystemFontList();
let fontInfo: font.FontInfo = font.getFontByName(fontList[0]); //获取系统默认字体
textStyle.fontInfo = { fontPath: fontInfo.path };
textStyle.textSize = 20;
page.addTextObject("hello world", 0, 0, textStyle); //添加示例文字
this._pixelMap = page.getPagePixelMap();
}).margin({ left: 15 })
Button("保存文件")
.fontSize(12)
.onClick(async () => {
let uri = 'file://docs/storage/Users/currentUser' + '/outputPdf'; //保存后文件存储路径
let fileUri: fileuri.FileUri = new fileuri.FileUri(uri);
let path = fileUri.path;
fs.mkdir(path);
const result: boolean = this.document.saveDocument(path + '/output.pdf'); //保存文件
if (result) {
this.showDialog('PDF保存成功', '存储路径为:用户目录/outputPdf');
} else {
this.showDialog('PDF保存失败', '');
}
}).margin({ left: 15 })
}
}
.width('100%')
}
}
针对HarmonyOS 鸿蒙Next使用filePreview打开文件的问题,首先需要明确的是,filePreview组件在HarmonyOS中的支持情况可能会随着系统版本的更新而有所变化。
根据最新的信息,filePreview组件在HarmonyOS鸿蒙Next中主要支持一些特定的文件类型预览,如.json、.ets、.js、.css以及.hml等。然而,关于PDF文件的支持情况,存在不同的说法。有观点认为,filePreview组件目前不支持PDF文件的直接预览;但也有信息显示,官网文档后续已更新,表示filePreview支持PDF格式。
若在使用filePreview组件时遇到无法预览PDF文件的情况,建议首先确认所使用的HarmonyOS鸿蒙Next系统版本,并查阅最新的官方文档以获取最准确的信息。此外,可以尝试使用其他方式如webview组件来加载并展示PDF文件,以实现预览功能。
如果问题依旧没法解决请联系官网客服,官网地址是:https://www.itying.com/category-93-b0.html。