HarmonyOS pdfService.PdfPage获取的PixelMap,Image组件不能显示?

代码如下:

@Entry
@Component
struct PDGPage {
  @State pixelMap: image.PixelMap|string = ""
  aboutToAppear(): void {
    this.openFile()
  }
  //打开选择的PDF文件
  async openFile() {
    let context = getContext() as common.UIAbilityContext;
    let dir: string = context.filesDir
    // 确保rawfile里面有pdf文件
    let filePath: string = dir + "/pdf_reference.pdf";
    fileIo.accessSync(filePath);
    let content: Uint8Array = context.resourceManager.getRawFileContentSync('rawfile/26.pdf');
    let fdSand = fileIo.openSync(filePath, fileIo.OpenMode.WRITE_ONLY | fileIo.OpenMode.CREATE | fileIo.OpenMode.TRUNC);
    fileIo.writeSync(fdSand.fd, content.buffer);
    fileIo.closeSync(fdSand.fd);
    let document = new pdfService.PdfDocument
    document.loadDocument(filePath, '');
    let pageCount = document.getPageCount()
    // for (let i = 0; i < pageCount; i++) {
    let page: pdfService.PdfPage = document.getPage(0)
    this.pixelMap = page.getPagePixelMap(); //设置Image组件参数
    // }
  }

  build() {
    Column() {
      Image(this.pixelMap)
        .width('500')
        .objectFit(ImageFit.Contain)
    }
    .height('100%')
    .width('100%')
  }
阅读 583
1 个回答

.getPage(0)需使用getCustomPagePixelMap()规范page的大小。

参考demo:

import { fileIo } from '@kit.CoreFileKit';
import { pdfService } from '@kit.PDFKit';
import { common } from '@kit.AbilityKit';
import { image } from '@kit.ImageKit';

@Entry
@Component
struct PDGPage {
  @State pixelMap: image.PixelMap | string = ""

  aboutToAppear(): void {
    this.openFile()
  }

  //打开选择的PDF文件
  async openFile() {
    let context = getContext() as common.UIAbilityContext;
    let dir: string = context.filesDir
    // 确保rawfile里面有pdf文件
    let filePath: string = dir + "/pdf_reference.pdf"; // /26.pdf
    fileIo.accessSync(filePath);
    let content: Uint8Array = context.resourceManager.getRawFileContentSync('rawfile/26.pdf');
    let fdSand = fileIo.openSync(filePath, fileIo.OpenMode.WRITE_ONLY | fileIo.OpenMode.CREATE | fileIo.OpenMode.TRUNC);
    fileIo.writeSync(fdSand.fd, content.buffer);
    fileIo.closeSync(fdSand.fd);
    let document = new pdfService.PdfDocument
    console.error("a "+ document)
    document.loadDocument(filePath, '');
    let pageCount = document.getPageCount()
    console.error("ab "+ pageCount)
    let page: pdfService.PdfPage = document.getPage(0)
    console.error("abc "+ page)
    this.pixelMap = page.getCustomPagePixelMap({x:0,y:0,rotate:0,width:page.getWidth(),height:page.getHeight()},false,false)
    console.error("abcd "+ this.pixelMap)
  }

  build() {
    Column() {
      Image(this.pixelMap)
        .width('500')
        .objectFit(ImageFit.Contain)
        .height('500')
    }
    .height('100%')
    .width('100%')
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进