summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/pdf/index.vue
blob: 7b079fe02d90c77b8507ac0d7e7556d81584c8fa (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
<script>
import pdfjsLib from 'vendor/pdf';
import workerSrc from 'vendor/pdf.worker.min';

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

export default {
  components: { page },
  props: {
    pdf: {
      type: [String, Uint8Array],
      required: true,
    },
  },
  data() {
    return {
      loading: false,
      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.PDFJS.workerSrc = workerSrc;
    if (this.hasPDF) this.load();
  },
  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);
    },
  },
};
</script>

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

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