summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/pdf/index.vue
blob: 4603859d7b0bc9e9ad0011258524f5f83523a4d5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
<template>
  <div class="pdf-viewer" v-if="hasPDF">
    <page v-for="(page, index) in pages"
      :key="index"
      :v-if="!loading"
      :page="page"
      :number="index + 1" />
  </div>
</template>

<script>
  import pdfjsLib from 'pdfjs-dist';
  import workerSrc from 'vendor/pdf.worker';

  import page from './page/index.vue';

  export default {
    props: {
      pdf: {
        type: [String, Uint8Array],
        required: true,
      },
    },
    data() {
      return {
        loading: false,
        pages: [],
      };
    },
    components: { page },
    watch: { pdf: 'load' },
    computed: {
      document() {
        return typeof this.pdf === 'string' ? this.pdf : { data: this.pdf };
      },
      hasPDF() {
        return this.pdf && this.pdf.length > 0;
      },
    },
    methods: {
      load() {
        this.pages = [];
        return pdfjsLib.getDocument(this.document)
          .then(this.renderPages)
          .then(() => this.$emit('pdflabload'))
          .catch(error => this.$emit('pdflaberror', error))
          .then(() => { this.loading = false; });
      },
      renderPages(pdf) {
        const pagePromises = [];
        this.loading = true;
        for (let num = 1; num <= pdf.numPages; num += 1) {
          pagePromises.push(
            pdf.getPage(num).then(p => this.pages.push(p)),
          );
        }
        return Promise.all(pagePromises);
      },
    },
    mounted() {
      pdfjsLib.PDFJS.workerSrc = workerSrc;
      if (this.hasPDF) this.load();
    },
  };
</script>

<style>
  .pdf-viewer {
    background: url('./assets/img/bg.gif');
    display: flex;
    flex-flow: column nowrap;
  }
</style>