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

使用jsPDF autoTable(HTML模式)时如何为PDF添加头部文本?

在autoTable生成的PDF顶部添加文本

要在PDF顶部添加文本,直接使用jsPDF内置的text()方法即可,同时需要调整autoTable的上边距避免文本与表格重叠,以下是修改后的代码:

const handleDownloadPdf = async (orientation) => {
    const report = new jsPDF({
        orientation: orientation,
        unit: "pt",
        format: "a4",
    });

    // 设置顶部文本的样式和位置
    report.setFontSize(16); // 设置字体大小
    report.setTextColor(0, 0, 0); // 设置文本颜色(黑色)
    // 在PDF顶部居中添加标题,x取页面宽度的一半,y设为40pt(距离顶部的距离)
    const pageWidth = report.internal.pageSize.getWidth();
    report.text("PDF报告标题", pageWidth / 2, 40, { align: "center" });

    // 添加副标题或其他补充文本
    report.setFontSize(12);
    report.text("生成时间:" + new Date().toLocaleString(), pageWidth / 2, 65, { align: "center" });

    // 调用autoTable时调整上边距,避免和顶部文本重叠
    report.autoTable({
        html: refExportExcel,
        margin: { top: 80, left: 15, right: 15, bottom: 15 }, // 增大上边距预留文本空间
    });

    report.save('Report.pdf');
};

关键说明:

  • report.text():第一个参数是文本内容,第二个是x坐标,第三个是y坐标,第四个参数可设置对齐方式(align: "center"/"left"/"right")。
  • 通过report.internal.pageSize.getWidth()获取页面宽度,轻松实现文本居中对齐。
  • 务必调整autoTable的margin.top值,保证表格与顶部文本之间留有足够间距,避免内容重叠。
  • 可借助setFontSize()、setTextColor()等方法自定义文本的字体大小、颜色等样式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 22:01:16