• 使用vue-pdf预览pdf文件


    安装 :npm install pdfjs-dist

    1. <template>
    2. <div>
    3. <el-card ref="pdf" class="file-card" shadow="never" :body-style="{ padding: '0px' }" >
    4. <canvas v-for="page in numPages" :ref="'canvas' + page" :key="page"></canvas>
    5. </el-card>
    6. </div>
    7. </template>
    8. <script>
    9. import PDFJS from 'pdfjs-dist'
    10. export default {
    11. data () {
    12. return {
    13. pdfDoc: null,
    14. numPages: 0
    15. }
    16. },
    17. methods: {
    18. renderPage (num) {
    19. this.pdfDoc.getPage(num)
    20. .then((page) => {
    21. const canvas = this.$refs['canvas' + num][0]
    22. // const canvas = document.getElementById('canvas' + num)
    23. const ctx = canvas.getContext('2d')
    24. var viewport = page.getViewport({ scale: 2 })
    25. const viewportElem = document.querySelector('meta[name=viewport]')
    26. viewportElem.setAttribute('content', 'width=device-width')
    27. canvas.width = viewport.width // 画布大小,默认值是width:300px,height:150px
    28. canvas.height = viewport.height
    29. canvas.style.width = '100%' // 画布的框架大小
    30. const renderContext = {
    31. canvasContext: ctx,
    32. viewport: viewport
    33. }
    34. page.render(renderContext)
    35. if (this.numPages > num) {
    36. this.renderPage(num + 1)
    37. }
    38. })
    39. }
    40. },
    41. created () {
    42. const that = this
    43. PDFJS.disableWorker = true
    44. PDFJS.GlobalWorkerOptions.workerSrc = '/js/pdf.worker.js'
    45. PDFJS.getDocument({
    46. url: '地址',
    47. cMapUrl: 'https://unpkg.com/pdfjs-dist@2.0.943/cmaps/',
    48. cMapPacked: true
    49. }).promise.then((pdf) => {
    50. this.pdfDoc = pdf
    51. this.numPages = this.pdfDoc.numPages
    52. that.$nextTick(() => {
    53. that.loading = false
    54. that.renderPage(1)
    55. })
    56. })
    57. }
    58. }
    59. </script>
    60. <style lang="scss" scoped>
    61. .file-card{
    62. border: none;
    63. width:100%;
    64. height: 100%;
    65. overflow:auto;
    66. }
    67. </style>

  • 相关阅读:
    C++:C++模板(函数模板与类模板的使用)
    (多级缓存)缓存同步
    cpu常用命令
    mybatis plus in使用时传数组、集合的注意点
    动手写数据库:实现记录管理
    Jmeter响应时间和tps监听器使用教程
    【ROS入门】实现参数服务器参数的增删改查操作
    初识 WebSocket
    谷贱伤农,薪贱伤码农!
    1 快速了解Paimon数据湖核心原理及架构
  • 原文地址:https://blog.csdn.net/zH1_234567/article/details/125445472