打印
第一步:权限申请
在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.UIAbilityContext
this.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) };
}