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

<script>
import pdfjsLib from 'pdfjs-dist';
import { getDocument } from 'pdfjs-dist/build/pdf';

export default {
  props: {
    url: {
      type: String,
      required: true,
    },
  },
  data() {
    return {
      loading: false,
      page: 1,
      scale: 1,
      canvas: null,
      ctx: null,
    };
  },
  mounted() {
    this.canvas = this.$refs.pdfCanvas;
    this.ctx = this.canvas.getContext('2d');
    this.loadPdf();
  },
  methods: {
    async loadPdf() {
      this.loading = true;

      const doc = await getDocument(this.url).promise;
      this.pdfDoc = doc;
      this.numPages = doc.numPages;

      this.renderPage(1);
    },

    async renderPage(pageNumber) {
      if (!this.pdfDoc) {
        return;
      }

      this.loading = true;

      const page = await this.pdfDoc.getPage(pageNumber);

      const viewport = page.getViewport({ scale: this.scale });
      this.canvas.width = viewport.width;
      this.canvas.height = viewport.height;

      const renderContext = {
        canvasContext: this.ctx,
        viewport,
      };

      page.render(renderContext);

      this.loading = false;
    },

    nextPage() {
      if (this.page < this.numPages) {
        this.page++;
        this.renderPage(this.page);
      }
    },

    prevPage() {
      if (this.page > 1) {
        this.page--;
        this.renderPage(this.page);
      }
    },

    zoomIn() {
      this.scale += 0.2;
      this.renderPage(this.page);
    },

    zoomOut() {
      this.scale -= 0.2;
      this.renderPage(this.page);
    },
  },
};
</script>

<style scoped>
.pdf-preview canvas {
  display: block;
}
</style>
