PDF预览功能

发布于:2024-07-11 ⋅ 阅读:(23) ⋅ 点赞:(0)

<template>
  <div id="pdf-view">
    <canvas v-for="page in state.pdfPages" :key="page" id="pdfCanvas" />
    <div id="text-view"></div>
  </div>
</template>

<script setup lang="ts">
  import { reactive, onMounted, nextTick } from "vue";
  import * as PDF from "pdfjs-dist";
  import * as pdfjsWorker from "pdfjs-dist/build/pdf.worker.mjs";
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  (window as any).pdfjsWorker = pdfjsWorker;

  import pdf from "./compressed.tracemonkey-pldi-09.pdf";

  defineOptions({
    name: "PdfViewer"
  });

  const state = reactive({
    // 文件路径
    pdfPath: pdf,
    // 总页数
    pdfPages: 1,
    // 页面缩放
    pdfScale: 2
  });

  onMounted(() => {
    loadFile(state.pdfPath);
  });

  let pdfDoc: PDF.PDFDocumentProxy | null = null;

  const loadFile = (url: string) => {
    PDF.getDocument({
      url,
      cMapUrl: "https://cdn.jsdelivr.net/npm/pdfjs-dist@4.3.136/cmaps/",
      cMapPacked: true
    }).promise.then((pdf) => {
      console.log("pdf", pdf);
      pdfDoc = pdf;
      // 获取pdf文件总页数
      state.pdfPages = pdf.numPages;
      nextTick(() => {
        renderPage(1); // 从第一页开始渲染
      });
    });
  };

  const renderPage = (num: number) => {
    pdfDoc!.getPage(num).then((page) => {
      const canvas = document.getElementById("pdfCanvas")! as HTMLCanvasElement;
      if (canvas) {
        const ctx = canvas.getContext("2d")!;
        const viewport = page.getViewport({ scale: state.pdfScale });
        canvas.width = viewport.width;
        canvas.height = viewport.height;
        page.render({
          canvasContext: ctx,
          viewport
        });
      }
    });
  };
</script>