在許多應用場景中,將PDF文檔的每一頁轉換為單獨的圖片文件是非常有幫助的。這可以用于文檔的分享、掃描文檔的電子化存檔、或者進行進一步的文字識別處理等。本文將介紹如何使用華為HarmonyOS提供的PDF處理服務將整個PDF文檔轉換為圖片,并將這些圖片存放在指定的文件夾中。以往想實現這個功能都需要一些收費的插件,現在鴻蒙直接支持。
場景介紹
假設我們有一個PDF文檔,想要將其所有的頁面轉換為圖片格式,并且希望每一頁都生成一張單獨的圖片文件。所有生成的圖片文件需要存儲在一個指定的文件夾中,以便后續的處理和使用。HarmonyOS的PDF服務提供了將PDF文檔轉換為圖片的功能,支持多種圖片格式,具體可以參考ImageFormat。
接口說明
接口名 | 描述 |
---|---|
convertToImage(path: string, format: ImageFormat, onProgress?: Callback<number>): boolean | 轉換PDF文檔為圖片。 |
- 接口名:
convertToImage
- 描述: 將PDF文檔的每一頁轉換為圖片,并存儲在指定的目錄中。
- 參數:
path: string
:指定輸出圖片的文件夾路徑。format: ImageFormat
:指定圖片的輸出格式。onProgress?: Callback<number>
:可選參數,用于監聽轉換進度的回調函數。
示例代碼
下面是一個完整的示例代碼,演示如何將PDF文檔的所有頁面轉換為PNG格式的圖片,并存儲在應用的沙箱目錄下的output
文件夾中。
import { fileIo as fs } from '@kit.CoreFileKit';
import { common } from '@kit.AbilityKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { pdfService } from '@kit.PDFKit';@Entry
@Component
struct PdfPage {private pdfDocument: pdfService.PdfDocument = new pdfService.PdfDocument();private context = getContext() as common.UIAbilityContext;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);}build() {Column() {// 轉換PDF文檔的按鈕Button('convertToImage').onClick(async () => {if (this.loadResult === pdfService.ParseResult.PARSE_SUCCESS) {// 設置輸出路徑let outputPath = getContext().filesDir + '/output/';// 創建輸出目錄fs.mkdir(outputPath);// 將所有的頁面轉化為png圖片,并存儲在output文件夾里let res = this.pdfDocument.convertToImage(outputPath, pdfService.ImageFormat.PNG);// 記錄轉換結果日志hilog.info(0x0000, 'PdfPage', 'convertToImage %{public}s!', res ? 'success' : 'fail');}})}}
}
代碼解析
- 導入必要的模塊:首先,我們需要導入一些必要的模塊,包括文件IO操作模塊
fileIo
、上下文模塊common
、日志記錄模塊hilog
,以及PDF處理模塊pdfService
。 - 加載PDF文檔:在
aboutToAppear
生命周期方法中,我們通過loadDocument
方法加載PDF文檔。這里假設PDF文檔的路徑為應用沙箱目錄下的input.pdf
。 - 創建輸出目錄:在點擊按鈕觸發的事件處理函數中,我們首先檢查PDF文檔是否成功加載。如果成功,我們將創建一個用于存放輸出圖片的文件夾,路徑為應用沙箱目錄下的
output
文件夾。 - 轉換為圖片:然后,調用
convertToImage
方法,將PDF文檔的所有頁面轉換為PNG格式的圖片,并存放在剛剛創建的output
文件夾中。 - 日志記錄:最后,我們使用
hilog.info
方法記錄轉換的結果,以便于調試和日志查看。
轉換指定頁面為圖片
DF文檔頁面轉換為圖片,或將頁面的指定區域轉換為圖片時使用。
接口說明
接口名 | 描述 |
---|---|
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區域的圖片內容,并指定圖片的寬和高。 |
示例代碼
- 調用loadDocument方法加載PDF文檔。
- 調用getPage方法獲取某個頁面。
- 調用getPagePixelMap或getCustomPagePixelMap方法獲取當前頁面或者頁面區域,這時獲取的是image.PixelMap圖像類型。
- 將image.PixelMap圖像類型轉化為二進制圖片文件并保存,參考以下方法pixelMap2Buffer。
import { pdfService } from '@kit.PDFKit';import { image } from '@kit.ImageKit';import { fileIo as fs } from '@kit.CoreFileKit';import { common } from '@kit.AbilityKit';import { BusinessError } from '@kit.BasicServicesKit';@Entry@Componentstruct PdfPage {private pdfDocument: pdfService.PdfDocument = new pdfService.PdfDocument();private context = getContext() as common.UIAbilityContext;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:圖片打包格式,只支持 jpg 和 webpquality:JPEG 編碼輸出圖片質量bufferSize:圖片大小,默認 10M*/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)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)}})// 獲取指定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);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);}})// 獲取指定PdfPage區域的圖片內容Button('getAreaPixelMap').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.getAreaPixelMap(matrix, 400, 400, true, false);if (!pixmap) {return}const imgBuffer = await this.pixelMap2Buffer(pixmap)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);}})}}}
總結
通過上述步驟和代碼,我們可以輕松地實現將一個PDF文檔的所有頁面轉換為單獨的圖片文件,并存放在指定的文件夾中。這種方法對于需要對PDF文檔進行處理或分享的場景非常有用。請注意,實際開發中需要處理各種異常情況,確保程序的健壯性和用戶體驗。