This module provides APIs for printing-related operations, including file printing, print job event monitoring, printer discovery and management, and print job status update. It is applicable to scenarios where printing capabilities need to be integrated into an app.
The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version.
Defines a callback class for listening for print job status change events (such as blocking, success, failure, and cancellation) during print job execution. After obtaining a PrintTask instance using print.print, you can register a listener to listen for the status changes of the print job.
on(type: 'block', callback: Callback<void>): void
Subscribes to the block events of a print job. This API uses an asynchronous callback to return the result.
Required permissions: ohos.permission.PRINT
System capability: SystemCapability.Print.PrintFramework
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| type | string | Yes | Listening type. The value is fixed at 'block'. The print job is blocked. |
| callback | Callback<void> | Yes | Callback used to notify the caller that the print job is blocked. |
Error codes
For details about the error codes, see Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | the application does not have permission to call this function. |
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. |
Example
import { print } from '@kit.BasicServicesKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { fileUri } from '@kit.CoreFileKit';
@Entry
@Component
struct Index {
build() {
Scroll() {
Column({ space: 10 }) {
Button("Print").width('90%').height(50).onClick(() => {
let filePath = '/data/storage/el2/base/haps/entry/files/test.pdf';
let context = this.getUIContext().getHostContext();
print.print([fileUri.getUriFromPath(filePath)], context).then((printTask: print.PrintTask) => {
printTask.on('block', () => {
console.info('print state is block');
})
// ...
}).catch((error: BusinessError) => {
console.error(`Failed to print. Code: ${error.code}, message: ${error.message}`);
})
})
}
.justifyContent(FlexAlign.Center)
.constraintSize({ minHeight: '100%' })
.width('100%')
}
.height('100%')
}
} on(type: 'succeed', callback: Callback<void>): void
Subscribes to the success events of a print job. This API uses an asynchronous callback to return the result.
Required permissions: ohos.permission.PRINT
System capability: SystemCapability.Print.PrintFramework
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| type | string | Yes | Listening type. The value is fixed at 'succeed'. The print job is successful. |
| callback | Callback<void> | Yes | Callback used to notify the caller that the print job is successful. |
Error codes
For details about the error codes, see Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | the application does not have permission to call this function. |
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. |
Example
import { print } from '@kit.BasicServicesKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { fileUri } from '@kit.CoreFileKit';
@Entry
@Component
struct Index {
build() {
Scroll() {
Column({ space: 10 }) {
Button("Print").width('90%').height(50).onClick(() => {
let filePath = '/data/storage/el2/base/haps/entry/files/test.pdf';
let context = this.getUIContext().getHostContext();
print.print([fileUri.getUriFromPath(filePath)], context).then((printTask: print.PrintTask) => {
printTask.on('succeed', () => {
console.info('print state is succeed');
})
// ...
}).catch((error: BusinessError) => {
console.error(`Failed to print. Code: ${error.code}, message: ${error.message}`);
})
})
}
.justifyContent(FlexAlign.Center)
.constraintSize({ minHeight: '100%' })
.width('100%')
}
.height('100%')
}
} on(type: 'fail', callback: Callback<void>): void
Subscribes to the failure events of a print job. This API uses an asynchronous callback to return the result.
Required permissions: ohos.permission.PRINT
System capability: SystemCapability.Print.PrintFramework
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| type | string | Yes | Listening type. The value is fixed at 'fail'. The print job fails. |
| callback | Callback<void> | Yes | Callback used to notify the caller that the print job fails. |
Error codes
For details about the error codes, see Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | the application does not have permission to call this function. |
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. |
Example
import { print } from '@kit.BasicServicesKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { fileUri } from '@kit.CoreFileKit';
@Entry
@Component
struct Index {
build() {
Scroll() {
Column({ space: 10 }) {
Button("Print").width('90%').height(50).onClick(() => {
let filePath = '/data/storage/el2/base/haps/entry/files/test.pdf';
let context = this.getUIContext().getHostContext();
print.print([fileUri.getUriFromPath(filePath)], context).then((printTask: print.PrintTask) => {
printTask.on('fail', () => {
console.info('print state is fail');
})
// ...
}).catch((error: BusinessError) => {
console.error(`Failed to print. Code: ${error.code}, message: ${error.message}`);
})
})
}
.justifyContent(FlexAlign.Center)
.constraintSize({ minHeight: '100%' })
.width('100%')
}
.height('100%')
}
} on(type: 'cancel', callback: Callback<void>): void
Subscribes to the cancellation events of a print job. This API uses an asynchronous callback to return the result.
Required permissions: ohos.permission.PRINT
System capability: SystemCapability.Print.PrintFramework
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| type | string | Yes | Listening type. The value is fixed at 'cancel'. The print job is canceled. |
| callback | Callback<void> | Yes | Callback used to notify the caller that the print job is canceled. |
Error codes
For details about the error codes, see Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | the application does not have permission to call this function. |
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. |
Example
import { print } from '@kit.BasicServicesKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { fileUri } from '@kit.CoreFileKit';
@Entry
@Component
struct Index {
build() {
Scroll() {
Column({ space: 10 }) {
Button("Print").width('90%').height(50).onClick(() => {
let filePath = '/data/storage/el2/base/haps/entry/files/test.pdf';
let context = this.getUIContext().getHostContext();
print.print([fileUri.getUriFromPath(filePath)], context).then((printTask: print.PrintTask) => {
printTask.on('cancel', () => {
console.info('print state is cancel');
})
// ...
}).catch((error: BusinessError) => {
console.error(`Failed to print. Code: ${error.code}, message: ${error.message}`);
})
})
}
.justifyContent(FlexAlign.Center)
.constraintSize({ minHeight: '100%' })
.width('100%')
}
.height('100%')
}
} off(type: 'block', callback?: Callback<void>): void
Unsubscribes from the block events of a print job.
Required permissions: ohos.permission.PRINT
System capability: SystemCapability.Print.PrintFramework
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| type | string | Yes | Listening type. The value is fixed at 'block'. The print job is blocked. |
| callback | Callback<void> | No | Callback used to unsubscribe from the block events of a specified print job. If this parameter is not passed, all registered callbacks of the caller will be unregistered. |
Error codes
For details about the error codes, see Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | the application does not have permission to call this function. |
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. |
Example
import { print } from '@kit.BasicServicesKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { fileUri } from '@kit.CoreFileKit';
@Entry
@Component
struct Index {
build() {
Scroll() {
Column({ space: 10 }) {
Button("Print").width('90%').height(50).onClick(() => {
let filePath = '/data/storage/el2/base/haps/entry/files/test.pdf';
let context = this.getUIContext().getHostContext();
print.print([fileUri.getUriFromPath(filePath)], context).then((printTask: print.PrintTask) => {
printTask.off('block', () => {
console.info('unregister state block');
})
// ...
}).catch((error: BusinessError) => {
console.error(`Failed to print. Code: ${error.code}, message: ${error.message}`);
})
})
}
.justifyContent(FlexAlign.Center)
.constraintSize({ minHeight: '100%' })
.width('100%')
}
.height('100%')
}
} off(type: 'succeed', callback?: Callback<void>): void
Unsubscribes from the success events of a print job.
Required permissions: ohos.permission.PRINT
System capability: SystemCapability.Print.PrintFramework
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| type | string | Yes | Listening type. The value is fixed at 'succeed'. The print job is successful. |
| callback | Callback<void> | No | Callback used to unsubscribe from the success events of a specified print job. If this parameter is not passed, all registered callbacks of the caller will be unregistered. |
Error codes
For details about the error codes, see Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | the application does not have permission to call this function. |
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. |
Example
import { print } from '@kit.BasicServicesKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { fileUri } from '@kit.CoreFileKit';
@Entry
@Component
struct Index {
build() {
Scroll() {
Column({ space: 10 }) {
Button("Print").width('90%').height(50).onClick(() => {
let filePath = '/data/storage/el2/base/haps/entry/files/test.pdf';
let context = this.getUIContext().getHostContext();
print.print([fileUri.getUriFromPath(filePath)], context).then((printTask: print.PrintTask) => {
printTask.off('succeed', () => {
console.info('unregister state succeed');
})
// ...
}).catch((error: BusinessError) => {
console.error(`Failed to print. Code: ${error.code}, message: ${error.message}`);
})
})
}
.justifyContent(FlexAlign.Center)
.constraintSize({ minHeight: '100%' })
.width('100%')
}
.height('100%')
}
} off(type: 'fail', callback?: Callback<void>): void
Unsubscribes from the failure events of a print job.
Required permissions: ohos.permission.PRINT
System capability: SystemCapability.Print.PrintFramework
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| type | string | Yes | Listening type. The value is fixed at 'fail'. The print job fails. |
| callback | Callback<void> | No | Callback used to unsubscribe from the failure events of a specified print job. If this parameter is not passed, all registered callbacks of the caller will be unregistered. |
Error codes
For details about the error codes, see Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | the application does not have permission to call this function. |
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. |
Example
import { print } from '@kit.BasicServicesKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { fileUri } from '@kit.CoreFileKit';
@Entry
@Component
struct Index {
build() {
Scroll() {
Column({ space: 10 }) {
Button("Print").width('90%').height(50).onClick(() => {
let filePath = '/data/storage/el2/base/haps/entry/files/test.pdf';
let context = this.getUIContext().getHostContext();
print.print([fileUri.getUriFromPath(filePath)], context).then((printTask: print.PrintTask) => {
printTask.off('fail', () => {
console.info('unregister state fail');
})
// ...
}).catch((error: BusinessError) => {
console.error(`Failed to print. Code: ${error.code}, message: ${error.message}`);
})
})
}
.justifyContent(FlexAlign.Center)
.constraintSize({ minHeight: '100%' })
.width('100%')
}
.height('100%')
}
} off(type: 'cancel', callback?: Callback<void>): void
Unsubscribes from the cancellation events of a print job.
Required permissions: ohos.permission.PRINT
System capability: SystemCapability.Print.PrintFramework
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| type | string | Yes | Listening type. The value is fixed at 'cancel'. The print job is canceled. |
| callback | Callback<void> | No | Callback used to unsubscribe from the cancellation events of a specified print job. If this parameter is not passed, all registered callbacks of the caller will be unregistered. |
Error codes
For details about the error codes, see Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | the application does not have permission to call this function. |
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. |
Example
import { print } from '@kit.BasicServicesKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { fileUri } from '@kit.CoreFileKit';
@Entry
@Component
struct Index {
build() {
Scroll() {
Column({ space: 10 }) {
Button("Print").width('90%').height(50).onClick(() => {
let filePath = '/data/storage/el2/base/haps/entry/files/test.pdf';
let context = this.getUIContext().getHostContext();
print.print([fileUri.getUriFromPath(filePath)], context).then((printTask: print.PrintTask) => {
printTask.off('cancel', () => {
console.info('unregister state cancel');
})
// ...
}).catch((error: BusinessError) => {
console.error(`Failed to print. Code: ${error.code}, message: ${error.message}`);
})
})
}
.justifyContent(FlexAlign.Center)
.constraintSize({ minHeight: '100%' })
.width('100%')
}
.height('100%')
}
} Provides information about the document to print. This API must be implemented by a third-party application. This API provides a callback to listen for file rendering and print job status events. You can pass a PrintDocumentAdapter instance through the print.print API.
onStartLayoutWrite(jobId: string, oldAttrs: PrintAttributes, newAttrs: PrintAttributes, fd: number, writeResultCallback: (jobId: string, writeResult: PrintFileCreationState) => void): void
The printing service uses this API to pass the file descriptor of an empty PDF file to the third-party app. The third-party app uses the new printing parameters to update the file to be printed. After the update is complete, the third-party app notifies the printing service using writeResultCallback.
Required permissions: ohos.permission.PRINT
System capability: SystemCapability.Print.PrintFramework
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| jobId | string | Yes | ID of the print job. |
| oldAttrs | PrintAttributes | Yes | Old print attributes. |
| newAttrs | PrintAttributes | Yes | New print attributes. The app uses this parameter to update the file to be printed. |
| fd | number | Yes | PDF file descriptor sent to the API caller. |
| writeResultCallback | (jobId: string, writeResult: PrintFileCreationState) => void | Yes | Callback used to print the updated file. |
Error codes
For details about the error codes, see Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | the application does not have permission to call this function. |
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. |
Example
import { print } from '@kit.BasicServicesKit';
class MyPrintDocumentAdapter implements print.PrintDocumentAdapter {
onStartLayoutWrite(jobId: string, oldAttrs: print.PrintAttributes, newAttrs: print.PrintAttributes, fd: number,
writeResultCallback: (jobId: string, writeResult: print.PrintFileCreationState) => void) {
writeResultCallback(jobId, print.PrintFileCreationState.PRINT_FILE_CREATED);
}
onJobStateChanged(jobId: string, state: print.PrintDocumentAdapterState) {
if (state === print.PrintDocumentAdapterState.PREVIEW_DESTROY) {
console.info('PREVIEW_DESTROY');
} else if (state === print.PrintDocumentAdapterState.PRINT_TASK_SUCCEED) {
console.info('PRINT_TASK_SUCCEED');
} else if (state === print.PrintDocumentAdapterState.PRINT_TASK_FAIL) {
console.info('PRINT_TASK_FAIL');
} else if (state === print.PrintDocumentAdapterState.PRINT_TASK_CANCEL) {
console.info('PRINT_TASK_CANCEL');
} else if (state === print.PrintDocumentAdapterState.PRINT_TASK_BLOCK) {
console.info('PRINT_TASK_BLOCK');
}
}
} onJobStateChanged(jobId: string, state: PrintDocumentAdapterState): void
Registers a listener for print job state changes.
Required permissions: ohos.permission.PRINT
System capability: SystemCapability.Print.PrintFramework
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| jobId | string | Yes | ID of the print job. |
| state | PrintDocumentAdapterState | Yes | New state of the print job. |
Error codes
For details about the error codes, see Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | the application does not have permission to call this function. |
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. |
Example
import { print } from '@kit.BasicServicesKit';
import { BusinessError } from '@kit.BasicServicesKit';
class MyPrintDocumentAdapter implements print.PrintDocumentAdapter {
onStartLayoutWrite(jobId: string, oldAttrs: print.PrintAttributes, newAttrs: print.PrintAttributes, fd: number,
writeResultCallback: (jobId: string, writeResult: print.PrintFileCreationState) => void) {
writeResultCallback(jobId, print.PrintFileCreationState.PRINT_FILE_CREATED);
}
onJobStateChanged(jobId: string, state: print.PrintDocumentAdapterState) {
if (state === print.PrintDocumentAdapterState.PREVIEW_DESTROY) {
console.info('PREVIEW_DESTROY');
} else if (state === print.PrintDocumentAdapterState.PRINT_TASK_SUCCEED) {
console.info('PRINT_TASK_SUCCEED');
} else if (state === print.PrintDocumentAdapterState.PRINT_TASK_FAIL) {
console.info('PRINT_TASK_FAIL');
} else if (state === print.PrintDocumentAdapterState.PRINT_TASK_CANCEL) {
console.info('PRINT_TASK_CANCEL');
} else if (state === print.PrintDocumentAdapterState.PRINT_TASK_BLOCK) {
console.info('PRINT_TASK_BLOCK');
}
}
} print(files: Array<string>, callback: AsyncCallback<PrintTask>): void
Prints files. This API uses an asynchronous callback to return the result. To start the system print preview page, call the print API and pass in context.
This API is supported since API version 10 and deprecated since API version 26.0.0. You are advised to use print instead.
Required permissions: ohos.permission.PRINT
System capability: SystemCapability.Print.PrintFramework
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| files | Array<string> | Yes | List of files to print. Images (in .jpg, .png, .gif, .bmp, or .webp format) and PDF files are supported. You should save the files to the application sandbox, obtain the sandbox URI through fileUri.getUriFromPath, and then pass this URI as a parameter to this API. |
| callback | AsyncCallback<PrintTask> | Yes | Callback to be invoked when the print job is finished. |
Error codes
For details about the error codes, see Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | the application does not have permission to call this function. |
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. |
Example
import { print } from '@kit.BasicServicesKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { fileUri } from '@kit.CoreFileKit';
// Pass in the URIs of the files.
let filePath = '/data/storage/el2/base/haps/entry/files/test.pdf';
print.print([fileUri.getUriFromPath(filePath)], (error: BusinessError, printTask: print.PrintTask) => {
if (error) {
console.error(`Failed to print. Code: ${error.code}, message: ${error.message}`);
} else {
printTask.on('succeed', () => {
console.info('print state is succeed');
})
// ...
}
}) print(files: Array<string>): Promise<PrintTask>
Prints files. This API uses a promise to return the result. To start the system print preview page, call the print API and pass in context.
This API is supported since API version 10 and deprecated since API version 26.0.0. You are advised to use print instead.
Required permissions: ohos.permission.PRINT
System capability: SystemCapability.Print.PrintFramework
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| files | Array<string> | Yes | List of files to print. Images (in .jpg, .png, .gif, .bmp, or .webp format) and PDF files are supported. You should save the files to the application sandbox, obtain the sandbox URI through fileUri.getUriFromPath, and then pass this URI as a parameter to this API. |
Return value
Error codes
For details about the error codes, see Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | the application does not have permission to call this function. |
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. |
Example
import { print } from '@kit.BasicServicesKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { fileUri } from '@kit.CoreFileKit';
// Pass in the URIs of the files.
let filePath = '/data/storage/el2/base/haps/entry/files/test.pdf';
print.print([fileUri.getUriFromPath(filePath)]).then((printTask: print.PrintTask) => {
printTask.on('succeed', () => {
console.info('print state is succeed');
})
// ...
}).catch((error: BusinessError) => {
console.error(`Failed to print. Code: ${error.code}, message: ${error.message}`);
}) print(files: Array<string>, context: Context, callback: AsyncCallback<PrintTask>): void
Prints files. The system print preview page is started. This API uses an asynchronous callback to return the result.
Required permissions: ohos.permission.PRINT
System capability: SystemCapability.Print.PrintFramework
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| files | Array<string> | Yes | List of files to be printed. Currently, the following file types are supported: .bm, .bmp, .doc, .docm, .docx, .dot, .dotm, .dotx, .gif, .jfif, .jpe, .jpeg, .jpg, pdf, .pot, .potm, .potx, .pps, .ppsm, .ppsx, .ppt, .pptm, .pptx, .png, .rtf, .txt, .webp, .wps, .xls, .xlsb, .xlsm, .xlsx, .xlt, .xltx, and .xml. You should save the files to the application sandbox, obtain the sandbox URI through fileUri.getUriFromPath, and then pass this URI as a parameter to this API. |
| context | Context | Yes | UIAbilityContext used to start the system print UI. |
| callback | AsyncCallback<PrintTask> | Yes | Callback to be invoked when the print job is finished. |
Error codes
For details about the error codes, see Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | the application does not have permission to call this function. |
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. |
Example
import { print } from '@kit.BasicServicesKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { fileUri } from '@kit.CoreFileKit';
@Entry
@Component
struct Index {
build() {
Scroll() {
Column({ space: 10 }) {
Button("Print").width('90%').height(50).onClick(() => {
let filePath = '/data/storage/el2/base/haps/entry/files/test.pdf';
let context = this.getUIContext().getHostContext();
print.print([fileUri.getUriFromPath(filePath)], context, (error: BusinessError, printTask: print.PrintTask) => {
if (error) {
console.error(`Failed to print. Code: ${error.code}, message: ${error.message}`);
} else {
printTask.on('succeed', () => {
console.info('print state is succeed');
})
// ...
}
})
})
}
.justifyContent(FlexAlign.Center)
.constraintSize({ minHeight: '100%' })
.width('100%')
}
.height('100%')
}
} print(files: Array<string>, context: Context): Promise<PrintTask>
Prints files. The system print preview page is started. This API uses a promise to return the result.
Required permissions: ohos.permission.PRINT
System capability: SystemCapability.Print.PrintFramework
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| files | Array<string> | Yes | List of files to be printed. Currently, the following file types are supported: .bm, .bmp, .doc, .docm, .docx, .dot, .dotm, .dotx, .gif, .jfif, .jpe, .jpeg, .jpg, pdf, .pot, .potm, .potx, .pps, .ppsm, .ppsx, .ppt, .pptm, .pptx, .png, .rtf, .txt, .webp, .wps, .xls, .xlsb, .xlsm, .xlsx, .xlt, .xltx, and .xml. You should save the files to the application sandbox, obtain the sandbox URI through fileUri.getUriFromPath, and then pass this URI as a parameter to this API. |
| context | Context | Yes | UIAbilityContext used to start the system print UI. |
Return value
Error codes
For details about the error codes, see Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | the application does not have permission to call this function. |
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. |
Example
import { print } from '@kit.BasicServicesKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { fileUri } from '@kit.CoreFileKit';
@Entry
@Component
struct Index {
build() {
Scroll() {
Column({ space: 10 }) {
Button("Print").width('90%').height(50).onClick(() => {
let filePath = '/data/storage/el2/base/haps/entry/files/test.pdf';
let context = this.getUIContext().getHostContext();
print.print([fileUri.getUriFromPath(filePath)], context).then((printTask: print.PrintTask) => {
printTask.on('succeed', () => {
console.info('print state is succeed');
})
// ...
}).catch((error: BusinessError) => {
console.error(`Failed to print. Code: ${error.code}, message: ${error.message}`);
})
})
}
.justifyContent(FlexAlign.Center)
.constraintSize({ minHeight: '100%' })
.width('100%')
}
.height('100%')
}
} print(jobName: string, printAdapter: PrintDocumentAdapter, printAttributes: PrintAttributes, context: Context): Promise<PrintTask>
Prints a file. This API uses a promise to return the result. Currently, only the .pdf file type is supported. When a third-party app needs to pass the file descriptor (FD) to start the system print preview page for printing, this API can be used to pass a custom PrintDocumentAdapter value to update the file to be printed.
Required permissions: ohos.permission.PRINT
System capability: SystemCapability.Print.PrintFramework
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| jobName | string | Yes | Name of the file to print, for example, test.pdf. Currently, only .pdf files are supported. The printer uses the onStartLayoutWrite API to send the fd of the empty PDF file to the API caller. The API caller uses the new print attributes to update the file to print. |
| printAdapter | PrintDocumentAdapter | Yes | PrintDocumentAdapter API instance implemented by a third-party application. |
| printAttributes | PrintAttributes | Yes | Print attributes. |
| context | Context | Yes | UIAbilityContext used to start the system print UI. |
Return value
Error codes
For details about the error codes, see Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | the application does not have permission to call this function. |
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. |
Example
import { print } from '@kit.BasicServicesKit';
import { BusinessError } from '@kit.BasicServicesKit';
@Entry
@Component
struct Index {
build() {
Scroll() {
Column({ space: 10 }) {
Button("Print").width('90%').height(50).onClick(() => {
let jobName : string = 'jobName';
// The PrintDocumentAdapter API needs to be implemented for printAdapter. The following is a simple example for reference.
let printAdapter : print.PrintDocumentAdapter = new MyPrintDocumentAdapter();
let printAttributes : print.PrintAttributes = {
copyNumber: 1,
pageRange: {
startPage: 0,
endPage: 5,
pages: []
},
pageSize: print.PrintPageType.PAGE_ISO_A3,
directionMode: print.PrintDirectionMode.DIRECTION_MODE_AUTO,
colorMode: print.PrintColorMode.COLOR_MODE_MONOCHROME,
duplexMode: print.PrintDuplexMode.DUPLEX_MODE_NONE
};
let context = this.getUIContext().getHostContext();
print.print(jobName, printAdapter, printAttributes, context).then((printTask: print.PrintTask) => {
printTask.on('succeed', () => {
console.info('print state is succeed');
})
// ...
}).catch((error: BusinessError) => {
console.error(`Failed to print. Code: ${error.code}, message: ${error.message}`);
})
})
}
.justifyContent(FlexAlign.Center)
.constraintSize({ minHeight: '100%' })
.width('100%')
}
.height('100%')
}
}
class MyPrintDocumentAdapter implements print.PrintDocumentAdapter {
onStartLayoutWrite(jobId: string, oldAttrs: print.PrintAttributes, newAttrs: print.PrintAttributes, fd: number,
writeResultCallback: (jobId: string, writeResult: print.PrintFileCreationState) => void) {
writeResultCallback(jobId, print.PrintFileCreationState.PRINT_FILE_CREATED);
}
onJobStateChanged(jobId: string, state: print.PrintDocumentAdapterState) {
if (state === print.PrintDocumentAdapterState.PREVIEW_DESTROY) {
console.info('PREVIEW_DESTROY');
} else if (state === print.PrintDocumentAdapterState.PRINT_TASK_SUCCEED) {
console.info('PRINT_TASK_SUCCEED');
} else if (state === print.PrintDocumentAdapterState.PRINT_TASK_FAIL) {
console.info('PRINT_TASK_FAIL');
} else if (state === print.PrintDocumentAdapterState.PRINT_TASK_CANCEL) {
console.info('PRINT_TASK_CANCEL');
} else if (state === print.PrintDocumentAdapterState.PRINT_TASK_BLOCK) {
console.info('PRINT_TASK_BLOCK');
}
}
} Defines the print attributes.
System capability: SystemCapability.Print.PrintFramework
Attributes
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| copyNumber | number | No | Yes | Number of printed file copies. The value must be a positive integer. If no value is passed, 0 is used by default. |
| pageRange | PrintPageRange | No | Yes | Page range of the file to print. If no value is passed, the default value is an empty range object. |
| pageSize | PrintPageSize | PrintPageType | No | Yes | Paper size of the file to print. If no value is passed, the default value is an empty paper size object. |
| directionMode | PrintDirectionMode | No | Yes | Print direction mode. If no value is passed, 0 is used by default. |
| colorMode | PrintColorMode | No | Yes | Color mode of the files to print. If no value is passed, 0 is used by default. |
| duplexMode | PrintDuplexMode | No | Yes | Duplex mode of the files to print. If no value is passed, 0 is used by default. |
Defines the print range.
System capability: SystemCapability.Print.PrintFramework
Attributes
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| startPage | number | No | Yes | Start page. The value is a positive integer. The default value is 1. |
| endPage | number | No | Yes | End page. The value must be a positive integer. The default value is the maximum number of pages in the file to be printed. |
| pages | Array<number> | No | Yes | Page range set of the file to print. The default value is empty. |
Defines the size of the printed page.
System capability: SystemCapability.Print.PrintFramework
Attributes
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| id | string | No | No | Paper size ID. |
| name | string | No | No | Paper size name. |
| width | number | No | No | Page width, in mils (1 mil = 1/1000 inch). |
| height | number | No | No | Page height, in mils (1 mil = 1/1000 inch). |
Enumerates the print direction modes.
System capability: SystemCapability.Print.PrintFramework
| Name | Value | Description |
|---|---|---|
| DIRECTION_MODE_AUTO | 0 | Automatic. |
| DIRECTION_MODE_PORTRAIT | 1 | Portrait mode. |
| DIRECTION_MODE_LANDSCAPE | 2 | Landscape mode. |
Enumerates the color modes.
System capability: SystemCapability.Print.PrintFramework
| Name | Value | Description |
|---|---|---|
| COLOR_MODE_MONOCHROME | 0 | Black and white. |
| COLOR_MODE_COLOR | 1 | Color. |
Enumerates the duplex modes.
System capability: SystemCapability.Print.PrintFramework
| Name | Value | Description |
|---|---|---|
| DUPLEX_MODE_NONE | 0 | Simplex (single-sided). |
| DUPLEX_MODE_LONG_EDGE | 1 | Duplex (double-sided) with flipping on long edge. |
| DUPLEX_MODE_SHORT_EDGE | 2 | Duplex (double-sided) with flipping on short edge. |
Enumerates the print page types.
System capability: SystemCapability.Print.PrintFramework
| Name | Value | Description |
|---|---|---|
| PAGE_ISO_A3 | 0 | A3. |
| PAGE_ISO_A4 | 1 | A4. |
| PAGE_ISO_A5 | 2 | A5. |
| PAGE_JIS_B5 | 3 | B5. |
| PAGE_ISO_C5 | 4 | C5. |
| PAGE_ISO_DL | 5 | DL. |
| PAGE_LETTER | 6 | Letter. |
| PAGE_LEGAL | 7 | Legal. |
| PAGE_PHOTO_4X6 | 8 | 4 x 6 photo paper. |
| PAGE_PHOTO_5X7 | 9 | 5 x 7 photo paper. |
| PAGE_INT_DL_ENVELOPE | 10 | International envelope DL. |
| PAGE_B_TABLOID | 11 | B Tabloid. |
Enumerates the print job states.
System capability: SystemCapability.Print.PrintFramework
| Name | Value | Description |
|---|---|---|
| PREVIEW_DESTROY | 0 | Print preview page destroyed. |
| PRINT_TASK_SUCCEED | 1 | The print job is successful. |
| PRINT_TASK_FAIL | 2 | The print job fails. |
| PRINT_TASK_CANCEL | 3 | The print job is canceled. |
| PRINT_TASK_BLOCK | 4 | The print job is blocked. |
Enumerates the print file creation status.
System capability: SystemCapability.Print.PrintFramework
| Name | Value | Description |
|---|---|---|
| PRINT_FILE_CREATED | 0 | The print file is created successfully. |
| PRINT_FILE_CREATION_FAILED | 1 | The print file fails to be created. |
| PRINT_FILE_CREATED_UNRENDERED | 2 | The print file is successfully created but not rendered. |
Enumerates the printer states.
System capability: SystemCapability.Print.PrintFramework
| Name | Value | Description |
|---|---|---|
| PRINTER_ADDED | 0 | A new printer is added. |
| PRINTER_REMOVED | 1 | The printer is removed. |
| PRINTER_CAPABILITY_UPDATED | 2 | The printer capabilities are updated. |
| PRINTER_CONNECTED | 3 | The printer is connected. |
| PRINTER_DISCONNECTED | 4 | The printer is disconnected. |
| PRINTER_RUNNING | 5 | The printer is running. |
Enumerates the print job states.
System capability: SystemCapability.Print.PrintFramework
| Name | Value | Description |
|---|---|---|
| PRINT_JOB_PREPARE | 0 | The printer is prepared for the print job. |
| PRINT_JOB_QUEUED | 1 | The print job is on the print queue of the printer. |
| PRINT_JOB_RUNNING | 2 | The print job is being executed. |
| PRINT_JOB_BLOCKED | 3 | The print job is blocked. |
| PRINT_JOB_COMPLETED | 4 | The print job is complete. |
Enumerates the print job substates.
System capability: SystemCapability.Print.PrintFramework
| Name | Value | Description |
|---|---|---|
| PRINT_JOB_COMPLETED_SUCCESS | 0 | The print job is successful. |
| PRINT_JOB_COMPLETED_FAILED | 1 | The print job fails. |
| PRINT_JOB_COMPLETED_CANCELLED | 2 | The print job is canceled. |
| PRINT_JOB_COMPLETED_FILE_CORRUPTED | 3 | The print file is corrupted. |
| PRINT_JOB_BLOCK_OFFLINE | 4 | The printer is offline. |
| PRINT_JOB_BLOCK_BUSY | 5 | The printer is occupied by another process. |
| PRINT_JOB_BLOCK_CANCELLED | 6 | The print job is canceled due to a block. |
| PRINT_JOB_BLOCK_OUT_OF_PAPER | 7 | The printer is out of paper. |
| PRINT_JOB_BLOCK_OUT_OF_INK | 8 | The printer is out of ink. |
| PRINT_JOB_BLOCK_OUT_OF_TONER | 9 | The printer is out of toner. |
| PRINT_JOB_BLOCK_JAMMED | 10 | The printer is in a paper jam. |
| PRINT_JOB_BLOCK_DOOR_OPEN | 11 | The printer door is open. |
| PRINT_JOB_BLOCK_SERVICE_REQUEST | 12 | Print service request. |
| PRINT_JOB_BLOCK_LOW_ON_INK | 13 | The printer is low on ink. |
| PRINT_JOB_BLOCK_LOW_ON_TONER | 14 | The printer is low on toner. |
| PRINT_JOB_BLOCK_REALLY_LOW_ON_INK | 15 | The printer is extremely low on ink. |
| PRINT_JOB_BLOCK_BAD_CERTIFICATE | 16 | The print certificate is incorrect. |
| PRINT_JOB_BLOCK_DRIVER_EXCEPTION20+ | 17 | The print driver is abnormal. |
| PRINT_JOB_BLOCK_ACCOUNT_ERROR | 18 | There is an error with the printer account. |
| PRINT_JOB_BLOCK_PRINT_PERMISSION_ERROR | 19 | There is an error with the printer permission. |
| PRINT_JOB_BLOCK_PRINT_COLOR_PERMISSION_ERROR | 20 | There is an error with the color printing permission. |
| PRINT_JOB_BLOCK_NETWORK_ERROR | 21 | The printer fails to connect to the network. |
| PRINT_JOB_BLOCK_SERVER_CONNECTION_ERROR | 22 | The printer fails to connect to the server. |
| PRINT_JOB_BLOCK_LARGE_FILE_ERROR | 23 | There is an error with a large file printing. |
| PRINT_JOB_BLOCK_FILE_PARSING_ERROR | 24 | There is an error with file parsing. |
| PRINT_JOB_BLOCK_SLOW_FILE_CONVERSION | 25 | The file conversion is slow. |
| PRINT_JOB_RUNNING_UPLOADING_FILES | 26 | The file is uploading. |
| PRINT_JOB_RUNNING_CONVERTING_FILES | 27 | The file is converting. |
| PRINT_JOB_BLOCK_FILE_UPLOADING_ERROR18+ | 30 | The file fails to be uploaded. |
| PRINT_JOB_BLOCK_DRIVER_MISSING20+ | 34 | The print driver is missing. |
| PRINT_JOB_BLOCK_INTERRUPT20+ | 35 | The print job is interrupted. |
| PRINT_JOB_BLOCK_PRINTER_UNAVAILABLE20+ | 98 | The printer is unavailable. |
| PRINT_JOB_BLOCK_UNKNOWN | 99 | There is an unknown error with the printer. |
Enumerates the print error codes.
System capability: SystemCapability.Print.PrintFramework
| Name | Value | Description |
|---|---|---|
| E_PRINT_NONE | 0 | No error. |
| E_PRINT_NO_PERMISSION | 201 | No permission. Request the required permission based on the permission requirements of the corresponding API and declare the permission in the configuration file. |
| E_PRINT_INVALID_PARAMETER | 401 | Invalid parameter. Check the parameter type and value range. |
| E_PRINT_GENERIC_FAILURE | 13100001 | Generic printing failure. Check the running status of the print service and try again. |
| E_PRINT_RPC_FAILURE | 13100002 | RPC failure. Check the RPC communication status and try again. |
| E_PRINT_SERVER_FAILURE | 13100003 | Print service failure. Check whether the print service is running properly and try again. |
| E_PRINT_INVALID_EXTENSION | 13100004 | Invalid print extension. Check whether the extension capability is correctly implemented. |
| E_PRINT_INVALID_PRINTER | 13100005 | Invalid printer. Check whether the printer ID and printer information are correct and try again. |
| E_PRINT_INVALID_PRINT_JOB | 13100006 | Invalid print job. Check whether the job ID and status are correct. |
| E_PRINT_FILE_IO | 13100007 | File input/output error. Check whether the file path, file status, and operation are correct. |
| E_PRINT_TOO_MANY_FILES18+ | 13100010 | Excessive files. Maximum number: 99. |
| E_PRINT_SMB_LOGIN_LOCKOUT24+ | 13100012 | The SMB-based shared printer account is locked due to multiple failed login attempts. Try again after the account is unlocked, or contact the administrator. Model restriction: This API can be used only in the stage model. |
| E_PRINT_SMB_CONNECTION_FAILURE24+ | 13100013 | The SMB-based shared printer fails to be connected (due to a network error, unreachable host, or blocked port). Model restriction: This API can be used only in the stage model. |
| E_PRINT_SMB_INVALID_CREDENTIALS24+ | 13100014 | The SMB-based shared printer account or password is incorrect. Model restriction: This API can be used only in the stage model. |
Enumerates print application events.
System capability: SystemCapability.Print.PrintFramework
| Name | Value | Description |
|---|---|---|
| APPLICATION_CREATED | 0 | Starts the print application. |
| APPLICATION_CLOSED_FOR_STARTED | 1 | Closes the print application by clicking Start. |
| APPLICATION_CLOSED_FOR_CANCELED | 2 | Closes the print application by clicking Cancel. |
addPrinterToDiscovery(printerInformation: PrinterInformation): Promise<void>
Adds a printer to the printer discovery list. This API uses a promise to return the result.
Required permissions: ohos.permission.PRINT
System capability: SystemCapability.Print.PrintFramework
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| printerInformation | PrinterInformation | Yes | The added printer. |
Return value
| Type | Description |
|---|---|
| Promise<void> | Promise that returns no value. resolve indicates that the operation is successful, and reject indicates that the operation fails. |
Error codes
For details about the error codes, see Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | the application does not have permission to call this function. |
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. |
Example
import { print } from '@kit.BasicServicesKit';
import { BusinessError } from '@kit.BasicServicesKit';
let printerInformation : print.PrinterInformation = {
printerId : 'testPrinterId', // printer ID can be obtained from the on('printerChange') callback.
printerName : 'testPrinterName',
printerStatus : 0,
description : 'testDesc',
uri : 'testUri',
printerMake : 'testPrinterMake',
options : 'testOps'
};
print.addPrinterToDiscovery(printerInformation).then(() => {
console.info('addPrinterToDiscovery success');
}).catch((error: BusinessError) => {
console.error(`Failed to addPrinterToDiscovery. Code: ${error.code}, message: ${error.message}`);
}) updatePrinterInDiscovery(printerInformation: PrinterInformation): Promise<void>
Updates the printer capabilities to the printer discovery list. This API uses a promise to return the result.
Required permissions: ohos.permission.PRINT
System capability: SystemCapability.Print.PrintFramework
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| printerInformation | PrinterInformation | Yes | Printer whose capability is to be updated. |
Return value
| Type | Description |
|---|---|
| Promise<void> | Promise that returns no value. resolve indicates that the operation is successful, and reject indicates that the operation fails. |
Error codes
For details about the error codes, see Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | the application does not have permission to call this function. |
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. |
Example
import { print } from '@kit.BasicServicesKit';
import { BusinessError } from '@kit.BasicServicesKit';
let testPageSize : print.PrintPageSize = {
id : 'ISO_A4',
name : 'iso_a4_210x297mm',
width : 8268,
height : 11692
};
let testCapability : print.PrinterCapabilities = {
supportedPageSizes : [testPageSize],
supportedColorModes : [print.PrintColorMode.COLOR_MODE_MONOCHROME],
supportedDuplexModes : [print.PrintDuplexMode.DUPLEX_MODE_NONE],
supportedMediaTypes : ['stationery'],
supportedQualities : [print.PrintQuality.QUALITY_NORMAL],
supportedOrientations : [print.PrintOrientationMode.ORIENTATION_MODE_PORTRAIT],
options : 'testOptions'
};
let printerInformation : print.PrinterInformation = {
printerId : 'testPrinterId', // printer ID can be obtained from the on('printerChange') callback.
printerName : 'testPrinterName',
printerStatus : 0,
description : 'testDesc',
capability : testCapability,
uri : 'testUri',
printerMake : 'testPrinterMake',
options : 'testOptions'
};
print.updatePrinterInDiscovery(printerInformation).then(() => {
console.info('updatePrinterInDiscovery success');
}).catch((error: BusinessError) => {
console.error(`Failed to updatePrinterInDiscovery. Code: ${error.code}, message: ${error.message}`);
}) removePrinterFromDiscovery(printerId: string): Promise<void>
Removes a printer from the printer discovery list. This API uses a promise to return the result.
Required permissions: ohos.permission.PRINT
System capability: SystemCapability.Print.PrintFramework
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| printerId | string | Yes | ID of the printer to be removed. |
Return value
| Type | Description |
|---|---|
| Promise<void> | Promise that returns no value. resolve indicates that the operation is successful, and reject indicates that the operation fails. |
Error codes
For details about the error codes, see Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | the application does not have permission to call this function. |
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. |
Example
import { print } from '@kit.BasicServicesKit';
import { BusinessError } from '@kit.BasicServicesKit';
// printer ID can be obtained from the on('printerChange') callback.
let printerId : string = 'testPrinterId';
print.removePrinterFromDiscovery(printerId).then(() => {
console.info('removePrinterFromDiscovery success');
}).catch((error: BusinessError) => {
console.error(`Failed to removePrinterFromDiscovery. Code: ${error.code}, message: ${error.message}`);
}) getPrinterInformationById(printerId: string): Promise<PrinterInformation>
Obtains printer information based on the printer ID. This API uses a promise to return the result.
Required permissions: ohos.permission.PRINT
System capability: SystemCapability.Print.PrintFramework
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| printerId | string | Yes | Printer ID used to obtain information. |
Return value
| Type | Description |
|---|---|
| Promise<PrinterInformation> | Promise used to return the printer information. |
Error codes
For details about the error codes, see Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | the application does not have permission to call this function. |
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. |
Example
import { print } from '@kit.BasicServicesKit';
import { BusinessError } from '@kit.BasicServicesKit';
// printer ID can be obtained from the on('printerChange') callback.
let printerId : string = 'testPrinterId';
print.getPrinterInformationById(printerId).then((printerInformation : print.PrinterInformation) => {
console.info('getPrinterInformationById data : ' + JSON.stringify(printerInformation));
}).catch((error: BusinessError) => {
console.error(`Failed to getPrinterInformationById. Code: ${error.code}, message: ${error.message}`);
}) Defines the printer information.
System capability: SystemCapability.Print.PrintFramework
Attributes
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| printerId | string | No | No | Printer ID. |
| printerName | string | No | No | Printer name. |
| printerStatus | PrinterStatus | No | No | Printer state. |
| description | string | No | Yes | Printer description. If no value is passed, the default value is an empty string. |
| capability | PrinterCapabilities | No | Yes | Printer capabilities. |
| uri | string | No | Yes | Printer URI. If no value is passed, the default value is an empty string. |
| printerMake | string | No | Yes | Printer model. If no value is passed, the default value is an empty string. |
| preferences18+ | PrinterPreferences | No | Yes | Printer preferences. |
| alias18+ | string | No | Yes | Printer alias. If no value is passed, the default value is an empty string. |
| selectedDriver24+ | PpdInfo | No | Yes | Information about the driver selected when a printer is added. Model restriction: This API can be used only in the stage model. |
| selectedProtocol24+ | string | No | Yes | Protocol used when a printer is added. If no value is passed, the default value is an empty string. Model restriction: This API can be used only in the stage model. |
| options | string | No | Yes | Printer details. If no value is passed, the default value is an empty string. |
Defines the printer capabilities.
System capability: SystemCapability.Print.PrintFramework
Attributes
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| supportedPageSizes | Array<PrintPageSize> | No | No | List of paper sizes supported by the printer. |
| supportedColorModes | Array<PrintColorMode> | No | No | List of color modes supported by the printer. |
| supportedDuplexModes | Array<PrintDuplexMode> | No | No | List of single- and double-sided modes supported by the printer. |
| supportedMediaTypes | Array<string> | No | Yes | List of paper types supported by the printer. If no value is passed, the default value is an empty list. |
| supportedQualities | Array<PrintQuality> | No | Yes | List of print quality supported by the printer. If no value is passed, the default value is an empty list. |
| supportedOrientations | Array<PrintOrientationMode> | No | Yes | List of print directions supported by the printer. If no value is passed, the default value is an empty list. |
| options | string | No | Yes | Printer capability details. If no value is passed, the default value is an empty string. |
| vendorPrinterPrefAbility | string | No | Yes | Printer preference settings page provided by the printer driver vendor. If no value is passed, the default value is an empty string. Model restriction: This API can be used only in the stage model. Since: 26.0.0 |
| vendorJobAttrAbility | string | No | Yes | Print job settings page provided by the printer driver vendor. If no value is passed, the default value is an empty string. Model restriction: This API can be used only in the stage model. Since: 26.0.0 |
Enumerates the print qualities.
System capability: SystemCapability.Print.PrintFramework
| Name | Value | Description |
|---|---|---|
| QUALITY_DRAFT | 3 | Draft |
| QUALITY_NORMAL | 4 | Standard |
| QUALITY_HIGH | 5 | High |
Enumerates the print directions.
System capability: SystemCapability.Print.PrintFramework
| Name | Value | Description |
|---|---|---|
| ORIENTATION_MODE_PORTRAIT | 0 | Portrait mode. |
| ORIENTATION_MODE_LANDSCAPE | 1 | Landscape mode. |
| ORIENTATION_MODE_REVERSE_LANDSCAPE | 2 | Reverse landscape mode. |
| ORIENTATION_MODE_REVERSE_PORTRAIT | 3 | Reverse portrait mode. |
| ORIENTATION_MODE_NONE | 4 | Adaptive mode. |
Enumerates the printer states.
System capability: SystemCapability.Print.PrintFramework
| Name | Value | Description |
|---|---|---|
| PRINTER_IDLE | 0 | The printer is idle. |
| PRINTER_BUSY | 1 | The printer is busy. |
| PRINTER_UNAVAILABLE | 2 | The printer is unavailable. |
Defines the printer preferences.
System capability: SystemCapability.Print.PrintFramework
Attributes
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| defaultDuplexMode | PrintDuplexMode | No | Yes | Default duplex mode. |
| defaultPrintQuality | PrintQuality | No | Yes | Default print quality. |
| defaultMediaType | string | No | Yes | Default paper type. |
| defaultPageSizeId | string | No | Yes | ID of the default paper size. The value can be a standard paper size defined by the International Organization for Standardization (ISO), for example, ISO_A4, or a non-standard paper size defined in the system, for example, Custom.178 × 254 mm. |
| defaultOrientation | PrintOrientationMode | No | Yes | Default print orientation. |
| borderless | boolean | No | Yes | Whether to print without margins. The value true means to print without margins, and false means the opposite. The default value is false. |
| defaultColorMode24+ | PrintColorMode | No | Yes | Default color mode. The default value is black and white. Model restriction: This API can be used only in the stage model. |
| defaultCollate24+ | boolean | No | Yes | Default output order. The value true means that pages are printed collated, and false means the opposite. The default value is true. Model restriction: This API can be used only in the stage model. |
| defaultReverse24+ | boolean | No | Yes | Default print order. The value true means that pages are printed in reverse order, and false means that pages are printed in normal order. The default value is false. Model restriction: This API can be used only in the stage model. |
| options | string | No | Yes | Other fields in the printer preferences. The fields are obtained from the printer or the printer driver and stored in the string in JSON format. |
| vendorOptions | string | No | Yes | Vendor-specific printer preferences of the printer driver, in JSON format. Model restriction: This API can be used only in the stage model. Since: 26.0.0 |
Enumerates printer-related events.
System capability: SystemCapability.Print.PrintFramework
| Name | Value | Description |
|---|---|---|
| PRINTER_EVENT_ADDED | 0 | Printer added. |
| PRINTER_EVENT_DELETED | 1 | Printer deleted. |
| PRINTER_EVENT_STATE_CHANGED | 2 | Printer state changed. |
| PRINTER_EVENT_INFO_CHANGED | 3 | Printer information changed. |
| PRINTER_EVENT_PREFERENCE_CHANGED | 4 | Printer preferences changed. |
| PRINTER_EVENT_LAST_USED_PRINTER_CHANGED | 5 | The last used printer changed. |
Enumerates the methods for determining the default printer.
System capability: SystemCapability.Print.PrintFramework
| Name | Value | Description |
|---|---|---|
| DEFAULT_PRINTER_TYPE_SET_BY_USER | 0 | The printer set by the user serves as the default printer. |
| DEFAULT_PRINTER_TYPE_LAST_USED_PRINTER | 1 | The printer used last time serves as the default printer. |
getAddedPrinters(): Promise<Array<string>>
Obtains the list of printers added to the system. This API uses a promise to return the result.
Required permissions: ohos.permission.MANAGE_PRINT_JOB or ohos.permission.PRINT
System capability: SystemCapability.Print.PrintFramework
Return value
| Type | Description |
|---|---|
| Promise<Array<string>> | Promise used to return a list of all added printers. |
Error codes
For details about the error codes, see Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | the application does not have permission to call this function. |
Example
import { print } from '@kit.BasicServicesKit';
import { BusinessError } from '@kit.BasicServicesKit';
print.getAddedPrinters().then((printers: string[]) => {
console.info('getAddedPrinters success ' + JSON.stringify(printers));
// ...
}).catch((error: BusinessError) => {
console.error(`Failed to getAddedPrinters. Code: ${error.code}, message: ${error.message}`);
}) type PrinterChangeCallback = (event: PrinterEvent, printerInformation: PrinterInformation) => void
Defines a callback that takes the printer event and printer information as parameters.
System capability: SystemCapability.Print.PrintFramework
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| event | PrinterEvent | Yes | Printer event. |
| printerInformation | PrinterInformation | Yes | Printer information. |
on(type: 'printerChange', callback: PrinterChangeCallback): void
Registers a listener for the printer change events. This API uses an asynchronous callback to return the result.
Required permissions: ohos.permission.PRINT
System capability: SystemCapability.Print.PrintFramework
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| type | 'printerChange' | Yes | Printer change event. |
| callback | PrinterChangeCallback | Yes | Callback to be invoked when the printer changes. |
Error codes
For details about the error codes, see Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | the application does not have permission to call this function. |
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. |
Example
import { print } from '@kit.BasicServicesKit';
// Trigger this callback when an added printer is changed.
let onPrinterChange =
(event: print.PrinterEvent, printerInformation: print.PrinterInformation) => {
console.info('printerChange, event: ' + event + ', printerInformation: ' + JSON.stringify(printerInformation));
};
print.on('printerChange', onPrinterChange); off(type: 'printerChange', callback?: PrinterChangeCallback): void
Unregisters the callback for printer change events.
Required permissions: ohos.permission.PRINT
System capability: SystemCapability.Print.PrintFramework
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| type | 'printerChange' | Yes | Printer change event. |
| callback | PrinterChangeCallback | No | Callback for printer change events to be unregistered. If this parameter is not passed, all registered callbacks of the caller will be unregistered. |
Error codes
For details about the error codes, see Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | the application does not have permission to call this function. |
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. |
Example
import { print } from '@kit.BasicServicesKit';
// Trigger this callback when an added printer is changed.
let onPrinterChange =
(event: print.PrinterEvent, printerInformation: print.PrinterInformation) => {
console.info('printerChange, event: ' + event + ', printerInformation: ' + JSON.stringify(printerInformation));
};
print.on('printerChange', onPrinterChange);
print.off('printerChange'); startDiscoverPrinter(extensionList: Array<string>, callback: AsyncCallback<void>): void
Discovers printers by specifying the extension list. The discovered printers have the specified print extension abilities. If an empty extension list is specified, all extension abilities are loaded. This API uses an asynchronous callback to return the result. When printer discovery is no longer needed, call stopDiscoverPrinter to stop the discovery and release system resources. Otherwise, the system will continuously discover printers, consuming system resources.
Required permissions: ohos.permission.MANAGE_PRINT_JOB or ohos.permission.PRINT
System capability: SystemCapability.Print.PrintFramework
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| extensionList | Array<string> | Yes | List of PrintExtensionAbilities to be loaded. The list members are the bundle names of the applications with print extension abilities. An empty list indicates that all extension abilities are loaded. |
| callback | AsyncCallback<void> | Yes | Callback to be invoked when a printer is discovered. |
Error codes
For details about the error codes, see Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | the application does not have permission to call this function. |
Example
import { print } from '@kit.BasicServicesKit';
import { BusinessError } from '@kit.BasicServicesKit';
// Load all print extension abilities.
let extensionList: string[] = [];
// Specify the bundle name of your applications to load required print extension abilities during printer discovery.
// let extensionList: string[] = ['com.myapplication.test'];
print.startDiscoverPrinter(extensionList, (error: BusinessError) => {
if (error) {
console.error(`Failed to startDiscoverPrinter. Code: ${error.code}, message: ${error.message}`);
} else {
console.info('start Discover Printer success');
}
}) startDiscoverPrinter(extensionList: Array<string>): Promise<void>
Discovers printers by specifying the extension list. The discovered printers have the specified print extension abilities. If an empty extension list is specified, all extension abilities are loaded. This API uses a promise to return the result. When printer discovery is no longer needed, call stopDiscoverPrinter to stop the discovery and release system resources. Otherwise, the system will continuously discover printers, consuming system resources.
Required permissions: ohos.permission.MANAGE_PRINT_JOB or ohos.permission.PRINT
System capability: SystemCapability.Print.PrintFramework
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| extensionList | Array<string> | Yes | List of PrintExtensionAbilities to be loaded. The list members are the bundle names of the applications with print extension abilities. An empty list indicates that all extension abilities are loaded. |
Return value
| Type | Description |
|---|---|
| Promise<void> | Promise that returns no value. resolve indicates that the operation is successful, and reject indicates that the operation fails. |
Error codes
For details about the error codes, see Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | the application does not have permission to call this function. |
Example
import { print } from '@kit.BasicServicesKit';
import { BusinessError } from '@kit.BasicServicesKit';
// Load all print extension abilities.
let extensionList: string[] = [];
// Specify the bundle name of your applications to load required print extension abilities during printer discovery.
// let extensionList: string[] = ['com.myapplication.test'];
print.startDiscoverPrinter(extensionList).then(() => {
console.info('start Discovery success');
}).catch((error: BusinessError) => {
console.error(`Failed to startDiscoverPrinter. Code: ${error.code}, message: ${error.message}`);
}) stopDiscoverPrinter(callback: AsyncCallback<void>): void
Stops discovering printers. This API uses an asynchronous callback to return the result.
Required permissions: ohos.permission.MANAGE_PRINT_JOB or ohos.permission.PRINT
System capability: SystemCapability.Print.PrintFramework
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| callback | AsyncCallback<void> | Yes | Callback to be invoked when printer discovery is stopped. |
Error codes
For details about the error codes, see Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | the application does not have permission to call this function. |
Example
import { print } from '@kit.BasicServicesKit';
import { BusinessError } from '@kit.BasicServicesKit';
print.stopDiscoverPrinter((error: BusinessError) => {
if (error) {
console.error(`Failed to stopDiscoverPrinter. Code: ${error.code}, message: ${error.message}`);
} else {
console.info('stop Discover Printer success');
}
}) stopDiscoverPrinter(): Promise<void>
Stops discovering printers. This API uses a promise to return the result.
Required permissions: ohos.permission.MANAGE_PRINT_JOB or ohos.permission.PRINT
System capability: SystemCapability.Print.PrintFramework
Return value
| Type | Description |
|---|---|
| Promise<void> | Promise that returns no value. resolve indicates that the operation is successful, and reject indicates that the operation fails. |
Error codes
For details about the error codes, see Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | the application does not have permission to call this function. |
Example
import { print } from '@kit.BasicServicesKit';
import { BusinessError } from '@kit.BasicServicesKit';
print.stopDiscoverPrinter().then(() => {
console.info('stop Discovery success');
}).catch((error: BusinessError) => {
console.error(`Failed to stopDiscoverPrinter. Code: ${error.code}, message: ${error.message}`);
}) connectPrinter(printerId: string, callback: AsyncCallback<void>): void
Connects to a printer by printer ID. This API uses an asynchronous callback to return the result.
Required permissions: ohos.permission.MANAGE_PRINT_JOB or ohos.permission.PRINT
System capability: SystemCapability.Print.PrintFramework
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| printerId | string | Yes | Printer ID. |
| callback | AsyncCallback<void> | Yes | Callback to be invoked when a printer is connected. |
Error codes
For details about the error codes, see Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | the application does not have permission to call this function. |
Example
import { print } from '@kit.BasicServicesKit';
import { BusinessError } from '@kit.BasicServicesKit';
// printer ID can be obtained from the on('printerChange') callback.
let printerId: string = 'printerId_32';
print.connectPrinter(printerId, (error: BusinessError) => {
if (error) {
console.error(`Failed to connectPrinter. Code: ${error.code}, message: ${error.message}`);
} else {
console.info('start connect Printer success');
}
}) connectPrinter(printerId: string): Promise<void>
Connects to a printer by printer ID. This API uses a promise to return the result.
Required permissions: ohos.permission.MANAGE_PRINT_JOB or ohos.permission.PRINT
System capability: SystemCapability.Print.PrintFramework
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| printerId | string | Yes | Printer ID. |
Return value
| Type | Description |
|---|---|
| Promise<void> | Promise that returns no value. resolve indicates that the operation is successful, and reject indicates that the operation fails. |
Error codes
For details about the error codes, see Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | the application does not have permission to call this function. |
Example
import { print } from '@kit.BasicServicesKit';
import { BusinessError } from '@kit.BasicServicesKit';
// printer ID can be obtained from the on('printerChange') callback.
let printerId: string = 'printerId_32';
print.connectPrinter(printerId).then(() => {
console.info('start connect Printer success');
}).catch((error: BusinessError) => {
console.error(`Failed to connectPrinter. Code: ${error.code}, message: ${error.message}`);
}) startPrint(job: PrintJobData): Promise<void>
Prints a file or binary data. This API uses a promise to return the result. This API directly creates a print job by specifying the target printer ID and print parameters in PrintJobData. Call print.print to display the system print preview page.
Required permissions: ohos.permission.PRINT
System capability: SystemCapability.Print.PrintFramework
Model restriction: This API can be used only in the stage model.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| job | PrintJobData | Yes | Print job data. |
Return value
| Type | Description |
|---|---|
| Promise<void> | Promise that returns no value. resolve indicates that the operation is successful, and reject indicates that the operation fails. |
Error codes
For details about the error codes, see Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | the application does not have permission to call this function. |
Example
import { print } from '@kit.BasicServicesKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { fileIo } from '@kit.CoreFileKit';
let tempPath = '/data/storage/el2/base/haps/entry/files/note.jpg';
let file: fileIo.File;
file = fileIo.openSync(tempPath, 4);
let printJobData: print.PrintJobData = {
printerId: 'printerId', // printer ID can be obtained from the on('printerChange') callback.
jobName: 'jobName',
documentFormat: print.PrintDocumentFormat.DOCUMENT_FORMAT_AUTO,
docFlavor: print.DocFlavor.FILE_DESCRIPTOR,
copyNumber: 1,
isLandscape: false,
colorMode: print.PrintColorMode.COLOR_MODE_MONOCHROME,
duplexMode: print.PrintDuplexMode.DUPLEX_MODE_NONE,
pageSize: {id: 'ISO_A4', name: 'ISO_A4', width: 8268, height: 11692},
fdList: [file.fd],
};
print.startPrint(printJobData).then(() => {
console.info('start print success');
}).catch((error: BusinessError) => {
console.error(`Failed to startPrint. Code: ${error.code}, message: ${error.message}`);
}) Enumerates the data formats.
System capability: SystemCapability.Print.PrintFramework
Model restriction: This API can be used only in the stage model.
| Name | Value | Description |
|---|---|---|
| DOCUMENT_FORMAT_AUTO | 0 | Auto-detected format. |
| DOCUMENT_FORMAT_JPEG | 1 | JPEG. |
| DOCUMENT_FORMAT_PDF | 2 | PDF. |
| DOCUMENT_FORMAT_POSTSCRIPT | 3 | PostScript. |
| DOCUMENT_FORMAT_TEXT | 4 | Text. |
| DOCUMENT_FORMAT_RAW | 5 | RAW. |
Enumerates the data source types for printing.
System capability: SystemCapability.Print.PrintFramework
Model restriction: This API can be used only in the stage model.
| Name | Value | Description |
|---|---|---|
| FILE_DESCRIPTOR | 0 | File descriptor. |
| BYTES | 1 | Binary data. |
Defines a print job.
System capability: SystemCapability.Print.PrintFramework
Model restriction: This API can be used only in the stage model.
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| printerId | string | No | No | Printer ID. |
| jobName | string | No | No | Name of the print job. |
| documentFormat | PrintDocumentFormat | No | No | Format of the print data. |
| docFlavor | DocFlavor | No | No | Data source type. If this parameter is set to FILE_DESCRIPTOR, the fdList parameter must be provided. If this parameter is set to BYTES, the binaryData parameter must be provided. |
| copyNumber | number | No | No | Number of printed file copies. The value is a positive integer. The default value is 1. |
| isLandscape | boolean | No | No | Whether pages are printed in landscape mode. The value true indicates that pages are printed in landscape mode, and false indicates that pages are printed in portrait mode. The default value is false. |
| colorMode | PrintColorMode | No | No | Color mode. |
| duplexMode | PrintDuplexMode | No | No | Simplex or duplex mode. |
| pageSize | PrintPageSize | No | No | Selected page size. |
| jobId | string | No | Yes | Unique identifier of the print job. |
| fdList | number[] | No | Yes | FD list of files to print. This parameter is required when docFlavor is set to FILE_DESCRIPTOR. |
| binaryData | Uint8Array | No | Yes | Binary data to print. This parameter is required when docFlavor is set to BYTES. |
| printQuality | PrintQuality | No | Yes | Print quality. |
| mediaType | string | No | Yes | Type of the paper to print. |
| isBorderless | boolean | No | Yes | Whether to print without margins. The value true means to print without margins, and false means the opposite. Default value: true. |
| isAutoRotate | boolean | No | Yes | Whether to automatically rotate the page. The value true means to automatically rotate the page, and false means the opposite. Default value: true. |
| isReverse | boolean | No | Yes | Whether pages are printed in reverse order. The value true means that pages are printed in reverse order, and false means that pages are printed in normal order. The default value is false. |
| isCollate | boolean | No | Yes | Whether pages are printed uncollated. The value true means that pages are printed collated, and false means the opposite. Default value: true. |
| isSequential | boolean | No | Yes | Whether the printing is sequential. The value true means that the printing is sequential, and false means the opposite. The default value is false. |
| options | string | No | Yes | Additional information about the print job, in JSON format. The parameter must contain the printerUri, printerName, and documentFormat fields. If the value is not passed or the format is invalid, the CUPS task will fail to be created. |
| vendorOptions | string | No | Yes | Vendor-specific print job attributes of the printer driver, in JSON format. Since: 26.0.0 |
Defines the page margins for printing.
System capability: SystemCapability.Print.PrintFramework
Attributes
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| top | number | No | Yes | Top margin of the page, in millimeters. The default value is 0. |
| bottom | number | No | Yes | Bottom margin of the page, in millimeters. The default value is 0. |
| left | number | No | Yes | Left margin of the page, in millimeters. The default value is 0. |
| right | number | No | Yes | Right margin of the page, in millimeters. The default value is 0. |
Defines the print range.
System capability: SystemCapability.Print.PrintFramework
Attributes
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| startPage | number | No | Yes | Start page. The value is a positive integer. The default value is 1. |
| endPage | number | No | Yes | End page. The value must be a positive integer. The default value is the maximum number of pages in the file to be printed. |
| pages | Array<number> | No | Yes | Page range set of the file to print. The default value is empty. |
Defines the print preview attributes.
System capability: SystemCapability.Print.PrintFramework
Attributes
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| previewRange | PrinterRange | No | No | Preview page range. |
| result | number | No | Yes | Preview file generation result. The value is defined by the developer. |
Defines the resolution for printing.
System capability: SystemCapability.Print.PrintFramework
Attributes
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| id | string | No | No | Resolution ID. |
| horizontalDpi | number | No | No | Horizontal DPI. |
| verticalDpi | number | No | No | Vertical DPI. |
Defines the printer capabilities.
System capability: SystemCapability.Print.PrintFramework
Attributes
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| colorMode | number | No | No | Color mode. For details, see PrintColorMode. |
| duplexMode | number | No | No | Simplex or duplex mode. For details about the value, see PrintDuplexMode. |
| pageSize | Array<PrintPageSize> | No | No | List of page sizes supported by the printer. |
| resolution | Array<PrintResolution> | No | Yes | List of resolutions supported by the printer. |
| minMargin | PrintMargin | No | Yes | Minimum margin of the printer. |
| options | Object | No | Yes | Printer capability information, in JSON format. |
Defines the printer information.
System capability: SystemCapability.Print.PrintFramework
Attributes
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| printerId | string | No | No | Printer ID. |
| printerName | string | No | No | Printer name. |
| printerState | PrinterState | No | No | Printer state. |
| printerIcon | number | No | Yes | Resource ID of the printer icon. The default value is -1. |
| description | string | No | Yes | Printer description. |
| capability | PrinterCapability | No | Yes | Printer capabilities. |
| options | Object | No | Yes | Printer information, in JSON format. |
Defines a print job.
System capability: SystemCapability.Print.PrintFramework
Attributes
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| fdList | Array<number> | No | No | FD list of files to print. |
| jobId | string | No | No | ID of the print job. |
| printerId | string | No | No | ID of the printer used for printing. |
| jobState | PrintJobState | No | No | State of the print job. |
| jobSubstate | PrintJobSubState | No | No | Substate of the print job. |
| copyNumber | number | No | No | Number of printed file copies. The value is a positive integer. The default value is 1. |
| pageRange | PrinterRange | No | No | Print page range. |
| isSequential | boolean | No | No | Whether the printing is sequential. The value true means that the printing is sequential, and false means the opposite. The default value is false. |
| pageSize | PrintPageSize | No | No | Selected page size. |
| isLandscape | boolean | No | No | Whether pages are printed in landscape mode. The value true indicates that pages are printed in landscape mode, and false indicates that pages are printed in portrait mode. The default value is false. |
| colorMode | number | No | No | Color mode. For details, see PrintColorMode. |
| duplexMode | number | No | No | Simplex or duplex mode. For details about the value, see PrintDuplexMode. |
| margin | PrintMargin | No | Yes | Current page margin. |
| preview | PreviewAttribute | No | Yes | Preview settings. |
| options | Object | No | Yes | Detailed information about a print job, in JSON format. |
| vendorOptions | string | No | Yes | Vendor-specific print job attributes of the printer driver, in JSON format. Model restriction: This API can be used only in the stage model. Since: 26.0.0 |
updatePrintJobState(jobId: string, state: PrintJobState, subState: PrintJobSubState, callback: AsyncCallback<void>): void
Updates the print job state. This API uses an asynchronous callback to return the result.
Required permissions: ohos.permission.MANAGE_PRINT_JOB or ohos.permission.ENTERPRISE_MANAGE_PRINT
System capability: SystemCapability.Print.PrintFramework
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| jobId | string | Yes | ID of the print job. |
| state | PrintJobState | Yes | Print job state. |
| subState | PrintJobSubState | Yes | Substate of the print job. |
| callback | AsyncCallback<void> | Yes | Callback to be invoked when the print job state is updated. |
Error codes
For details about the error codes, see Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | The application does not have permission to call this function. |
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. |
Example
import { print } from '@kit.BasicServicesKit';
import { BusinessError } from '@kit.BasicServicesKit';
// Obtain the job ID from the onStartPrintJob callback of the PrintExtensionAbility.
let jobId : string = 'jobId';
let state : print.PrintJobState = print.PrintJobState.PRINT_JOB_PREPARE;
let subState : print.PrintJobSubState = print.PrintJobSubState.PRINT_JOB_COMPLETED_SUCCESS;
print.updatePrintJobState(jobId, state, subState, (error: BusinessError) => {
if (error) {
console.error(`Failed to updatePrintJobState. Code: ${error.code}, message: ${error.message}`);
} else {
console.info('updatePrintJobState success');
}
}) updatePrintJobState(jobId: string, state: PrintJobState, subState: PrintJobSubState): Promise<void>
Updates the print job state. This API uses a promise to return the result.
Required permissions: ohos.permission.MANAGE_PRINT_JOB or ohos.permission.ENTERPRISE_MANAGE_PRINT
System capability: SystemCapability.Print.PrintFramework
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| jobId | string | Yes | ID of the print job. |
| state | PrintJobState | Yes | Print job state. |
| subState | PrintJobSubState | Yes | Substate of the print job. |
Return value
| Type | Description |
|---|---|
| Promise<void> | Promise that returns no value. resolve indicates that the operation is successful, and reject indicates that the operation fails. |
Error codes
For details about the error codes, see Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | the application does not have permission to call this function. |
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. |
Example
import { print } from '@kit.BasicServicesKit';
import { BusinessError } from '@kit.BasicServicesKit';
// Obtain the job ID from the onStartPrintJob callback of the PrintExtensionAbility.
let jobId : string = 'jobId';
let state : print.PrintJobState = print.PrintJobState.PRINT_JOB_PREPARE;
let subState : print.PrintJobSubState = print.PrintJobSubState.PRINT_JOB_COMPLETED_SUCCESS;
print.updatePrintJobState(jobId, state, subState).then(() => {
console.info('update print job state success');
}).catch((error: BusinessError) => {
console.error(`Failed to updatePrintJobState. Code: ${error.code}, message: ${error.message}`);
}) updatePrinterInformation(printerInformation: PrinterInformation): Promise<void>
Updates the information of a printer in the system. This API uses a promise to return the result. Currently, only the alias and options fields of PrinterInformation can be updated.
Required permissions: ohos.permission.MANAGE_PRINT_JOB or ohos.permission.ENTERPRISE_MANAGE_PRINT
System capability: SystemCapability.Print.PrintFramework
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| printerInformation | PrinterInformation | Yes | Printer information to be updated. Currently, only the alias and options fields can be updated. |
Return value
| Type | Description |
|---|---|
| Promise<void> | Promise that returns no value. resolve indicates that the operation is successful, and reject indicates that the operation fails. |
Error codes
For details about the error codes, see Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | the application does not have permission to call this function. |
| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. |
Example
import { print } from '@kit.BasicServicesKit';
import { BusinessError } from '@kit.BasicServicesKit';
let testPageSize : print.PrintPageSize = {
id : 'ISO_A4',
name : 'iso_a4_210x297mm',
width : 8268,
height : 11692
};
let testCapability : print.PrinterCapabilities = {
supportedPageSizes : [testPageSize],
supportedColorModes : [print.PrintColorMode.COLOR_MODE_MONOCHROME],
supportedDuplexModes : [print.PrintDuplexMode.DUPLEX_MODE_NONE],
supportedMediaTypes : ['stationery'],
supportedQualities : [print.PrintQuality.QUALITY_NORMAL],
supportedOrientations : [print.PrintOrientationMode.ORIENTATION_MODE_PORTRAIT],
options : 'testOptions'
};
let printerInformation : print.PrinterInformation = {
printerId : 'testPrinterId', // printer ID can be obtained from the on('printerChange') callback.
printerName : 'testPrinterName',
printerStatus : 0,
description : 'testDesc',
capability : testCapability,
uri : 'testUri',
printerMake : 'testPrinterMake',
options : 'testOptions'
};
print.updatePrinterInformation(printerInformation).then(() => {
console.info('updatePrinterInformation success');
}).catch((error: BusinessError) => {
console.error(`Failed to updatePrinterInformation. Code: ${error.code}, message: ${error.message}`);
}) Defines the PPD file information of the printer driver.
System capability: SystemCapability.Print.PrintFramework
Model restriction: This API can be used only in the stage model.
Attributes
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| manufacturer | string | No | No | Printer vendor name in the current PPD file. |
| nickName | string | No | No | Printer alias in the current PPD file. |
| ppdName | string | No | No | Name of the current PPD file. |
addPrinter(printerName: string, uri: string, ppdName?: string, options?: string): Promise<boolean>
Adds a printer to the system. This API uses a promise to return the result. This API is intended for scenarios where printers or scanners need to be managed, such as the management of the printer drivers, printing management software, third-party printing management software, and cloud printing.
Required permissions: ohos.permission.MANAGE_PRINT_JOB or ohos.permission.PRINTER_DRIVER
System capability: SystemCapability.Print.PrintFramework
Model restriction: This API can be used only in the stage model.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| printerName | string | Yes | Printer name. |
| uri | string | Yes | Printer URI. |
| ppdName | string | No | PPD driver file name of the printer in the file system. The name is generated after the driver is installed on the device, which is in the format of package name_module name_file name. For details about the name, contact the driver vendor. This parameter is passed when a specific PPD driver file needs to be specified. If this parameter is not passed, the system automatically matches a PPD driver file. |
| options | string | No | JSON object string, which indicates the printer option parameter. This is a reserved field, which is not used currently. |
Return value
| Type | Description |
|---|---|
| Promise<boolean> | Promise used to return the result indicating whether the printer is successfully added. true if the operation is successful, and false otherwise. |
Error codes
For details about the error codes, see Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | the application does not have permission to call this function. |
| 13100003 | Add the printer to system failed. |
Example
import { print } from '@kit.BasicServicesKit';
import { BusinessError } from '@kit.BasicServicesKit';
let printerName : string = 'printerName';
let uri : string = 'uri';
let ppdName : string = 'ppdName';
print.addPrinter(printerName, uri, ppdName).then(() => {
console.info('add printer success');
}).catch((error: BusinessError) => {
console.error(`Failed to addPrinter. Code: ${error.code}, message: ${error.message}`);
}) Enumerates the results of forcible watermark processing.
System capability: SystemCapability.Print.PrintFramework
Model restriction: This API can be used only in the stage model.
| Name | Value | Description |
|---|---|---|
| WATERMARK_HANDLE_SUCCESS | 0 | The forcible watermark processing is successful. |
| WATERMARK_HANDLE_FAILURE | 1 | The forcible watermark processing fails. |
type WatermarkCallback = (jobId: string, fd: number) => void
Callback type used to register an event listener for forcible watermark processing.
System capability: SystemCapability.Print.PrintFramework
Model restriction: This API can be used only in the stage model.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| jobId | string | Yes | ID of the print job. |
| fd | number | Yes | File descriptor of the file. |
registerWatermarkCallback(callback: WatermarkCallback): void
Registers an event listener for forcible watermark processing. A forcible watermark is the watermark that must be added to printed files according to enterprise management policies. In enterprise management scenarios, when a watermark (such as a company logo or confidentiality level mark) needs to be forcibly added to printed files, you can use this API to register a watermark processing callback.
Required permissions: ohos.permission.ENTERPRISE_MANAGE_PRINT
System capability: SystemCapability.Print.PrintFramework
Model restriction: This API can be used only in the stage model.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| callback | WatermarkCallback | Yes | Callback type used to register an event listener for forcible watermark processing. |
Error codes
For details about the error codes, see Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | the application does not have permission to call this function. |
Example
import { print } from '@kit.BasicServicesKit';
let watermarkCallback: print.WatermarkCallback = (jobId: string, fd: number) => {
console.info('Watermark callback triggered, jobId: ' + jobId + ', fd: ' + fd);
};
try {
print.registerWatermarkCallback(watermarkCallback);
console.info('registerWatermarkCallback success');
} catch (error) {
console.error(`Failed to registerWatermarkCallback. Code: ${error.code}, message: ${error.message}`);
} unregisterWatermarkCallback(callback?: WatermarkCallback): void
Deregisters an event listener for forcible watermark processing. When an enterprise management app no longer needs to forcibly add watermarks to printed files, you can call this API to unregister the previously registered watermark processing callback.
Required permissions: ohos.permission.ENTERPRISE_MANAGE_PRINT
System capability: SystemCapability.Print.PrintFramework
Model restriction: This API can be used only in the stage model.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| callback | WatermarkCallback | No | Watermark processing callback to be unregistered. If this parameter is not passed, all registered callbacks of the caller will be unregistered. |
Error codes
For details about the error codes, see Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | the application does not have permission to call this function. |
Example
import { print } from '@kit.BasicServicesKit';
let watermarkCallback: print.WatermarkCallback = (jobId: string, fd: number) => {
console.info('Watermark callback triggered, jobId: ' + jobId + ', fd: ' + fd);
};
try {
print.registerWatermarkCallback(watermarkCallback);
console.info('registerWatermarkCallback success');
// Deregister the specified callback for watermark processing.
print.unregisterWatermarkCallback(watermarkCallback);
console.info('unregisterWatermarkCallback success');
} catch (error) {
console.error(`Failed to unregisterWatermarkCallback. Code: ${error.code}, message: ${error.message}`);
} notifyWatermarkComplete(jobId: string, result: WatermarkHandleResult): void
Notifies that watermark processing is complete so that the subsequent printing process can continue.
Required permissions: ohos.permission.ENTERPRISE_MANAGE_PRINT
System capability: SystemCapability.Print.PrintFramework
Model restriction: This API can be used only in the stage model.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| jobId | string | Yes | ID of the print job. |
| result | WatermarkHandleResult | Yes | Watermark processing result. |
Error codes
For details about the error codes, see Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | the application does not have permission to call this function. |
Example
import { print } from '@kit.BasicServicesKit';
let watermarkCallback: print.WatermarkCallback = (jobId: string, fd: number) => {
console.info('Watermark callback triggered, jobId: ' + jobId + ', fd: ' + fd);
try {
// Notify the system that the watermark processing is successful.
print.notifyWatermarkComplete(jobId, print.WatermarkHandleResult.WATERMARK_HANDLE_SUCCESS);
console.info('notifyWatermarkComplete success');
} catch (error) {
console.error(`Failed to notifyWatermarkComplete. Code: ${error.code}, message: ${error.message}`);
}
};
try {
print.registerWatermarkCallback(watermarkCallback);
console.info('registerWatermarkCallback success');
} catch (error) {
console.error(`Failed to registerWatermarkCallback. Code: ${error.code}, message: ${error.message}`);
}