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

如何使用jsPDF打印div?执行代码后仅显示空白页求助

jsPDF导出div空白?看这两个修复方案

你的代码问题出在这两点:

  • 错把pdf.text当属性赋值了——它是个方法,而且只能添加纯文本,根本解析不了HTML
  • jsPDF本身没法直接把HTML元素的innerHTML转成PDF内容,得用专门的渲染方式

下面给两种可行的解决办法:

方法1:用新版jsPDF的html()方法(推荐)

新版jsPDF(2.0+)自带HTML渲染功能,不用额外装插件,直接写就行:

downloadPDF() {
  const pdf = new jsPDF('p', 'mm', 'a4'); // 纵向、毫米单位、A4尺寸,可按需调整
  pdf.html(document.getElementById('resume'), {
    callback: (pdf) => {
      pdf.save('info.pdf');
    },
    x: 10, // 内容在PDF里的X起始坐标
    y: 10  // Y起始坐标
  });
}

方法2:配合html2canvas转Canvas再导出(兼容旧版)

如果你的jsPDF版本比较老,就用html2canvas先把div转成图片,再塞进PDF里:

先确保页面引入了html2canvas,然后改代码:

downloadPDF() {
  const resumeDiv = document.getElementById('resume');
  html2canvas(resumeDiv).then(canvas => {
    const imgData = canvas.toDataURL('image/png');
    const pdf = new jsPDF('p', 'mm', 'a4');
    const imgWidth = 210; // A4宽度(毫米)
    const pageHeight = 297; // A4高度
    const imgHeight = canvas.height * imgWidth / canvas.width;
    let remainingHeight = imgHeight;
    let yPos = 0;

    // 第一页
    pdf.addImage(imgData, 'PNG', 0, yPos, imgWidth, imgHeight);
    remainingHeight -= pageHeight;

    // 内容太长就加新页
    while (remainingHeight >= 0) {
      yPos = remainingHeight - imgHeight;
      pdf.addPage();
      pdf.addImage(imgData, 'PNG', 0, yPos, imgWidth, imgHeight);
      remainingHeight -= pageHeight;
    }

    pdf.save('info.pdf');
  });
}

额外注意

  • 要保证#resume元素是显示状态(别用display: none),不然抓不到内容
  • 用方法1的话,必须升级到jsPDF 2.0以上版本,旧版没有html()方法
  • 如果导出后样式乱了,检查下div里的CSS——太复杂的动画、渐变可能转不成PDF,尽量用基础样式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 18:40:31