Web组件打印html页面时可通过W3C标准协议接口和应用接口两种方式实现。开发者在使用该能力时,需配置ohos.permission.PRINT打印权限。
使用W3C标准协议接口拉起打印
通过创建打印适配器,拉起打印应用,并对当前Web页面内容进行渲染,渲染后生成的PDF文件信息通过fd传递给打印框架。W3C标准协议接口window.print()方法用于打印当前页面或弹出打印对话框。该方法没有任何参数,只需要在JavaScript中调用即可。
可通过前端css样式控制是否打印,例如@media print。再通过web加载该html页面的方式运行。
- print.html页面代码。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>printTest</title>
<style>
@media print {
h1 {
display: none;
}
}
</style>
</head>
<body>
<div>
<h1><b>
<center>This is a test page for printing</center>
</b>
<hr color=#00cc00 width=95%>
</h1>
<button class="Button Button--outline" onclick="window.print();">Print</button>
<p> content content content </p>
<div id="printableTable">
<table>
<thead>
<tr>
<td>Thing</td>
<td>Chairs</td>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>blue</td>
</tr>
<tr>
<td>2</td>
<td>green</td>
</tr>
</tbody>
</table>
</div>
<p> content content content </p>
<p> content content content </p>
</div>
</body>
- 应用侧代码。
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct Index {
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Row() {
Column() {
Web({ src: $rawfile("print.html"), controller: this.controller })
.javaScriptAccess(true)
}
.width('100%')
}
.height('100%')
}
}
通过调用应用侧接口拉起打印。
应用侧通过调用createWebPrintDocumentAdapter创建打印适配器,通过将适配器传入打印的print接口调起打印。
// xxx.ets
import web_webview from '@ohos.web.webview'
import business_error from '@ohos.base'
import print from '@ohos.print'
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Button('createWebPrintDocumentAdapter')
.onClick(() => {
try {
let webPrintDocadapter = this.controller.createWebPrintDocumentAdapter('example.pdf');
print.print('example_jobid', webPrintDocadapter, null, getContext());
} catch (error) {
let e: business_error.BusinessError = error as business_error.BusinessError;
console.error(`ErrorCode: ${e.code}, Message: ${e.message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
如果大家还没有掌握鸿蒙,现在想要在最短的时间里吃透它,我这边特意整理了《鸿蒙语法ArkTS、TypeScript、ArkUI等…视频教程》以及《鸿蒙开发学习手册》(共计890页),希望对大家有所帮助:https://docs.qq.com/doc/DZVVBYlhuRkZQZlB3
鸿蒙语法ArkTS、TypeScript、ArkUI等…视频教程:https://docs.qq.com/doc/DZVVBYlhuRkZQZlB3
OpenHarmony APP开发教程步骤:https://docs.qq.com/doc/DZVVBYlhuRkZQZlB3
《鸿蒙开发学习手册》:
如何快速入门:https://docs.qq.com/doc/DZVVBYlhuRkZQZlB3
1.基本概念
2.构建第一个ArkTS应用
3.……
开发基础知识:https://docs.qq.com/doc/DZVVBYlhuRkZQZlB3
1.应用基础知识
2.配置文件
3.应用数据管理
4.应用安全管理
5.应用隐私保护
6.三方应用调用管控机制
7.资源分类与访问
8.学习ArkTS语言
9.……
基于ArkTS 开发:https://docs.qq.com/doc/DZVVBYlhuRkZQZlB3
1.Ability开发
2.UI开发
3.公共事件与通知
4.窗口管理
5.媒体
6.安全
7.网络与链接
8.电话服务
9.数据管理
10.后台任务(Background Task)管理
11.设备管理
12.设备使用信息统计
13.DFX
14.国际化开发
15.折叠屏系列
16.……