鸿蒙系统下PdfKit功能实现详解(附示例代码)

前端 潘老师 1周前 (04-14) 14 ℃ (0) 扫码查看

本文将为大家详细介绍如何在鸿蒙系统里借助PdfKit实现PDF文件的查看、编辑等功能,代码示例均基于鸿蒙系统环境。

一、整体介绍

本示例聚焦于展示如何运用PDFKit提供的功能,实现对PDF文件内容的查看与编辑等操作。其中,相关功能通过PDFKit服务接口@kit.PDFKit引入。在正式讲解代码实现前,先了解一下最终的效果以及使用方法。

(一)效果预览

从实际运行效果来看,用户进入相关页面后,会看到几个操作选项,分别对应不同的PDF文件打开方式和预览功能。

(二)使用说明

进入应用页面后,有以下几个主要操作:

  • 点击“Open the PDF file on the computer”,这一操作会调用picker打开本地的pdf文件。
  • 点击“Opening a resource PDF file”,可以打开rawfile中的pdf文件。
  • 点击“Opening the PdfView file for preview”,就能开启pdf预览功能。

二、实现思路与代码详解

实现这些功能的核心在于通过pdfServicePdfView组件来操作PDF文档。下面对各个功能点的实现代码进行详细解读。

(一)打开PDF文档

要打开PDF文档,需指定文件路径并创建PdfDocument对象,示例代码如下:

// 定义要打开的PDF文件路径
let filePath = '/data/storage/el2/base/haps/View/files/input.pdf';
// 创建PdfDocument对象
let document: pdfService.PdfDocument = new pdfService.PdfDocument();
// 加载指定路径的PDF文档
document.loadDocument(filePath);

在这段代码中,先设定了要打开的PDF文件的路径,接着创建PdfDocument对象,最后通过该对象的loadDocument方法加载指定路径的PDF文档。

(二)将PDF转换为图片

把PDF转换为图片时,要先确定输出图片的保存路径,然后调用convertToImage方法,代码如下:

// 获取文件保存目录,并拼接输出图片的目录路径
let path: string = getContext().filesDir + "/outputImg/";
// 创建输出图片的目录
fs.mkdir(path);
// 将PDF文档的第一页转换为图片并保存到指定路径
const result: boolean = this.document.convertToImage(path, 0);

这里先获取应用的文件目录,拼接出输出图片的目录路径,并创建该目录。然后使用document对象的convertToImage方法,将PDF文档的第一页(参数0表示第一页)转换为图片并保存到指定路径,result用于接收转换操作的结果,true表示转换成功,false表示失败。

(三)添加页眉页脚

添加页眉页脚时,需创建HeaderFooterInfo对象,并设置各种属性,示例如下:

// 创建页眉页脚信息对象
let hfInfo: pdfService.HeaderFooterInfo = new pdfService.HeaderFooterInfo();
// 创建字体信息对象
hfInfo.fontInfo = new pdfService.FontInfo();
// 设置字体路径,确保该字体路径存在
hfInfo.fontInfo.fontPath = font.getFontByName("HarmonyOS Sans")?.path;  
hfInfo.fontInfo.fontName = '';
hfInfo.textSize = 10;
// 设置字符集
hfInfo.charset = pdfService.CharsetType.PDF_FONT_DEFAULT_CHARSET;
hfInfo.underline = false;
// 设置文本颜色,这里的颜色值是十六进制表示
hfInfo.textColor = 0x00000000;
hfInfo.leftMargin = 1.0;
hfInfo.topMargin = 40.0;
hfInfo.rightMargin = 1.0;
hfInfo.bottomMargin = 40.0;
// 设置页眉左侧文本,其中包含日期和页码的占位符
hfInfo.headerLeftText = "left H <<dd.mm.yyyy>> <<1/n>>";
hfInfo.headerCenterText = "center H <<m/d/yyyy>> <<1/n>>";
hfInfo.headerRightText = "right H <<m/d>><<1>>";
// 设置页脚左侧文本
hfInfo.footerLeftText = "left F <<m/d>><<1>>";
hfInfo.footerCenterText = "center F <<m/d>><<1>>";
hfInfo.footerRightText = "right F <<dd.mm.yyyy>><<1>>";
// 在第1页到第5页添加页眉页脚,最后两个参数表示是否添加页眉和页脚
this.document.addHeaderFooter(hfInfo, 1, 5, true, true);

这段代码先创建了HeaderFooterInfo对象,对字体、文本大小、颜色、边距以及页眉页脚的具体文本内容进行设置,最后调用addHeaderFooter方法,在指定的页面范围内添加页眉页脚。

(四)添加水印

添加水印的实现方式如下:

// 创建文本水印信息对象
let wminfo: pdfService.TextWatermarkInfo = new pdfService.TextWatermarkInfo();
// 设置水印类型为文本水印
wminfo.watermarkType = pdfService.WatermarkType.WATERMARK_TEXT;
wminfo.content = "This is Watermark";
wminfo.textSize = 30;
wminfo.textColor = 200;
// 创建字体信息对象并设置字体路径
wminfo.fontInfo = new pdfService.FontInfo();
wminfo.fontInfo.fontPath = font.getFontByName("HarmonyOS Sans").path;
wminfo.opacity = 0.5;
wminfo.isOnTop = true;
wminfo.rotation = 45;
wminfo.scale = 1.5;
wminfo.opacity = 0.5;
// 设置水印垂直对齐方式为顶部对齐
wminfo.verticalAlignment = pdfService.WatermarkAlignment.WATERMARK_ALIGNMENT_TOP;
// 设置水印水平对齐方式为左侧对齐
wminfo.horizontalAlignment = pdfService.WatermarkAlignment.WATERMARK_ALIGNMENT_LEFT;
wminfo.horizontalSpace = 1.0;
wminfo.verticalSpace = 1.0;
// 在第0页到第18页添加水印,最后两个参数表示是否覆盖原有内容
this.document.addWatermark(wminfo, 0, 18, true, true);

在这段代码里,创建TextWatermarkInfo对象,设置水印的各种属性,如类型、内容、字体、颜色、透明度、对齐方式等,然后使用addWatermark方法在指定页面范围内添加水印。

(五)添加页面背景图片

为PDF页面添加背景图片的代码如下:

// 创建背景信息对象
let bginfo: pdfService.BackgroundInfo = new pdfService.BackgroundInfo();
// 设置背景图片路径
bginfo.imagePath = this.backGroundImgPath = getContext().filesDir + "/background.png";
bginfo.backgroundColor = 50;
bginfo.isOnTop = true;
bginfo.rotation = 45;
bginfo.scale = 0.5;
bginfo.opacity = 0.3;
// 设置背景垂直对齐方式为顶部对齐
bginfo.verticalAlignment = pdfService.BackgroundAlignment.BACKGROUND_ALIGNMENT_TOP;
// 设置背景水平对齐方式为左侧对齐
bginfo.horizontalAlignment = pdfService.BackgroundAlignment.BACKGROUND_ALIGNMENT_LEFT;
bginfo.horizontalSpace = 1.0;
bginfo.verticalSpace = 1.0;
// 在第2页到第18页添加背景图片,最后两个参数表示是否覆盖原有内容
this.document.addBackground(bginfo, 2, 18, true, true);

这里创建BackgroundInfo对象,设置背景图片路径、颜色、透明度、旋转角度、对齐方式等属性,再通过addBackground方法在指定页面添加背景图片。

(六)添加书签

添加书签时,涉及创建书签、设置书签属性等操作,代码如下:

// 创建第一个书签
let mark1: pdfService.Bookmark = this.document.createBookmark();
// 创建第二个书签
let mark2: pdfService.Bookmark = this.document.createBookmark();
// 将第一个书签插入到文档中,父书签为null,页码为1
this.document.insertBookmark(mark1, null, 1);
// 将第二个书签插入到文档中,父书签为mark1,页码为1
this.document.insertBookmark(mark2, mark1, 1);
// 获取第一个书签的目标信息对象
let destInfo: pdfService.DestInfo = mark1.getDestInfo();
// 设置目标页面的显示模式为FIT_MODE_XYZ
destInfo.fitMode = pdfService.FitMode.FIT_MODE_XYZ;
destInfo.pageIndex = 1;
destInfo.left = 20;
destInfo.top = 30;
destInfo.zoom = 1.5;
// 设置第一个书签的目标信息
mark1.setDestInfo(destInfo);
// 获取第一个书签的书签信息对象
let bookInfo: pdfService.BookmarkInfo = mark1.getBookmarkInfo();
bookInfo.title = "这里是跳到第一页的书签";
bookInfo.titleColor = 12;
bookInfo.isBold = true;
bookInfo.isItalic = true;
// 设置第一个书签的书签信息
mark1.setBookmarkInfo(bookInfo);

这段代码展示了如何创建书签、插入书签、设置书签的目标页面显示属性以及书签的标题、颜色、字体样式等信息。

(七)通过PdfView组件实现预览功能

  1. 打开pdf文件
    借助PdfView组件打开pdf文件的代码如下:
// 获取应用上下文
let context = getContext() as common.UIAbilityContext;
// 获取应用的文件目录
let dir = context.filesDir;
// 拼接要打开的PDF文件路径
let filePath = dir + `/input.pdf`;
// 创建PdfController对象
this.controller = new pdfViewManager.PdfController();
// 加载PDF文档
let loadResult: pdfService.ParseResult = await this.controller.loadDocument(filePath);

PdfView({
    controller: this.controller,
    pageFit: pdfService.PageFit.FIT_WIDTH,
    showScroll: true
})
.id('pdfview_app_view')
.layoutWeight(1)

这段代码首先获取应用上下文和文件目录,拼接出要打开的PDF文件路径。然后创建PdfController对象,通过该对象加载PDF文档。最后创建PdfView组件,并设置相关属性,如控制器、页面适应方式、是否显示滚动条等。
2. 设置预览方式
设置预览方式的代码与打开pdf文件的代码部分重复,同样是先加载文档,再创建PdfView组件并设置属性:

// 获取应用上下文
let context = getContext() as common.UIAbilityContext;
// 获取应用的文件目录
let dir = context.filesDir;
// 拼接要打开的PDF文件路径
let filePath = dir + `/input.pdf`;
// 创建PdfController对象
this.controller = new pdfViewManager.PdfController();
// 加载PDF文档
let loadResult: pdfService.ParseResult = await this.controller.loadDocument(filePath);

PdfView({
    controller: this.controller,
    pageFit: pdfService.PageFit.FIT_WIDTH,
    showScroll: true
})
.id('pdfview_app_view')
.layoutWeight(1)

在实际应用中,可根据需求调整pageFit等属性来改变预览效果。
3. 设置监听
为了实现与用户的交互,还可以设置一些监听事件,比如文本选中、图片选中和页码变化的监听,代码如下:

// 文本选中监听回调
this.controller.registerTextSelectedListener((textSelect: pdfViewManager.TextSelectedParam) => {
    hilog.info(0x0000, '', 'registerTextSelectedListener'+textSelect.text);
});
// 图片选中监听回调
this.controller.registerImageSelectedListener((imageSelect: pdfViewManager.ImageSelectedParam) => {
    hilog.info(0x0000, '', 'registerImageSelectedListener'+imageSelect.toString());
});
// 页码变化监听回调
this.controller.registerPageChangedListener((pageIndex: number) => {
    hilog.info(0x0000, '', 'registerPageChangedListener'+pageIndex.toString());
});

这些监听回调函数会在相应的事件发生时被触发,方便开发者获取相关信息并进行后续处理。
4. 搜索关键字
在PDF文档中搜索关键字的代码如下:

this.controller.searchKey(this.inputStr, (index: number) => {
    hilog.info(0x0000, '', 'searchKey result index:'+index);
});

在这段代码中,this.inputStr是要搜索的关键字,通过searchKey方法进行搜索,搜索结果会在回调函数中返回,index表示关键字所在的页码(如果未找到,index可能为特定的错误值)。

通过以上步骤,我们就可以在鸿蒙系统中利用PdfKit实现对PDF文件的多种操作和预览功能。希望这些代码示例和解释能帮助大家在实际开发中更好地运用PdfKit。


版权声明:本站文章,如无说明,均为本站原创,转载请注明文章来源。如有侵权,请联系博主删除。
本文链接:https://www.panziye.com/front/17199.html
喜欢 (0)
请潘老师喝杯Coffee吧!】
分享 (0)
用户头像
发表我的评论
取消评论
表情 贴图 签到 代码

Hi,您需要填写昵称和邮箱!

  • 昵称【必填】
  • 邮箱【必填】
  • 网址【可选】