You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

HTML导出PDF时含文本图片不显示的问题及修复方案

问题修复:HTML导出PDF时图片无法显示的解决方法

导出HTML内容为PDF文件时,文本数据可正常导出,但添加含文本的图片后,图片无法在下载的PDF中显示。以下是修复后的完整实现代码,可确保图片像在UI中一样正常显示:

export default function BasicTextFields() {
  const exportToPdf = (name, div) => {
    const input = document.getElementById(div);
    html2canvas(input).then((canvas) => {
      // 创建新的PDF画布
      const imgData = canvas.toDataURL("image/jpeg");
      const pdf = new JsPDF("p", "pt", [canvas.width, canvas.height]);
      // 获取PDF文件自身的尺寸
      const imgProps = pdf.getImageProperties(imgData);
      const width = pdf.internal.pageSize.getWidth();
      const height = (imgProps.height * width) / imgProps.width;
      // 转换PDF并保存文件
      pdf.addImage(imgData, "JPEG", 0, 0, width, height);
      pdf.save(`${name}.pdf`); // 下载渲染后的PDF
    });
  };
  return (
    <Grid
      container
      rowSpacing={4}
      component="div"
      id="exportTofile"
    >
      <Grid item xs={12}>
        <Box display="flex" alignItems="center">
          <Box flexGrow={1}>
            <Typography variant="h3"> Dashboard</Typography>
          </Box>
          <Box display="flex" gap={2}>
            <Button
              variant="contained"
              color="primary"
              title="Download"
              onClick={() => {
                exportToPdf("exportToPdf", "exportTofile");
              }}
            >
              DOWNLOAD
            </Button>
          </Box>
        </Box>
      </Grid>
      <Grid item xs={12}>
        <Typography variant="h4">First summery</Typography>
        <Box mt={2}>
          <Typography variant="subtitle2">
            <Box
              dangerouslySetInnerHTML={{
                __html: commentData
              }}
            />
          </Typography>
        </Box>
      </Grid>
      <Grid item xs={12}>
        <Typography variant="h4">Second summery</Typography>
        <Box mt={2}>
          <Box>
            <Typography variant="subtitle2">
              <Box
                dangerouslySetInnerHTML={{
                  __html:
                    "<p><strong>Lorem Ipsum</strong> is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.</p>\n"
                }}
              />
            </Typography>
          </Box>
        </Box>
      </Grid>
    </Grid>
  );
}

修复逻辑

核心是通过html2canvas将目标DOM元素(包含其中的图片)完整渲染为Canvas,再将Canvas转换为图片数据后嵌入PDF,确保所有视觉内容(包括带文本的图片)都能被精准捕获并导出。

内容的提问来源于stack exchange,提问作者dev john

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 09:24:58