<template>
  <div class="pdf-preview">
    <div ref="pdfContainer"></div>
  </div>
</template>

<script>
import * as pdfjsLib from "pdfjs-dist";
import pdfWorker from "pdfjs-dist/build/pdf.worker.entry";

pdfjsLib.GlobalWorkerOptions.workerSrc = pdfWorker;

export default {
  props: {
    pdfUrl: {
      type: String,
      required: true,
    },
  },
  mounted() {
    this.loadPdf();
  },
  methods: {
    async loadPdf() {
      try {
        const loadingTask = pdfjsLib.getDocument(this.pdfUrl);
        const pdf = await loadingTask.promise;

        // 遍历每一页
        for (let pageNumber = 1; pageNumber <= pdf.numPages; pageNumber++) {
          const page = await pdf.getPage(pageNumber);
          await this.renderPage(page);
        }
      } catch (error) {
        console.error("加载 PDF 文件失败:", error);
      }
    },
    async renderPage(page) {
      const viewport = page.getViewport({ scale: 1.5 });

      // 创建一个 Canvas 元素
      const canvas = document.createElement("canvas");
      const context = canvas.getContext("2d");
      canvas.width = viewport.width;
      canvas.height = viewport.height;

      const renderContext = {
        canvasContext: context,
        viewport: viewport,
      };

      await page.render(renderContext).promise;

      // 将 Canvas 添加到容器中
      this.$refs.pdfContainer.appendChild(canvas);
    },
  },
};
</script>

<style>
.pdf-preview {
  text-align: center;
  margin: 16px 0;
}
canvas {
  border: 1px solid #ddd;
  margin-bottom: 16px;
}
</style>
