文档管理中心
我的

您当前正在浏览新版开发者文档中心,目录分类和层级有所调整。点击左侧当前文档分类名称前的“☰”图标,可切换文档分类。 了解新版目录

指南与API参考指南应用服务PDF Kit(PDF服务)PdfView预览组件预览PDF文档

预览PDF文档

本文导读

PDF Kit提供了丰富的PDF文档预览能力,比如:

  • 页面跳转

  • 页面缩放

  • 单双页显示

  • 页面适配

  • 滚动视图方式预览

详细说明及使用请参考:PdfView组件。

示例代码

  1. 导入相关模块。

  2. 以下示例代码中以预览“input.pdf”文件名为例,此时需要确保在工程目录“src/main/resources/rawfile”里存在input.pdf文档,并且拷贝input.pdf文档到沙箱目录。

  3. 调用loadDocument方法,加载PDF文档。

  4. 调用PdfView预览组件,渲染显示。

收起
自动换行
深色代码主题
复制
  1. import { pdfService, pdfViewManager, PdfView } from '@kit.PDFKit'
  2. import { fileIo } from '@kit.CoreFileKit';
  3. import { hilog } from '@kit.PerformanceAnalysisKit';
  4. import { BusinessError } from '@kit.BasicServicesKit';
  5. // ...
  6. @Entry
  7. @Component
  8. struct PreviewPage {
  9. private controller: pdfViewManager.PdfController = new pdfViewManager.PdfController();
  10. private context = this.getUIContext().getHostContext() as Context;
  11. aboutToAppear(): void {
  12. let dir: string = this.context.resourceDir
  13. // 确保在工程目录src/main/resources/resfile里存在input.pdf文档
  14. let filePath: string = dir + '/input.pdf';
  15. try {
  16. let res = fileIo.accessSync(filePath);
  17. if (!res) {
  18. let content: Uint8Array = this.context.resourceManager.getRawFileContentSync('resfile/input.pdf');
  19. let fdSand = fileIo.openSync(
  20. filePath,
  21. fileIo.OpenMode.WRITE_ONLY |
  22. fileIo.OpenMode.CREATE |
  23. fileIo.OpenMode.TRUNC
  24. );
  25. fileIo.writeSync(fdSand.fd, content.buffer);
  26. fileIo.closeSync(fdSand.fd);
  27. }
  28. } catch (e) {
  29. let error: BusinessError = e as BusinessError;
  30. hilog.error(0x0000, 'PreviewPage', `Code: ${error.code}, message: ${error.message} `);
  31. }
  32. (async () => {
  33. // 该监听方法只能在文档加载前调用一次
  34. this.controller.registerPageCountChangedListener((pageCount: number) => {
  35. hilog.info(0x0000, 'registerPageCountChanged-', pageCount.toString());
  36. });
  37. let loadResult1: pdfService.ParseResult = await this.controller.loadDocument(filePath);
  38. // 注意:这里刚加载文档,请不要在这里立即设置PDF文档的预览方式
  39. })()
  40. }
  41. build() {
  42. Stack({ alignContent: Alignment.TopStart }) {
  43. PdfView({
  44. controller: this.controller,
  45. pageFit: pdfService.PageFit.FIT_WIDTH,
  46. showScroll: true
  47. })
  48. .id('pdfview_app_view')
  49. // ...
  50. }
  51. .width('100%').height('100%')
  52. }
  53. }