使用html-docx-js-typescript将富文本导出为

2024-04-29  本文已影响0人  时光已翩然轻擦

一、问题

二、背景

最近有个需求,将项目中原来的将富文本导出为pdf的功能改为将富文本导出为word,本以为只是换一个插件导出即可的小事情,结果在实践的时候发现导出pdf与导出word竟还有些许不同之处,就比如本文的问题:在导出pdf时,我们可以通过style来设置图片的大小,这与我们在富文本编辑器中所见的相同;然而到了导出word的时候,就会发现这些样式完全不生效,导出的图片大大小小,有些甚至因为图片过大而超出了word编辑器的界限,为了使导出的word文档看起来令人舒适/方便查看,那么图片大小一定要相对统一(这边要求让所有图片的宽度保持一致)。

三、解决方法

function getImageSize(url) {
  return new Promise(function(resolve, reject) {
    const image = new Image()
    image.src = url
    image.onload = function() {
      resolve({
        width: image.width, // 图片原宽度
        height: image.height, // 图片原高度
        scale: image.height / image.width, // 图片高度与宽度之比
        scaleWidth: 300, // 设置的缩放后的宽度为300,可根据实际需求调整
        scaleHeight: (image.height / image.width) * 300, // 计算缩放后的高度
        src: url // 图片url
      })
    }
    image.onerror = function() {
      reject(new Error('error'))
    }
  })
}
const size = await getImageSize(url)
const imgHtml = `<img src="${url}" width="${size.scaleWidth}" height="${size.scaleHeight}" />`
const imgsPromise = imgList.map(async url => {
  const size =  await getImageSize(url)
  return `<img src="${url}" width="${size.scaleWidth}" height="${size.scaleHeight}" />`
})
const imgs = await Promise.all(imgsPromise )
// 原
export function getHtml() {
  const imgHtml = <img src="xxxxxx"/>
  return `
    ……// 内容
    ${imgHtml}
    ……// 内容
  `
}

// 改后
export async function getHtml() {
  const size = await getImageSize(url)
  const imgHtml = `<img src="${url}" width="${size.scaleWidth}" height="${size.scaleHeight}" />`
  return `
    ……// 内容
    ${imgHtml}
    ……// 内容
  `
}
// 原
const html = getHtml()

// 改后
const html = await getHtml()

四、参考资料

五、本站相关内容

上一篇 下一篇

猜你喜欢

热点阅读