文章目录createPdf 是什么配置参数说清楚Callback 方式Promise 方式完整流程图那个最容易忽略的坑权限配置写在最后能把一张网页直接转成 PDF保存到本地——这个需求在报表、电子凭证、文档生成场景里非常常见。HarmonyOS 的 Web 组件内置了createPdf接口不需要引入任何第三方库直接调用就行。今天把 Callback 和 Promise 两种写法都讲清楚并且重点说清楚那个最容易忽略的坑。createPdf 是什么WebviewController.createPdf()是 Web 组件控制器上的一个方法它把当前 Web 组件渲染的页面内容截取成 PDF 格式以二进制数据流的形式返回给你。你拿到这个数据流之后可以用fileIo把它写成.pdf文件存到应用沙箱目录里或者分享给用户下载。配置参数说清楚调用createPdf前需要传一个PdfConfiguration对象// PdfConfiguration 的完整字段单位英寸constpdfConfig:webview.PdfConfiguration{width:8.27,// 页面宽度8.27 英寸 ≈ A4 纸宽度height:11.69,// 页面高度11.69 英寸 ≈ A4 纸高度marginTop:0,// 上边距marginBottom:0,// 下边距marginRight:0,// 右边距marginLeft:0,// 左边距shouldPrintBackground:true// 是否打印背景色/背景图};注意单位是英寸不是毫米也不是像素。A4 纸尺寸换算宽210mm ÷ 25.4 ≈8.27 英寸高297mm ÷ 25.4 ≈11.69 英寸shouldPrintBackground: true建议开启否则有背景色的页面导出来是白底效果很差。Callback 方式import{fileIo}fromkit.CoreFileKit;import{webview}fromkit.ArkWeb;import{BusinessError}fromkit.BasicServicesKit;import{common}fromkit.AbilityKit;EntryComponentstruct Index{controller:webview.WebviewControllernewwebview.WebviewController();pdfConfig:webview.PdfConfiguration{width:8.27,height:11.69,marginTop:0,marginBottom:0,marginRight:0,marginLeft:0,shouldPrintBackground:true};build(){Column(){Button(保存为 PDFCallback 方式).onClick((){this.controller.createPdf(this.pdfConfig,(error,result:webview.PdfData){if(error){console.error(生成PDF失败:${(errorasBusinessError).message});return;}try{letcontextthis.getUIContext().getHostContext()ascommon.UIAbilityContext;letfilePathcontext.filesDir/output.pdf;letfilefileIo.openSync(filePath,fileIo.OpenMode.READ_WRITE|fileIo.OpenMode.CREATE);// result.pdfArrayBuffer() 返回 Uint8Array.buffer 取得背后的 ArrayBufferfileIo.write(file.fd,result.pdfArrayBuffer().buffer).then((writeLen:number){console.info(PDF写入成功文件大小:${writeLen}bytes);}).catch((err:BusinessError){console.error(写入失败:${err.message}, code:${err.code});}).finally((){fileIo.closeSync(file);// 无论成功失败都要关闭文件句柄});}catch(resError){console.error(处理PDF数据时出错:${(resErrorasBusinessError).message});}});})Web({src:https://www.example.com,controller:this.controller}).width(100%).layoutWeight(1)}.height(100%).width(100%)}}Promise 方式import{fileIo}fromkit.CoreFileKit;import{webview}fromkit.ArkWeb;import{BusinessError}fromkit.BasicServicesKit;import{common}fromkit.AbilityKit;EntryComponentstruct Index{controller:webview.WebviewControllernewwebview.WebviewController();pdfConfig:webview.PdfConfiguration{width:8.27,height:11.69,marginTop:0,marginBottom:0,marginRight:0,marginLeft:0,shouldPrintBackground:true};build(){Column(){Button(保存为 PDFPromise 方式).onClick((){this.controller.createPdf(this.pdfConfig).then((result:webview.PdfData){letcontextthis.getUIContext().getHostContext()ascommon.UIAbilityContext;letfilePathcontext.filesDir/output.pdf;letfilefileIo.openSync(filePath,fileIo.OpenMode.READ_WRITE|fileIo.OpenMode.CREATE);returnfileIo.write(file.fd,result.pdfArrayBuffer().buffer).then((writeLen:number){console.info(PDF写入成功文件大小:${writeLen}bytes);returnfile;}).catch((err:BusinessError){console.error(写入失败:${err.message});returnfile;}).then((file){fileIo.closeSync(file);});}).catch((err:BusinessError){console.error(生成PDF失败:${err.message}, code:${err.code});});})Web({src:https://www.example.com,controller:this.controller}).width(100%).layoutWeight(1)}.height(100%).width(100%)}}两种方式功能完全一样Promise 方式更现代链式调用更清晰。如果你的项目支持async/await可以进一步简化asyncfunctionsavePdf(controller:webview.WebviewController,context:common.UIAbilityContext){try{constresultawaitcontroller.createPdf({width:8.27,height:11.69,marginTop:0,marginBottom:0,marginRight:0,marginLeft:0,shouldPrintBackground:true});constfilePathcontext.filesDir/output.pdf;constfilefileIo.openSync(filePath,fileIo.OpenMode.READ_WRITE|fileIo.OpenMode.CREATE);try{constwriteLenawaitfileIo.write(file.fd,result.pdfArrayBuffer().buffer);console.info(PDF生成成功大小:${writeLen}bytes路径:${filePath});}finally{fileIo.closeSync(file);}}catch(err){console.error(PDF生成失败:${(errasBusinessError).message});}}完整流程图那个最容易忽略的坑必须等页面渲染完成再调用createPdf如果页面还在加载中就调用createPdf生成的 PDF 可能是空白的或者只有部分内容。正确做法是监听onPageEnd事件在页面加载完成后再允许用户触发 PDF 生成EntryComponentstruct Index{controller:webview.WebviewControllernewwebview.WebviewController();StatepageReady:booleanfalse;build(){Column(){Button(保存为 PDF).enabled(this.pageReady)// 页面未加载完时按钮禁用.onClick((){if(!this.pageReady)return;// 调用 createPdf...})Web({src:https://www.example.com,controller:this.controller}).onPageEnd((){this.pageReadytrue;// 页面加载完成后才开放}).width(100%).layoutWeight(1)}}}权限配置生成 PDF 不需要额外权限但如果 Web 组件加载的是网络地址https://需要在module.json5里声明网络权限{module:{requestPermissions:[{name:ohos.permission.INTERNET}]}}加载本地$rawfile()文件则不需要。写在最后createPdf这个接口用法并不复杂难点在于参数单位是英寸要换算好pdfArrayBuffer()返回的是Uint8Array写文件时要取.buffer页面必须加载完成才能调用否则生成空白 PDF
HarmonyOS ArkWeb 系列之网页秒变PDF:createPdf 完整指南
发布时间:2026/5/20 1:29:12
文章目录createPdf 是什么配置参数说清楚Callback 方式Promise 方式完整流程图那个最容易忽略的坑权限配置写在最后能把一张网页直接转成 PDF保存到本地——这个需求在报表、电子凭证、文档生成场景里非常常见。HarmonyOS 的 Web 组件内置了createPdf接口不需要引入任何第三方库直接调用就行。今天把 Callback 和 Promise 两种写法都讲清楚并且重点说清楚那个最容易忽略的坑。createPdf 是什么WebviewController.createPdf()是 Web 组件控制器上的一个方法它把当前 Web 组件渲染的页面内容截取成 PDF 格式以二进制数据流的形式返回给你。你拿到这个数据流之后可以用fileIo把它写成.pdf文件存到应用沙箱目录里或者分享给用户下载。配置参数说清楚调用createPdf前需要传一个PdfConfiguration对象// PdfConfiguration 的完整字段单位英寸constpdfConfig:webview.PdfConfiguration{width:8.27,// 页面宽度8.27 英寸 ≈ A4 纸宽度height:11.69,// 页面高度11.69 英寸 ≈ A4 纸高度marginTop:0,// 上边距marginBottom:0,// 下边距marginRight:0,// 右边距marginLeft:0,// 左边距shouldPrintBackground:true// 是否打印背景色/背景图};注意单位是英寸不是毫米也不是像素。A4 纸尺寸换算宽210mm ÷ 25.4 ≈8.27 英寸高297mm ÷ 25.4 ≈11.69 英寸shouldPrintBackground: true建议开启否则有背景色的页面导出来是白底效果很差。Callback 方式import{fileIo}fromkit.CoreFileKit;import{webview}fromkit.ArkWeb;import{BusinessError}fromkit.BasicServicesKit;import{common}fromkit.AbilityKit;EntryComponentstruct Index{controller:webview.WebviewControllernewwebview.WebviewController();pdfConfig:webview.PdfConfiguration{width:8.27,height:11.69,marginTop:0,marginBottom:0,marginRight:0,marginLeft:0,shouldPrintBackground:true};build(){Column(){Button(保存为 PDFCallback 方式).onClick((){this.controller.createPdf(this.pdfConfig,(error,result:webview.PdfData){if(error){console.error(生成PDF失败:${(errorasBusinessError).message});return;}try{letcontextthis.getUIContext().getHostContext()ascommon.UIAbilityContext;letfilePathcontext.filesDir/output.pdf;letfilefileIo.openSync(filePath,fileIo.OpenMode.READ_WRITE|fileIo.OpenMode.CREATE);// result.pdfArrayBuffer() 返回 Uint8Array.buffer 取得背后的 ArrayBufferfileIo.write(file.fd,result.pdfArrayBuffer().buffer).then((writeLen:number){console.info(PDF写入成功文件大小:${writeLen}bytes);}).catch((err:BusinessError){console.error(写入失败:${err.message}, code:${err.code});}).finally((){fileIo.closeSync(file);// 无论成功失败都要关闭文件句柄});}catch(resError){console.error(处理PDF数据时出错:${(resErrorasBusinessError).message});}});})Web({src:https://www.example.com,controller:this.controller}).width(100%).layoutWeight(1)}.height(100%).width(100%)}}Promise 方式import{fileIo}fromkit.CoreFileKit;import{webview}fromkit.ArkWeb;import{BusinessError}fromkit.BasicServicesKit;import{common}fromkit.AbilityKit;EntryComponentstruct Index{controller:webview.WebviewControllernewwebview.WebviewController();pdfConfig:webview.PdfConfiguration{width:8.27,height:11.69,marginTop:0,marginBottom:0,marginRight:0,marginLeft:0,shouldPrintBackground:true};build(){Column(){Button(保存为 PDFPromise 方式).onClick((){this.controller.createPdf(this.pdfConfig).then((result:webview.PdfData){letcontextthis.getUIContext().getHostContext()ascommon.UIAbilityContext;letfilePathcontext.filesDir/output.pdf;letfilefileIo.openSync(filePath,fileIo.OpenMode.READ_WRITE|fileIo.OpenMode.CREATE);returnfileIo.write(file.fd,result.pdfArrayBuffer().buffer).then((writeLen:number){console.info(PDF写入成功文件大小:${writeLen}bytes);returnfile;}).catch((err:BusinessError){console.error(写入失败:${err.message});returnfile;}).then((file){fileIo.closeSync(file);});}).catch((err:BusinessError){console.error(生成PDF失败:${err.message}, code:${err.code});});})Web({src:https://www.example.com,controller:this.controller}).width(100%).layoutWeight(1)}.height(100%).width(100%)}}两种方式功能完全一样Promise 方式更现代链式调用更清晰。如果你的项目支持async/await可以进一步简化asyncfunctionsavePdf(controller:webview.WebviewController,context:common.UIAbilityContext){try{constresultawaitcontroller.createPdf({width:8.27,height:11.69,marginTop:0,marginBottom:0,marginRight:0,marginLeft:0,shouldPrintBackground:true});constfilePathcontext.filesDir/output.pdf;constfilefileIo.openSync(filePath,fileIo.OpenMode.READ_WRITE|fileIo.OpenMode.CREATE);try{constwriteLenawaitfileIo.write(file.fd,result.pdfArrayBuffer().buffer);console.info(PDF生成成功大小:${writeLen}bytes路径:${filePath});}finally{fileIo.closeSync(file);}}catch(err){console.error(PDF生成失败:${(errasBusinessError).message});}}完整流程图那个最容易忽略的坑必须等页面渲染完成再调用createPdf如果页面还在加载中就调用createPdf生成的 PDF 可能是空白的或者只有部分内容。正确做法是监听onPageEnd事件在页面加载完成后再允许用户触发 PDF 生成EntryComponentstruct Index{controller:webview.WebviewControllernewwebview.WebviewController();StatepageReady:booleanfalse;build(){Column(){Button(保存为 PDF).enabled(this.pageReady)// 页面未加载完时按钮禁用.onClick((){if(!this.pageReady)return;// 调用 createPdf...})Web({src:https://www.example.com,controller:this.controller}).onPageEnd((){this.pageReadytrue;// 页面加载完成后才开放}).width(100%).layoutWeight(1)}}}权限配置生成 PDF 不需要额外权限但如果 Web 组件加载的是网络地址https://需要在module.json5里声明网络权限{module:{requestPermissions:[{name:ohos.permission.INTERNET}]}}加载本地$rawfile()文件则不需要。写在最后createPdf这个接口用法并不复杂难点在于参数单位是英寸要换算好pdfArrayBuffer()返回的是Uint8Array写文件时要取.buffer页面必须加载完成才能调用否则生成空白 PDF