1/* 2 * Copyright (c) 2023-2023 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16import type { PrinterCapability } from '@ohos/common'; 17import { MediaSizeUtil, Log, PrinterCapsOptions } from '@ohos/common'; 18import CheckEmptyUtils from '@ohos/common'; 19 20const TAG = 'LocalPrinterCapabilities'; 21 22export default class LocalPrinterCapabilities { 23 /** 24 * 构造PrinterCapability对象 25 * 26 * @param printerCapability 27 */ 28 static buildPrinterCapability(printerCapability: PrinterCapability, caps: PrinterCapability): void { 29 printerCapability.colorMode = caps.colorMode; 30 printerCapability.duplexMode = caps.duplexMode; 31 //set printPageSize 32 let sizeList: string[] = caps.pageSize.map((size) => { 33 return size.name; 34 }); 35 const codes: number[] = MediaSizeUtil.getCodesBySizes(sizeList); 36 printerCapability.pageSize = MediaSizeUtil.getMediaSizeArrayByCodes(LocalPrinterCapabilities.removeDuplicates(codes)); 37 } 38 39 /** 40 * 构造额外的参数, 传递给UI 41 */ 42 static buildExtraCaps(caps: PrinterCapability, printerUri: string): string { 43 let optionObject: PrinterCapsOptions = LocalPrinterCapabilities.parseOption(caps.options); 44 if (optionObject === undefined) { 45 return ''; 46 } 47 let options: object = { 48 supportedMediaTypes: LocalPrinterCapabilities.removeDuplicates(optionObject.supportedMediaTypes), 49 supportedQuality: optionObject.supportedQualities, 50 make: optionObject.make, 51 printerUri: printerUri 52 }; 53 return JSON.stringify(options); 54 } 55 56 private static parseOption(options: string): PrinterCapsOptions { 57 if (CheckEmptyUtils.checkStrIsEmpty(options)) { 58 return undefined; 59 } 60 let result: PrinterCapsOptions = undefined; 61 try { 62 result = JSON.parse(options); 63 } catch (error) { 64 Log.error(TAG, 'json parse error: ' + error); 65 } 66 return result; 67 } 68 69 /** 70 * remove duplicates 71 * 72 * @param array 73 */ 74 private static removeDuplicates(array: number[]): number[] { 75 return [...new Set<number>(array)] as number[]; 76 } 77}