转换指定页面或指定区域为图片
场景介绍
PDF文档页面转换为图片,或将页面的指定区域转换为图片时使用。
接口说明
| 接口名 | 描述 |
|---|---|
| getPagePixelMap(): image.PixelMap | 获取当前页的图片。 |
| getCustomPagePixelMap(matrix: PdfMatrix, isGray: boolean, drawAnnotations: boolean): image.PixelMap | 获取指定PdfPage区域的图片内容。 |
| getAreaPixelMap(matrix: PdfMatrix, bitmapwidth: number, bitmapHeight: number, isGray: boolean, drawAnnotations: boolean): image.PixelMap | 获取指定PdfPage区域的图片内容,并指定图片的宽和高。 |
| getAreaPixelMapWithOptions(matrix: PdfMatrix, bitmapwidth: number, bitmapHeight: number, options?: PixelOptions): image.PixelMap | 获取指定PdfPage区域的图片内容,并指定图片的宽和高等参数。 |
示例代码
-
调用loadDocument方法加载PDF文档。
-
调用getPage方法获取某个页面。
-
调用getPagePixelMap,getAreaPixelMapWithOptions或getCustomPagePixelMap方法获取当前页面或者页面区域,这时获取的是image.PixelMap图像类型。
-
将image.PixelMap图像类型转化为二进制图片文件并保存,参考以下方法pixelMap2Buffer。
import { pdfService } from '@kit.PDFKit';import { image } from '@kit.ImageKit';import { fileIo as fs } from '@kit.CoreFileKit';import { BusinessError } from '@kit.BasicServicesKit';import { hilog } from '@kit.PerformanceAnalysisKit';@Entry@Componentstruct PdfPage {private pdfDocument: pdfService.PdfDocument = new pdfService.PdfDocument();private context = this.getUIContext().getHostContext() as Context;private loadResult: pdfService.ParseResult = pdfService.ParseResult.PARSE_ERROR_FORMAT;aboutToAppear(): void {// 确保沙箱目录有input.pdf文档let filePath = this.context.filesDir + '/input.pdf';this.loadResult = this.pdfDocument.loadDocument(filePath);}// 将 pixelMap 转成图片格式pixelMap2Buffer(pixelMap: image.PixelMap): Promise<ArrayBuffer> {return new Promise((resolve, reject) => {/**设置打包参数format:图片打包格式quality:JPEG 编码输出图片质量bufferSize:图片大小*/let packOpts: image.PackingOption = { format: 'image/jpeg', quality: 98 }// 创建ImagePacker实例const imagePackerApi = image.createImagePacker()imagePackerApi.packToData(pixelMap, packOpts).then((buffer: ArrayBuffer) => {resolve(buffer)}).catch((err: BusinessError) => {reject()})})}build() {Column() {// 获取为图片并保存到应用沙箱Button('getPagePixelMap').onClick(async () => {if (this.loadResult === pdfService.ParseResult.PARSE_SUCCESS) {let page = this.pdfDocument.getPage(0)let pixmap: image.PixelMap = page.getPagePixelMap();if (!pixmap) {return}const imgBuffer = await this.pixelMap2Buffer(pixmap)try {const file =fs.openSync(this.context.filesDir + `/${Date.now()}.png`, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);await fs.write(file.fd, imgBuffer)// 关闭文档await fs.close(file.fd)} catch (e) {let error: BusinessError = e as BusinessError;hilog.error(0x0000, 'PdfPage', `Code: ${error.code}, message: ${error.message} `);}}})// 获取指定PdfPage区域的图片内容。Button('getCustomPagePixelMap').onClick(async () => {if (this.loadResult === pdfService.ParseResult.PARSE_SUCCESS) {let page = this.pdfDocument.getPage(0);let matrix = new pdfService.PdfMatrix();matrix.x = 100;matrix.y = 100;matrix.width = 500;matrix.height = 500;matrix.rotate = 0;let pixmap: image.PixelMap = page.getCustomPagePixelMap(matrix, false, false);if (!pixmap) {return;}const imgBuffer = await this.pixelMap2Buffer(pixmap);try {const file =fs.openSync(this.context.filesDir + `/${Date.now()}.jpeg`, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);await fs.write(file.fd, imgBuffer);// 关闭文件await fs.close(file.fd);} catch (e) {let error: BusinessError = e as BusinessError;hilog.error(0x0000, 'PdfPage', `Code: ${error.code}, message: ${error.message} `);}}})// 获取指定PdfPage区域的图片内容Button('getAreaPixelMap').onClick(async () => {if (this.loadResult === pdfService.ParseResult.PARSE_SUCCESS) {//获取对应的pagelet page = this.pdfDocument.getPage(0);let matrix = new pdfService.PdfMatrix();//设置matrix来控制需要获取的区域matrix.x = 100;matrix.y = 100;matrix.width = 500;matrix.height = 500;matrix.rotate = 0;let pixmap: image.PixelMap = page.getAreaPixelMap(matrix, 400, 400, true, false);if (!pixmap) {return}const imgBuffer = await this.pixelMap2Buffer(pixmap)try {const file =fs.openSync(this.context.filesDir + `/${Date.now()}.bmp`, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);await fs.write(file.fd, imgBuffer)// 关闭文件await fs.close(file.fd);} catch (e) {let error: BusinessError = e as BusinessError;hilog.error(0x0000, 'PdfPage', `Code: ${error.code}, message: ${error.message} `);}}})// 获取指定PdfPage区域的图片内容Button('getAreaPixelMapWithOptions').onClick(async () => {if (this.loadResult === pdfService.ParseResult.PARSE_SUCCESS) {//获取对应pagelet page = this.pdfDocument.getPage(0);let matrix = new pdfService.PdfMatrix();//设置matrix来控制需要获取的区域matrix.x = 100;matrix.y = 100;matrix.width = 500;matrix.height = 500;matrix.rotate = 0;//设置pixelmap是否黑白,背景是否透明等参数let options = new pdfService.PixelOptions();options.isGray = false;options.drawAnnotations = true;options.isTransparent = true;let pixmap: image.PixelMap = page.getAreaPixelMapWithOptions(matrix, 400, 400, options);if (!pixmap) {return}const imgBuffer = await this.pixelMap2Buffer(pixmap)try {const file =fs.openSync(this.context.filesDir + `/${Date.now()}.bmp`, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);await fs.write(file.fd, imgBuffer)// 关闭文件await fs.close(file.fd);} catch (e) {let error: BusinessError = e as BusinessError;hilog.error(0x0000, 'PdfPage', `Code: ${error.code}, message: ${error.message} `);}}})}}}