@ohos.print (Print)

The print module provides APIs for basic print operations.

NOTE 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.

Modules to Import

import { print } from '@kit.BasicServicesKit';

PrintTask

Implements event listeners for print jobs.

on

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';

let filePath = '/data/storage/el2/base/haps/entry/files/test.pdf';
print.print([fileUri.getUriFromPath(filePath)]).then((printTask: print.PrintTask) => {
    printTask.on('block', () => {
        console.info('print state is block');
    })
    // ...
}).catch((error: BusinessError) => {
    console.error('print err ' + JSON.stringify(error));
})

on

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';

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('print err ' + JSON.stringify(error));
})

on

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';

let filePath = '/data/storage/el2/base/haps/entry/files/test.pdf';
print.print([fileUri.getUriFromPath(filePath)]).then((printTask: print.PrintTask) => {
    printTask.on('fail', () => {
        console.info('print state is fail');
    })
    // ...
}).catch((error: BusinessError) => {
    console.error('print err ' + JSON.stringify(error));
})

on

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';

let filePath = '/data/storage/el2/base/haps/entry/files/test.pdf';
print.print([fileUri.getUriFromPath(filePath)]).then((printTask: print.PrintTask) => {
    printTask.on('cancel', () => {
        console.info('print state is cancel');
    })
    // ...
}).catch((error: BusinessError) => {
    console.error('print err ' + JSON.stringify(error));
})

off

off(type: 'block', callback?: Callback<void>): void

Unsubscribes from 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> No Callback used to unsubscribe from the block events of a specified 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';
import { fileUri } from '@kit.CoreFileKit';

let filePath = '/data/storage/el2/base/haps/entry/files/test.pdf';
print.print([fileUri.getUriFromPath(filePath)]).then((printTask: print.PrintTask) => {
    printTask.off('block', () => {
        console.info('unregister state block');
    })
    // ...
}).catch((error: BusinessError) => {
    console.error('print err ' + JSON.stringify(error));
})

off

off(type: 'succeed', callback?: Callback<void>): void

Unsubscribes from 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> No Callback used to unsubscribe from the success events of a specified 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';
import { fileUri } from '@kit.CoreFileKit';

let filePath = '/data/storage/el2/base/haps/entry/files/test.pdf';
print.print([fileUri.getUriFromPath(filePath)]).then((printTask: print.PrintTask) => {
    printTask.off('succeed', () => {
        console.info('unregister state succeed');
    })
    // ...
}).catch((error: BusinessError) => {
    console.error('print err ' + JSON.stringify(error));
})

off

off(type: 'fail', callback?: Callback<void>): void

Unsubscribes from 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> No Callback used to unsubscribe from the failure events of a specified 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';
import { fileUri } from '@kit.CoreFileKit';

let filePath = '/data/storage/el2/base/haps/entry/files/test.pdf';
print.print([fileUri.getUriFromPath(filePath)]).then((printTask: print.PrintTask) => {
    printTask.off('fail', () => {
        console.info('unregister state fail');
    })
    // ...
}).catch((error: BusinessError) => {
    console.error('print err ' + JSON.stringify(error));
})

off

off(type: 'cancel', callback?: Callback<void>): void

Unsubscribes from 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> No Callback used to unsubscribe from the cancellation events of a specified 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';
import { fileUri } from '@kit.CoreFileKit';

let filePath = '/data/storage/el2/base/haps/entry/files/test.pdf';
print.print([fileUri.getUriFromPath(filePath)]).then((printTask: print.PrintTask) => {
    printTask.off('cancel', () => {
        console.info('unregister state cancel');
    })
    // ...
}).catch((error: BusinessError) => {
    console.error('print err ' + JSON.stringify(error));
})

PrintDocumentAdapter11+

Provides information about the document to print. This API must be implemented by a third-party application.

onStartLayoutWrite11+

onStartLayoutWrite(jobId: string, oldAttrs: PrintAttributes, newAttrs: PrintAttributes, fd: number, writeResultCallback: (jobId: string, writeResult: PrintFileCreationState) => void): void

Sends an empty PDF file descriptor to a third-party application. The third-party application updates the file with the new print attributes and then calls writeResultCallback to print the file.

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.
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');
        }
    }
}

onJobStateChanged11+

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.print

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.

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)], (err: BusinessError, printTask: print.PrintTask) => {
    if (err) {
        console.error('print err ' + JSON.stringify(err));
    } else {
        printTask.on('succeed', () => {
            console.info('print state is succeed');
        })
        // ...
    }
})

print.print

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.

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

Type Description
Promise<PrintTask> Promise used to return a PrintTask object.

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('print err ' + JSON.stringify(error));
})

print.print11+

print(files: Array<string>, context: Context, callback: AsyncCallback<PrintTask>): void

Prints files. 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, (err: BusinessError, printTask: print.PrintTask) => {
                        if (err) {
                            console.error('print err ' + JSON.stringify(err));
                        } else {
                            printTask.on('succeed', () => {
                                console.info('print state is succeed');
                            })
                            // ...
                        }
                    })
                })
            }
            .justifyContent(FlexAlign.Center)
            .constraintSize({ minHeight: '100%' })
            .width('100%')
        }
        .height('100%')
    }
}

print.print11+

print(files: Array<string>, context: Context): Promise<PrintTask>

Prints files. 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

Type Description
Promise<PrintTask> Promise used to return a PrintTask object.

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('print err ' + JSON.stringify(error));
                    })
                })
            }
            .justifyContent(FlexAlign.Center)
            .constraintSize({ minHeight: '100%' })
            .width('100%')
        }
        .height('100%')
    }
}

print.print11+

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.

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

Type Description
Promise<PrintTask> Promise used to return a PrintTask object.

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";
                    let printAdapter : print.PrintDocumentAdapter | null = null;
                    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('print err ' + JSON.stringify(error));
                    })
                })
            }
            .justifyContent(FlexAlign.Center)
            .constraintSize({ minHeight: '100%' })
            .width('100%')
        }
        .height('100%')
    }
}

PrintAttributes11+

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 default value is 1.
pageRange PrintPageRange No Yes Page range of the file to print.
pageSize PrintPageSize | PrintPageType No Yes Page size of the file to print.
directionMode PrintDirectionMode No Yes Print direction mode.
colorMode PrintColorMode No Yes Color mode of the files to print.
duplexMode PrintDuplexMode No Yes Duplex mode of the files to print.

PrintPageRange11+

Defines the print range.

System capability: SystemCapability.Print.PrintFramework

Attributes

Name Type Read-Only Optional Description
startPage number No Yes Start page. The default value is 1.
endPage number No Yes End page. The default value is the maximum number of pages of the file to be printed.
pages Array<number> No Yes Page range set of the file to print. The default value is empty.

PrintPageSize11+

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 millimeters.
height number No No Page height, in millimeters.

PrintDirectionMode11+

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.

PrintColorMode11+

Enumerates the color modes.

System capability: SystemCapability.Print.PrintFramework

Name Value Description
COLOR_MODE_MONOCHROME 0 Black and white.
COLOR_MODE_COLOR 1 Color.

PrintDuplexMode11+

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.

PrintPageType11+

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.

PrintDocumentAdapterState11+

Enumerates the print job states.

System capability: SystemCapability.Print.PrintFramework

Name Value Description
PREVIEW_DESTROY 0 The preview fails.
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.

PrintFileCreationState11+

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.

PrinterState14+

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 is updated.
PRINTER_CONNECTED 3 The printer is connected.
PRINTER_DISCONNECTED 4 The printer is disconnected.
PRINTER_RUNNING 5 The printer is running.

PrintJobState14+

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.

PrintJobSubState14+

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.

PrintErrorCode14+

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.
E_PRINT_INVALID_PARAMETER 401 Invalid parameters.
E_PRINT_GENERIC_FAILURE 13100001 Printing failure.
E_PRINT_RPC_FAILURE 13100002 RPC failure.
E_PRINT_SERVER_FAILURE 13100003 Print service failure.
E_PRINT_INVALID_EXTENSION 13100004 Invalid printer extension.
E_PRINT_INVALID_PRINTER 13100005 Invalid printer.
E_PRINT_INVALID_PRINT_JOB 13100006 Invalid print job.
E_PRINT_FILE_IO 13100007 Incorrect file input/output.
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.
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.

ApplicationEvent14+

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.

print.addPrinterToDiscovery14+

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.

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',
    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('addPrinterToDiscovery error : ' + JSON.stringify(error));
})

print.updatePrinterInDiscovery14+

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.

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',
    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('updatePrinterInDiscovery error : ' + JSON.stringify(error));
})

print.removePrinterFromDiscovery14+

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 Printer to remove.

Return value

Type Description
Promise<void> Promise that returns no 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';

let printerId : string = 'testPrinterId';
print.removePrinterFromDiscovery(printerId).then(() => {
    console.info('removePrinterFromDiscovery success');
}).catch((error: BusinessError) => {
    console.error('removePrinterFromDiscovery error : ' + JSON.stringify(error));
})

print.getPrinterInformationById14+

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';

let printerId : string = 'testPrinterId';
print.getPrinterInformationById(printerId).then((printerInformation : print.PrinterInformation) => {
    console.info('getPrinterInformationById data : ' + JSON.stringify(printerInformation));
}).catch((error: BusinessError) => {
    console.error('getPrinterInformationById error : ' + JSON.stringify(error));
})

PrinterInformation14+

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.
capability PrinterCapabilities No Yes Printer capabilities.
uri string No Yes Printer URI.
printerMake string No Yes Printer model.
preferences18+ PrinterPreferences No Yes Printer preferences.
alias18+ string No Yes Printer alias.
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.
Model restriction: This API can be used only in the stage model.
options string No Yes Printer details.

PrinterCapabilities14+

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.
supportedQualities Array<PrintQuality> No Yes List of print quality supported by the printer.
supportedOrientations Array<PrintOrientationMode> No Yes List of print directions supported by the printer.
options string No Yes Printer capability details.

PrintQuality14+

Enumerates the print qualities.

System capability: SystemCapability.Print.PrintFramework

Name Value Description
QUALITY_DRAFT 3 Draft
QUALITY_NORMAL 4 Standard
QUALITY_HIGH 5 High

PrintOrientationMode14+

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.

PrinterStatus14+

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.

PrinterPreferences18+

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 queried from the printer or obtained from the printer driver and stored in the string in JSON format.

PrinterEvent18+

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.

DefaultPrinterType18+

Enumerates default printer types.

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.

print.getAddedPrinters18+

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 because ' + JSON.stringify(error));
})

PrinterChangeCallback18+

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.

print.on18+

on(type: 'printerChange', callback: PrinterChangeCallback): void

Registers a listener for the printer change events. This API uses a 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);

print.off18+

off(type: 'printerChange', callback?: PrinterChangeCallback): void

Unregisters the listener for printer state change events. This API uses a 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 No Callback to unregister.

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');

print.startDiscoverPrinter20+

startDiscoverPrinter(extensionList: Array<string>, callback: AsyncCallback<void>): void

Discovers printers by specifying the extension list. The discovered printers contain 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.

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, (err: BusinessError) => {
    if (err) {
        console.error('failed to start Discover Printer because : ' + JSON.stringify(err));
    } else {
        console.info('start Discover Printer success');
    }
})

print.startDiscoverPrinter20+

startDiscoverPrinter(extensionList: Array<string>): Promise<void>

Discovers printers by specifying the extension list. The discovered printers contain 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.

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.

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 start Discovery because : ' + JSON.stringify(error));
})

print.stopDiscoverPrinter20+

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((err: BusinessError) => {
    if (err) {
        console.error('failed to stop Discover Printer because : ' + JSON.stringify(err));
    } else {
        console.info('stop Discover Printer success');
    }
})

print.stopDiscoverPrinter20+

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.

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 stop Discovery because : ' + JSON.stringify(error));
})

print.connectPrinter20+

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';

let printerId: string = 'printerId_32';
print.connectPrinter(printerId, (err: BusinessError) => {
    if (err) {
        console.error('failed to connect Printer because : ' + JSON.stringify(err));
    } else {
        console.info('start connect Printer success');
    }
})

print.connectPrinter20+

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.

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';

let printerId: string = 'printerId_32';
print.connectPrinter(printerId).then(() => {
    console.info('start connect Printer success');
}).catch((error: BusinessError) => {
    console.error('failed to connect Printer because : ' + JSON.stringify(error));
})

print.startPrint23+

startPrint(job: PrintJobData): Promise<void>

Prints a file or binary data. This API uses a promise to return the result.

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.

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/stroage/el2/base/haps/entry/files/note.jpg';
let file: fileIo.File;
file = fileIo.openSync(tempPath, 4);

let printJobData: print.PrintJobData = {
    printerId: "printerId",
    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 print because : ' + JSON.stringify(error));
})

PrintDocumentFormat23+

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.

DocFlavor23+

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 data.
BYTES 1 Binary data.

PrintJobData23+

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.
copyNumber number No No Number of file list copies.
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.
binaryData Uint8Array No Yes Binary data to print.
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 uncollated, 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 Object stringified in JSON format.

PrintMargin24+

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.

PrinterRange24+

Defines the print range.

System capability: SystemCapability.Print.PrintFramework

Attributes

Name Type Read-Only Optional Description
startPage number No Yes Start page. The default value is 1.
endPage number No Yes End page. The default value is the maximum number of pages of the file to be printed.
pages Array<number> No Yes Page range set of the file to print. The default value is empty.

PreviewAttribute24+

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 Print preview result. The default value is -1.

PrintResolution24+

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.

PrinterCapability24+

Defines the printer capabilities.

System capability: SystemCapability.Print.PrintFramework

Attributes

Name Type Read-Only Optional Description
colorMode number No No Color mode.
duplexMode number No No Simplex or duplex mode.
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 options. The value is a JSON object string.

PrinterInfo24+

Provides 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 capability.
options Object No Yes Printer options. The value is a JSON object string.

PrintJob24+

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 Copy of the file list.
pageRange PrinterRange No No Print 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.
duplexMode number No No Simplex or duplex mode.
margin PrintMargin No Yes Current page margin.
preview PreviewAttribute No Yes Preview settings.
options Object No Yes Printer options. The value is a JSON object string.

print.updatePrintJobState24+

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';

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, (err: BusinessError) => {
    if (err) {
        console.error('updataPrintJobState failed, because : ' + JSON.stringify(err));
    } else {
        console.info('updatePrintJobState success');
    }
})

print.updatePrintJobState24+

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.

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 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('update print job state error : ' + JSON.stringify(error));
})

print.updatePrinterInformation24+

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.

Return value

Type Description
Promise<void> Promise that returns no 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';

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',
    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('updatePrinterInformation error : ' + JSON.stringify(error));
})

PpdInfo24+

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.

SharedHost24+

Defines the shared device information.

System capability: SystemCapability.Print.PrintFramework

Model restriction: This API can be used only in the stage model.

Attributes

Name Type Read-Only Optional Description
ip string No No IP address of the shared device.
shareName string No No Host name of the shared device.
workgroupName string No No Workgroup name of the shared device.

print.addPrinter24+

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.

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 file name of the printer.
options string No JSON object string, which indicates the printer option parameter.

Return value

Type Description
Promise<boolean> Promise used to return the result indicating whether the printer is successfully added.

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('add printer error : ' + JSON.stringify(error));
})

WatermarkHandleResult24+

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.

print.WatermarkCallback24+

type WatermarkCallback = (jobId: string, fd: number) => void

Defines the 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.

print.registerWatermarkCallback24+

registerWatermarkCallback(callback: WatermarkCallback): void

Registers an event listener for forcible watermark processing.

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';
import { BusinessError } 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('registerWatermarkCallback error: ' + JSON.stringify(error));
}

print.unregisterWatermarkCallback24+

unregisterWatermarkCallback(callback?: WatermarkCallback): void

Deregisters an event listener for forcible watermark processing.

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 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';
import { BusinessError } 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('unregisterWatermarkCallback error: ' + JSON.stringify(error));
}

print.notifyWatermarkComplete24+

notifyWatermarkComplete(jobId: string, result: WatermarkHandleResult): void

Notifies that watermark processing is complete.

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';
import { BusinessError } 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('notifyWatermarkComplete error: ' + JSON.stringify(error));
    }
}

try {
    print.registerWatermarkCallback(watermarkCallback);
    console.info('registerWatermarkCallback success');
} catch (error) {
    console.error('registerWatermarkCallback error: ' + JSON.stringify(error));
}