1. web 组件打印简介
web 组件在加载了网页以后,有两种方式可以实现打印,第一种是在网页中调用 W3C 标准协议接口 window.print()进行打印,这种方式比较简单方便,只要网页中触发了该方法即可打印,缺点是如果网页没有地方触发则不能打印;另外一种是在应用侧实现的,通过 web 控制器的 createWebPrintDocumentAdapter 方法创建打印适配器,然后将适配器传入打印的 print 接口即可调起打印,虽然有点复杂,但是可以打印任何网页;本文将分别演示这两种打印方式的实现。
2. web 组件打印演示
本示例运行后的界面如图所示,这里的网页使用的是应用内置的 html 资源文件:
单击网页中的“打印”按钮,即可弹出打印页面如图所示:
页面的上部为打印预览,下部为打印配置。
如果不使用页面内的打印按钮,而是单击应用侧的“打印”按钮(确保不选中“打印背景”选项),则会弹出如下的打印页面:
这里的预览页面没有显示背景色,如果要打印背景色,可以选中“打印背景”选项。
3. web 组件打印示例编写
下面详细介绍创建该示例的步骤。
步骤 1:创建 Empty Ability 项目。
步骤 2:在 module.json5 配置文件加上对权限的声明:
"requestPermissions": [ { "name": "ohos.permission.INTERNET" } ]
复制代码
这里添加了访问互联网的权限。
步骤 3:添加 print.html 资源文件,该文件即为 web 组件加载的 html 文件,内容如下:
<!DOCTYPE html><html>
<body style="background-color: lightblue;"><div style="text-align: center;"> <h1> 打印测试页 </h1> <button onclick="window.print();">打印</button> <p> 网页内容 </p> <p style="color: blue;"> 打印Web组件中的网页内容示例 </p></div></body>
复制代码
步骤 4:在 Index.ets 文件里添加如下的代码:
import web_webview from '@ohos.web.webview'import { print } from '@kit.BasicServicesKit';
@Entry@Componentstruct Index { //是否打印背景 @State printBackground: boolean = false scroller: Scroller = new Scroller() controller: web_webview.WebviewController = new web_webview.WebviewController() webPrintAdapter?: print.PrintDocumentAdapter
build() { Row() { Column() { Text("Web组件打印") .fontSize(14) .fontWeight(FontWeight.Bold) .width('100%') .textAlign(TextAlign.Center) .padding(10)
Flex({ justifyContent: FlexAlign.End, alignItems: ItemAlign.Center }) { Text("打印背景") .fontSize(14)
Checkbox() .select($$this.printBackground) .shape(CheckBoxShape.ROUNDED_SQUARE)
Button("打印") .onClick(() => { this.print() }) .width(60) .fontSize(14) } .width('100%') .padding(5)
Scroll(this.scroller) { Web({ src: $rawfile("print.html"), controller: this.controller }) .padding(10) .width('100%') .textZoomRatio(150) .backgroundColor(0xeeeeee) .javaScriptAccess(true) } .align(Alignment.Top) .backgroundColor(0xeeeeee) .height(300) .flexGrow(1) .scrollable(ScrollDirection.Vertical) .scrollBar(BarState.On) .scrollBarWidth(20) } .width('100%') .justifyContent(FlexAlign.Start) .height('100%') } .height('100%') }
//打印web组件内容 print() { if (this.webPrintAdapter == undefined) { this.webPrintAdapter = this.controller.createWebPrintDocumentAdapter("webPrint"); }
this.controller.setPrintBackground(this.printBackground) print.print("printJob", this.webPrintAdapter, null, getContext()) .then((task: print.PrintTask) => { task.on('succeed', () => { console.log('打印成功!'); }) }) }}
复制代码
步骤 5:编译运行,建议使用真机。
步骤 6:按照本节第 2 部分“web 组件打印演示”操作即可。
4. 代码分析
本示例代码较简单,需要注意的是网页内打印调用方法,即 window.print();另外一点是在应用侧打印时,注意不要多次创建打印适配器,本示例是通过判断打印适配器的变量是否为 undefined 实现的。
(本文作者原创,除非明确授权禁止转载)
本文源码地址:
https://gitee.com/zl3624/harmonyos_network_samples/tree/master/code/web/WebPrint
本系列源码地址:
https://gitee.com/zl3624/harmonyos_network_samples
评论