目录

Converting a Specified Page or Area to an Image

Use Cases

Converts a PDF document page or a specified area on a page to an image. Since version 26.0.0, specified areas on multiple pages can be merged into one image.

API Description

API Name Description
getPagePixelMap(): image.PixelMap Obtains the image of the current page.
getCustomPagePixelMap(matrix: PdfMatrix, isGray: boolean, drawAnnotations: boolean): image.PixelMap Obtains the image content in the specified PdfPage area.
getAreaPixelMap(matrix: PdfMatrix, bitmapwidth: number, bitmapHeight: number, isGray: boolean, drawAnnotations: boolean): image.PixelMap Obtains the image content in the specified PdfPage area and specifies the width and height of the image.
getAreaPixelMapWithOptions(matrix: PdfMatrix, bitmapwidth: number, bitmapHeight: number, options?: PixelOptions): image.PixelMap Obtains the image content in the specified PdfPage area and specifies parameters, such as the width and height of the image.
getPixelMapWithPages(pageIndices: number[], matrices: PdfMatrix[], bitmapWidth: number, bitmapHeight: number, pixelOptions?: PixelOptions): image.PixelMap Obtains the pixelMap after multiple pages are merged.

Sample Code

  1. Call the loadDocument method to load a PDF document.

  2. Call the getPage method to obtain a page.

  3. Call the getPagePixelMap, getAreaPixelMapWithOptions, and getCustomPagePixelMap (or getPixelMapWithPages) methods to obtain the current page and page area (or specify multiple pages). The return values are all image.PixelMap images.

  4. Convert the image.PixelMap image into a binary image file and save it by referring to the following pixelMap2Buffer method.

import { pdfService } from '@kit.PDFKit';
import { image } from '@kit.ImageKit';
import { fileIo } from '@kit.CoreFileKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
// ...

@Entry
@Component
struct 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 {
    // Ensure that the input.pdf document exists in the src/main/resources/resfile project directory.
    let filePath = this.context.resourceDir + '/input.pdf';
    this.loadResult = this.pdfDocument.loadDocument(filePath);
  }

  // Convert pixelMap to the image format.
  pixelMap2Buffer(pixelMap: image.PixelMap): Promise<ArrayBuffer> {
    return new Promise((resolve, reject) => {
         /**
          Set packing parameters.
          format: image packaging format
          quality: quality of the output image during JPEG encoding
          bufferSize: image size.
          */
      let packOpts: image.PackingOption = { format: 'image/jpeg', quality: 98 }
      // Create an ImagePacker instance.
      const imagePackerApi = image.createImagePacker()
      imagePackerApi.packToData(pixelMap, packOpts).then((buffer: ArrayBuffer) => {
        resolve(buffer)
      }).catch((err: BusinessError) => {
        reject()
      })
    })
  }

  build() {
    Column() {
      // ...
        // Obtain it as an image and save it to the app sandbox.
        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 =
                fileIo.openSync(this.context.filesDir + `/${Date.now()}.png`, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE);
              await fileIo.write(file.fd, imgBuffer)
              // Close the document.
              await fileIo.close(file.fd)
            } catch (e) {
              let error: BusinessError = e as BusinessError;
              hilog.error(0x0000, 'PdfPage', `Code: ${error.code}, message: ${error.message} `);
            }
          }
        })
        // Obtain the image content in the specified PdfPage area.
        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 =
                fileIo.openSync(this.context.filesDir + `/${Date.now()}.jpeg`, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE);
              await fileIo.write(file.fd, imgBuffer);
              await fileIo.close(file.fd);
            } catch (e) {
              let error: BusinessError = e as BusinessError;
              hilog.error(0x0000, 'PdfPage', `Code: ${error.code}, message: ${error.message} `);
            }
          }
        })
        // Obtain the image content in the specified PdfPage area.
        Button('getAreaPixelMap').onClick(async () => {
          if (this.loadResult === pdfService.ParseResult.PARSE_SUCCESS) {
            // Obtain the corresponding page.
            let page = this.pdfDocument.getPage(0);
            let matrix = new pdfService.PdfMatrix();
            // Set the matrix to control the area to be obtained.
            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 =
                fileIo.openSync(this.context.filesDir + `/${Date.now()}.bmp`, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE);
              await fileIo.write(file.fd, imgBuffer)
              await fileIo.close(file.fd);
            } catch (e) {
              let error: BusinessError = e as BusinessError;
              hilog.error(0x0000, 'PdfPage', `Code: ${error.code}, message: ${error.message} `);
            }
          }
        })
        Button('getAreaPixelMapWithOptions').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;
            // Set parameters, such as whether the PixelMap is in black and white and whether the background is transparent.
            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 =
                fileIo.openSync(this.context.filesDir + `/${Date.now()}.bmp`, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE);
              await fileIo.write(file.fd, imgBuffer)
              await fileIo.close(file.fd);
            } catch (e) {
              let error: BusinessError = e as BusinessError;
              hilog.error(0x0000, 'PdfPage', `Code: ${error.code}, message: ${error.message} `);
            }
          }
        })
        // ...
    }
  }
}