PDF.js 转 canvas 页面不平铺的问题?

使用PDF.js 转成canvas放到页面上不会平铺
目前效果是:
image.png

期望实现的效果:
image.png
请问各位社区大佬应该怎么去解决?

function renderPage(num: number) {
  pdfDoc.getPage(num).then((page: any) => {
    const canvas: any = document.getElementById(`pdfSource${num}`)
    const ctx = canvas.getContext('2d')
    const dpr = window.devicePixelRatio || 1
    const bsr =
      ctx.webkitBackingStorePixelRatio ||
      ctx.mozBackingStorePixelRatio ||
      ctx.msBackingStorePixelRatio ||
      ctx.oBackingStorePixelRatio ||
      ctx.backingStorePixelRatio ||
      1
    const ratio = dpr / bsr
    const viewport = page.getViewport({ scale: state.pdfScale })
    canvas.width = viewport.width
    canvas.height = viewport.height
    state.pdfWidth = `${viewport.width}px`
    ctx.setTransform(ratio, 0, 0, ratio, 0, 0)
    // 将 PDF 页面渲染到 canvas 上下文中
    const renderContext = {
      canvasContext: ctx,
      viewport
    }
    page.render(renderContext)
  })
}

目前代码是这样的缩放倍率为1

  • pdf.js的版本是3.2.146
  • vue3+ts+vite
阅读 1.1k
1 个回答

在创建时 给canvas一个固定宽,渲染后再为这个canvas设置样式width:100%即可解决。

function createTargeCanvas(num) {
  let targetContainer = document.getElementById('target')
  let canvas = document.createElement('canvas')
  canvas.id = 'target' + num
  canvas.width = 770
  targetContainer?.appendChild(canvas)
}
function loadFileTarget(url: string) {
  PDF.getDocument(url).promise.then((p: any) => {
    pdfDoc = p
    const { numPages } = p
    state.pdfPages = numPages
    targetTotal.value = numPages
    CreateCanvasTarget(state.pdfPages)
    for (let i = 1; i <= state.pdfPages; i++) {
      let canvas = document.getElementById(`target${i}`)
      canvas!.style.width = '100%'
    }
    for (let i = 1; i <= state.pdfPages; i++) {
      renderPageTarget(i)
    }
  })
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题