打印
第一步:权限申请
在module.json5中进行如下配置;
"requestPermissions": [{"name": "ohos.permission.PRINT","reason": "$string:permissionsReason","usedScene": {"abilities": ["EntryAbility"],"when":"always"}},{"name": "ohos.permission.INTERNET"},
],
第二步:将打印的内容保存至沙箱(这里是将网络图片下载到沙箱),并将地址转化成uri沙箱目录格式
import { fileUri } from '@kit.CoreFileKit';
import { downloadFileWithUniqueName } from './dowmload';
import { common } from '@kit.AbilityKit';
import { PrintService } from './printPage';@Entry
@Component
struct Index {@State message: string = 'Hello World';@State uri: string = ""@State filePath:string = ""private printService: PrintService | null = new PrintService(getContext(this)); // 打印服务实例build() {Scroll() {Column({ space: 10 }) {Button("下载").onClick(async () => {const res = await downloadFileWithUniqueName("https://pic.rmb.bdstatic.com/bjh/bb8918b3bce/241107/8b2d3382db261f701e50d6acddcb48bc.jpeg?for=bg", "test.jpg")let context = getContext(this) as common.UIAbilityContextthis.filePath = `${context.filesDir}/${res.uniqueNameWithoutExt}.${res.ext}`})Text("显示").fontSize(50).fontWeight(FontWeight.Bold).onClick(() => {console.log('filePath-----',this.filePath)this.uri = fileUri.getUriFromPath(this.filePath)console.log('uri-----',this.uri)})Image(this.uri).width(100).height(100)Button("打印").width('90%').height(50).onClick(() => {let hostContext = this.getUIContext().getHostContext();if (hostContext) {this.printService = new PrintService(hostContext);this.printService.executePrint([this.uri,this.uri])} else {console.error('获取上下文失败,无法初始化打印服务');}})}.justifyContent(FlexAlign.Center).constraintSize({ minHeight: '100%' }).width('100%')}.height('100%')}
}
note:其中打印需要的上下文需要用this.getUIContext().getHostContext()来获取,需要的地址格式需要用fileUri.getUriFromPath来获取。
第三步:封装打印文件需要的类
import { BusinessError, print } from '@kit.BasicServicesKit';
/*** 打印服务类*/
export class PrintService {private context: Context;constructor(context: Context) {this.context = context;}/*** 执行打印操作*/executePrint(files: string[],callback?: () => void): void {try {if (files.length === 0) {console.error('没有有效的文件可打印');return;}console.log("最终打印URI列表:", JSON.stringify(files));print.print(files, this.context).then((printTask: print.PrintTask) => {printTask.on('succeed', () => {console.info('print state is succeed');if (callback) {callback();}})}).catch((error: BusinessError) => {console.error('print err ' + JSON.stringify(error));})}catch (e){console.error('打印失败:' + JSON.stringify(e));}}
}
拓展:下载的工具类
import { fileIo } from '@kit.CoreFileKit';
import { request } from '@kit.BasicServicesKit';/*** 将网络图片下载到沙箱* @param url 当前应用上下文* @param originalFileName 文件名(不含扩展名)* @returns 下载任务、唯一文件名、后缀*/interface DownloadTask {task: request.DownloadTask;uniqueNameWithoutExt: string;ext?: string;
}// 下载文件并生成唯一文件路径,返回下载任务和唯一文件名(不含后缀)
export async function downloadFileWithUniqueName(url: string,originalFileName: string
): Promise<DownloadTask> {// 获取上下文和文件目录const context = getContext();const filesDir = context.filesDir;// 分离文件名和扩展名const extIndex = originalFileName.lastIndexOf('.');const nameWithoutExt = extIndex > 0 ? originalFileName.substring(0, extIndex) : originalFileName;const ext = extIndex > 0 ? originalFileName.substring(extIndex) : '';let newName = originalFileName;let counter = 1;// 尝试生成唯一的文件名while (fileIo.accessSync(`${filesDir}/${newName}`)) {newName = `${nameWithoutExt}(${counter})${ext}`;counter++;}const uniqueFilePath = `${filesDir}/${newName}`;const uniqueNameWithoutExt = newName.substring(0, newName.lastIndexOf('.')) || newName;// 下载配置const downFileConfig: request.DownloadConfig = {url: url,filePath: uniqueFilePath,background: true,};// 执行下载const task = await request.downloadFile(context, downFileConfig);return { task: task, uniqueNameWithoutExt:uniqueNameWithoutExt, ext:ext.slice(1) };
}
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/931852.shtml
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!