• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Printing Frontend Pages
2
3With the **Web** component, you can print HTML pages through W3C standards-compliant APIs or application APIs.
4
5Before using the print capability, declare related permissions in the **module.json5** file. For details, see [Declaring Permissions](../security/AccessToken/declare-permissions.md).
6
7  ```
8  "requestPermissions":[
9      {
10        "name" : "ohos.permission.PRINT"
11      }
12    ]
13  ```
14
15## Initiating a Print Task Through the W3C Standards-compliant API
16The printing process with W3C is as follows: A print adapter is created, the print application is started, the current web page content is rendered, and the PDF file generated after rendering is transferred to the print framework through the file descriptor (FD). Use the **window.print()** method to print the current document or open the print dialog box. This method does not have any parameter; simply call it in JavaScript.
17
18You can use the frontend CSS styles, for example, **@media print**, to control the printed content. Then load the HTML page in the **Web** component.
19
20- Sample code of the **print.html** page:
21
22  Example 1:
23
24  ```html
25  <!DOCTYPE html>
26  <html>
27
28  <head>
29      <meta charset="utf-8">
30      <title>printTest</title>
31      <style>
32          @media print {
33              h1 {
34                  display: none;
35              }
36          }
37      </style>
38  </head>
39
40  <body>
41      <div>
42          <h1><b>
43                  <center>This is a test page for printing</center>
44              </b>
45              <hr color=#00cc00 width=95%>
46          </h1>
47          <button class="Button Button--outline" onclick="window.print();">Print</button>
48          <p> content content content </p>
49          <div id="printableTable">
50              <table>
51                  <thead>
52                      <tr>
53                          <td>Thing</td>
54                          <td>Chairs</td>
55                      </tr>
56                  </thead>
57                  <tbody>
58                      <tr>
59                          <td>1</td>
60                          <td>blue</td>
61                      </tr>
62                      <tr>
63                          <td>2</td>
64                          <td>green</td>
65                      </tr>
66                  </tbody>
67              </table>
68          </div>
69          <p> content content content </p>
70          <p> content content content </p>
71      </div>
72  </body>
73  ```
74
75  Example 2 (nesting a page in an iframe):
76
77
78  ```html
79  <!DOCTYPE html>
80  <html lang="en">
81  <head>
82      <meta charset="UTF-8">
83      <meta name="viewport" content="width=device-width, initial-scale=1.0">
84      <title>Print Nested Page in an iframe</title>
85  </head>
86  <body>
87      <button id="printIframe">Print nested page in an iframe</button>
88
89      <script>
90          function setPrint() {
91              const closePrint = () => {
92                  document.body.removeChild(this);
93              };
94              this.contentWindow.onbeforeunload = closePrint;
95              this.contentWindow.onafterprint = closePrint;
96              this.contentWindow.print();
97          }
98
99          document.getElementById("printIframe").addEventListener("click", () => {
100              const hideFrame = document.createElement("iframe");
101              hideFrame.onload = setPrint;
102              hideFrame.style.display = "none"; // Hide iframe
103              hideFrame.src = "example.pdf";
104              document.body.appendChild(hideFrame);
105          });
106
107      </script>
108  </body>
109  </html>
110  ```
111
112- Application code:
113
114  ```ts
115  import { webview } from '@kit.ArkWeb';
116
117  @Entry
118  @Component
119  struct Index {
120    controller: webview.WebviewController = new webview.WebviewController();
121
122    build() {
123      Row() {
124        Column() {
125          Web({ src: $rawfile("print.html"), controller: this.controller })
126            .javaScriptAccess(true)
127        }
128        .width('100%')
129      }
130      .height('100%')
131    }
132  }
133  ```
134
135## Initiating a Print Task Through the Application API
136On the application side, call [createWebPrintDocumentAdapter](../reference/apis-arkweb/arkts-apis-webview-WebviewController.md#createwebprintdocumentadapter11) to create a print adapter and pass the adapter to the **print** API to initiate printing.
137
138```ts
139// xxx.ets
140import { webview } from '@kit.ArkWeb';
141import { BusinessError } from '@kit.BasicServicesKit';
142import { print } from '@kit.BasicServicesKit'
143
144@Entry
145@Component
146struct WebComponent {
147  controller: webview.WebviewController = new webview.WebviewController();
148
149  build() {
150    Column() {
151      Button('createWebPrintDocumentAdapter')
152        .onClick(() => {
153          try {
154            let webPrintDocadapter = this.controller.createWebPrintDocumentAdapter('example.pdf');
155            print.print('example_jobid', webPrintDocadapter, null, this.getUIContext().getHostContext());
156          } catch (error) {
157            console.error(`ErrorCode: ${(error as BusinessError).code},  Message: ${(error as BusinessError).message}`);
158          }
159        })
160      Web({ src: 'www.example.com', controller: this.controller })
161    }
162  }
163}
164```
165