summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/pdf/index.vue
blob: c8a04eb72c4b3798d95a220eb31ce0be90208c70 (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
74
75
76
77
78
79
80
<script>
import pdfjsLib from 'pdfjs-dist/build/pdf';
import workerSrc from 'pdfjs-dist/build/pdf.worker.min';

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

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

<template>
  <div v-if="hasPDF" class="pdf-viewer">
    <page
      v-for="(page, index) in pages"
      v-if="page"
      :key="index"
      :page="page"
      :number="index + 1"
    />
  </div>
</template>

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