• 使用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>

  • 相关阅读:
    Qt——QGridLayout
    开启智慧之旅,AI与机器学习驱动的微服务设计模式探索
    Java 多线程基础
    elementUI踩坑记录-el-table
    实现内网穿透-netapp
    第3章 【MySQL】字符集和比较规则
    uniapp使用request下载图片,并且显示出来
    大语言模型(LLM)综述(六):大型语言模型的基准和评估
    Spring Cloud Gateway从数据库读取路由配置
    WebSocket
  • 原文地址:https://blog.csdn.net/zH1_234567/article/details/125445472