目录

Printing Frontend Pages

The Web component can print HTML pages in two ways: through the W3C standard protocol API and through the app-side API.

Before using the print capability, declare related permissions in the module.json5 file. For details, see Declaring Permissions in the Configuration File.

"requestPermissions":[
    {
      "name" : "ohos.permission.PRINT"
    }
  ]

Initiating a Print Task Through the W3C Standards-compliant API

A print adapter is created to start the print app and render the current web page content. The PDF file information generated after rendering is passed to the print framework through a file descriptor (fd). The W3C standard protocol API window.print() is used to print the current page or pop up a print dialog box. This method takes no parameters and only needs to be called in JavaScript.

You can use frontend CSS styles to control whether to print, for example, @media print. Then load the HTML page in the Web component.

Initiating a Print Task Through the Application API

On the application side, call createWebPrintDocumentAdapter to create a print adapter and pass the adapter to the print API to initiate printing.

import { webview } from '@kit.ArkWeb';
import { BusinessError, print } from '@kit.BasicServicesKit';

@Entry
@Component
struct WebComponent {
  controller: webview.WebviewController = new webview.WebviewController();

  build() {
    Column() {
      Button('createWebPrintDocumentAdapter')
        .onClick(() => {
          try {
            let webPrintDocAdapter = this.controller.createWebPrintDocumentAdapter('example.pdf');
            print.print('example_job_id', webPrintDocAdapter, null, this.getUIContext().getHostContext());
          } catch (error) {
            console.error(`ErrorCode: ${(error as BusinessError).code},  Message: ${(error as BusinessError).message}`);
          }
        })
      Web({ src: 'www.example.com', controller: this.controller });
    }
  }
}