瀏覽器通過js將局部dom生成pdf實現(xiàn):下載、打印

安裝依賴

yarn add html2canvas@1.0.0 jspdf
html2canvas建議固定為1.0.0(tip:最新版本button會出現(xiàn)文字偏下)

工具文件:

htmll-to-pdf.js:

import html2Canvas from 'html2canvas'
import JsPDF from 'jspdf'

/**
 * 獲取pdf實例對象
 * @param elementSelector
 * @returns {Promise<unknown>}
 */
const getPdfInfo = elementSelector => {
  const targetElement = typeof elementSelector === 'string' ? document.querySelector(elementSelector) : elementSelector
  if (!targetElement) {
    throw new Error('Target element not found')
  }

  return new Promise(resolve => {
    html2Canvas(targetElement, {
      allowTaint: true, // 允許跨域圖片
      scale: 2, // 提升清晰度(可選)
    })
      .then(canvas => {
        const contentWidth = canvas.width
        const contentHeight = canvas.height
        const pageHeight = (contentWidth / 592.28) * 841.89 // A4 紙比例
        let leftHeight = contentHeight
        let position = 0
        const imgWidth = 595.28 // A4 寬度
        const imgHeight = (imgWidth / contentWidth) * contentHeight
        const pageData = canvas.toDataURL('image/jpeg', 1.0)

        const pdf = new JsPDF('p', 'pt', 'a4')

        // 多頁處理
        if (leftHeight < pageHeight) {
          pdf.addImage(pageData, 'JPEG', 20, 20, imgWidth - 40, imgHeight - 40)
        } else {
          while (leftHeight > 0) {
            pdf.addImage(pageData, 'JPEG', 20, position, imgWidth - 40, imgHeight - 40)
            leftHeight -= pageHeight
            position -= 841.89 // A4 高度
            if (leftHeight > 0) pdf.addPage()
          }
        }

        resolve(pdf)
      })
      .catch(() => {})
  })
}

/**
 * 生成blob 可用來上傳
 * @param elementSelector
 * @returns {Promise<*>}
 */
export const htmlToPdfBlob = async elementSelector => {
  const pdf = await getPdfInfo(elementSelector)
  return pdf.output('blob')
}

/**
 * 生成pdf文件 下載到本地
 * @param elementSelector
 * @param fileName
 * @returns {Promise<void>}
 */
export const exportPDF = async (elementSelector, fileName = 'filename') => {
  const pdf = await getPdfInfo(elementSelector)
  pdf.save(`${fileName}.pdf`)
}

/**
 * 生成pdf文件 瀏覽器打印
 * @param elementSelector
 * @returns {Promise<void>}
 */
export const htmlToPdfPrint = async elementSelector => {
  const pdf = await getPdfInfo(elementSelector)
  pdf.autoPrint()
  window.open(pdf.output('bloburl')) // 新窗口打開
}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容