文档管理中心
我的

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

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

设置PDF文档预览效果

pdfViewManager为PDF文档提供了丰富的预览特性。

  • 单双页布局,是否连续滚动和页面适配方式。

  • 页面跳转,如上一页,下一页,跳转到指定页。

  • 页面放大、缩小。

图1:提供了双页预览布局,页面宽度适配和连续滚动的预览方式

接口说明

展开
接口名 描述
setPageLayout(columnCount: pdfService.PageLayout): void

设置页面布局模式。其中“columnCount”取值如下:

1:单页面。

2:双页面。

setPageContinuous(isContinuous: boolean): void 设置页面滚动是否连续排列。
setPageFit(pageFit: pdfService.PageFit): void 设置页面的适配模式。
goToPage(pageIndex: number): void 跳转到指定页。
setPageZoom(zoom: number): void 设置视图的缩放比例。

示例代码

  1. 先加载PDF文档。

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

  3. 在按钮【setPreviewMode】里,调用setPageLayout、setPageContinuous等方法,设置文档预览效果。

  4. 在按钮【goTopage】里,调用goToPage方法,设置页面跳转。

  5. 在按钮【zoomPage2】里,调用setPageZoom方法,将页面放大2倍。

收起
自动换行
深色代码主题
复制
  1. import { pdfService, PdfView, pdfViewManager } from '@kit.PDFKit';
  2. // ...
  3. @Entry
  4. @Component
  5. struct PdfViewPreviewMethod {
  6. private controller: pdfViewManager.PdfController = new pdfViewManager.PdfController();
  7. private context = this.getUIContext().getHostContext() as Context;
  8. private loadResult: pdfService.ParseResult = pdfService.ParseResult.PARSE_ERROR_FORMAT;
  9. aboutToAppear(): void {
  10. // 确保在工程目录src/main/resources/resfile里存在input.pdf文档
  11. let filePath = this.context.resourceDir + '/input.pdf';
  12. (async () => {
  13. this.loadResult = await this.controller.loadDocument(filePath);
  14. // 注意:这里刚加载文档,请不要在这里立即设置PDF文档的预览方法。
  15. })()
  16. }
  17. build() {
  18. Stack({ alignContent: Alignment.TopStart }) {
  19. PdfView({
  20. controller: this.controller,
  21. pageFit: pdfService.PageFit.FIT_WIDTH,
  22. showScroll: true
  23. })
  24. .id('pdfview_app_view')
  25. .width('100%')
  26. .height('100%')
  27. .margin({ top: 150 })
  28. Column({ space: 10 }) {
  29. // ...
  30. Row({ space: 10 }) {
  31. // 设置预览方式
  32. Button('setPreviewMode')
  33. .onClick(() => {
  34. if (this.loadResult === pdfService.ParseResult.PARSE_SUCCESS) {
  35. // 单页布局
  36. this.controller.setPageLayout(pdfService.PageLayout.LAYOUT_SINGLE);
  37. // 是否连续滚动预览
  38. this.controller.setPageContinuous(true);
  39. // 适配页的预览方式
  40. this.controller.setPageFit(pdfService.PageFit.FIT_PAGE);
  41. }
  42. })
  43. // 跳转到第11页
  44. Button('goTopage')
  45. .onClick(() => {
  46. if (this.loadResult === pdfService.ParseResult.PARSE_SUCCESS) {
  47. this.controller.goToPage(10);
  48. }
  49. })
  50. }
  51. Row({ space: 10 }) {
  52. // 页面放大2倍
  53. Button('zoomPage2')
  54. .onClick(() => {
  55. if (this.loadResult === pdfService.ParseResult.PARSE_SUCCESS) {
  56. this.controller.setPageZoom(2);
  57. }
  58. })
  59. }
  60. }
  61. .alignItems(HorizontalAlign.Start)
  62. .padding(10)
  63. }
  64. .width('100%').height('100%')
  65. }
  66. }