import { DocType, DocumentScanner, DocumentScannerConfig, SaveOption, FilterId, ShootingMode, EditTab } from "@kit.VisionKit";import { hilog, LogLevel } from '@ohos.hilog'; // 日志工具
const TAG = 'DocScannerDemo'; // 日志标签
@Entry@Componentexport struct DocDemoPage { @State scanResults: string[] = []; // 保存扫描结果URI private pathStack: NavPathStack | null = null;
// 扫描配置初始化 private docScanConfig = new DocumentScannerConfig();
// 页面加载时配置扫描参数 aboutToAppear() { this.docScanConfig.supportType = [DocType.DOC, DocType.SHEET]; // 支持文档和表格识别 this.docScanConfig.maxShotCount = 3; // 最多拍摄3张 this.docScanConfig.isGallerySupported = true; // 允许从图库选图 this.docScanConfig.defaultFilterId = FilterId.STRENGTHEN; // 默认增强滤镜 this.docScanConfig.defaultShootingMode = ShootingMode.MANUAL; // 手动拍摄模式 this.docScanConfig.editTabs = [EditTab.ROTATE_TAB, EditTab.RESHOOT_TAB]; // 显示旋转和重拍按钮 this.docScanConfig.saveOptions = [SaveOption.JPG, SaveOption.PDF, SaveOption.EXCEL]; // 支持三种保存格式 this.docScanConfig.isShareable = true; // 开启分享功能 }
build() { NavDestination({ name: 'documentScanner' }) { Stack() { // 扫描结果展示区域 Column() { if (this.scanResults.length > 0) { Text('扫描结果').fontSize(18).fontWeight(500).margin({ top: 20 }); Grid() { ForEach(this.scanResults, (uri, index) => { // 展示缩略图,点击可预览(示例中简化为日志输出) Image(uri) .objectFit(ImageFit.Contain) .width(150) .height(150) .margin(10) .onClick(() => hilog.info(LogLevel.INFO, TAG, `预览图片:${uri}`)); }) .columnsTemplate('1fr 1fr') // 两行布局 .rowGap(10) .columnGap(10); } } .width('100%') .padding(20);
// 文档扫描控件主体 DocumentScanner({ scannerConfig: this.docScanConfig, onResult: (code: number, saveType: SaveOption, uris: string[]) => { hilog.info(LogLevel.INFO, TAG, `扫描结果:code=${code}, 格式=${SaveOption[saveType]}`); switch (code) { case 200: // 成功 this.scanResults = uris; // 更新结果列表 hilog.info(LogLevel.INFO, TAG, `保存路径:${uris.join(', ')}`); break; case -1: // 用户取消 this.pathStack.pop(); // 返回上一页 break; case 1008601001: // URI无效(5.0.5+支持) hilog.error(LogLevel.ERROR, TAG, '传入的图片规格不符合要求'); break; } } }) .size({ width: '100%', height: '100%' }) .margin({ top: 80 }); // 留出结果展示区域空间 } .width('100%') .height('100%') .hideTitleBar(true); // 隐藏导航栏 .onReady((context: NavDestinationContext)=>{ this.pathStack = context?.pathStack; }) }}
评论