<template>
  <div class="pdf-viewer">
    <canvas ref="pdfCanvas"></canvas>
    <div v-if="loading" class="loading">加载中...</div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import * as pdfjsLib from 'pdfjs-dist';


pdfjsLib.GlobalWorkerOptions.workerSrc = new URL(
  'pdfjs-dist/build/pdf.worker.min.mjs',
  import.meta.url
).href;

export default {
  name: 'PdfViewer',
  props: {
    pdfUrl: {
      type: String,
      required: true
    }
  },
  setup(props) {
    const pdfCanvas = ref(null);
    const loading = ref(true);

    onMounted(async () => {
      try {
        const loadingTask = pdfjsLib.getDocument(props.pdfUrl);
        const pdf = await loadingTask.promise;
        const page = await pdf.getPage(1); // 加载第一页

        const viewport = page.getViewport({ scale: 1.5 });
        const context = pdfCanvas.value.getContext('2d');
        const renderContext = {
          canvasContext: context,
          viewport: viewport
        };

        pdfCanvas.value.width = viewport.width;
        pdfCanvas.value.height = viewport.height;

        await page.render(renderContext).promise;
      } catch (error) {
        console.error('加载 PDF 出错:', error);
      } finally {
        loading.value = false;
      }
    });

    return {
      pdfCanvas,
      loading
    };
  }
};
</script>

<style scoped>
.pdf-viewer {
  position: relative;
  width: 100%;
  height: 800px;
}

canvas {
  width: 100%;
  height: 100%;
}

.loading {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 18px;
  color: #333;
}
</style>