前端把页面用PDF导出

使用场景:

把展示的页面内容,导出PDF方便查看

主要使用的是 jspdf-html2canvas 组件

安装

javascript 复制代码
npm install jspdf-html2canvas --save   
//^1.6.0  如果使用不行,再尝试控制版本使用
//npm install jspdf-html2canvas@1.6.0 --save

使用

javascript 复制代码
import html2PDF from 'jspdf-html2canvas';

// 绑定元素
const reportNewRef = React.useRef<HTMLDivElement>(null);

//下载函数
 const testDownload = async () => {
    try {
      const dom = reportNewRef.current;
      if (!dom) {
        return;
      }

      await html2PDF(dom, {
        jsPDF: {
          format: 'a4',
          unit: 'mm',
          orientation: 'portrait',
          hotfixes: ['px_scaling'], // 解决 px 单位在高分屏上的缩放问题
        },
        html2canvas: {
          scale: 2, // 放大比例,解决高分辨率屏幕下图像模糊问题
          useCORS: true,
          logging: false,
          backgroundColor: '#fff', // 背景颜色设置为白色
          scrollX: 0,
          scrollY: 0, // 禁止纵向滚动
          windowWidth: dom.scrollWidth, // 设置为内容的实际宽度,确保完整渲染
        },
        margin: { top: 0, right: 12, bottom: 0, left: 12 },
        imageType: 'image/jpeg', // 使用 JPEG 格式,通常比 PNG 更小
        imageQuality: 1, // 设置为 1,表示最高质量的 JPEG 图片
        output: '下载文件.pdf', // 输出文件名
      });
      message.success('PDF下载成功');
    } catch (err) {
      console.error('导出失败', err);
      message.error('PDF导出失败');
    }
};





// 点击下载按钮
<Button key="download" type="primary" icon={<DownloadOutlined />}
    onClick={() => {
         //这里触发下载函数 
         testDownload()
    }}
>
 下载PDF
</Button>


//需要下载的页面
<div ref={reportNewRef}>

这里是下载内容,里面就正常写,怎么展示在页面上就怎么写。

</div>

隐藏页面来下载

主要是利用元素控制下载页面的显隐并且把下载内容定位到用户看不到的地方。

监听是否显示和页面是否存在,延时下载,考虑数据加载需要时间,这一块也可以考虑到数据请求完成,页面加载完成后,再做下载操。

javascript 复制代码
 const [open, setOpen] = useState(false);
 const reportNewRef = React.useRef<HTMLDivElement>(null);
 const testDownload = async () => {
    try {
      const dom = reportNewRef.current;
      if (!dom) {
        return;
      }

      await html2PDF(dom, {
        jsPDF: {
          format: 'a4',
          unit: 'mm',
          orientation: 'portrait',
          hotfixes: ['px_scaling'], // 解决 px 单位在高分屏上的缩放问题
        },
        html2canvas: {
          scale: 2, // 放大比例,解决高分辨率屏幕下图像模糊问题
          useCORS: true,
          logging: false,
          backgroundColor: '#fff', // 背景颜色设置为白色
          scrollX: 0,
          scrollY: 0, // 禁止纵向滚动
          windowWidth: dom.scrollWidth, // 设置为内容的实际宽度,确保完整渲染
        },
        margin: { top: 0, right: 12, bottom: 0, left: 12 },
        imageType: 'image/jpeg', // 使用 JPEG 格式,通常比 PNG 更小
        imageQuality: 1, // 设置为 1,表示最高质量的 JPEG 图片
        output: '下载文件.pdf', // 输出文件名
      });
      message.success('PDF下载成功');
    } catch (err) {
      console.error('导出失败', err);
      message.error('PDF导出失败');
    } finally {
      setOpen(false);
    }
  };

  useEffect(() => {
  let timeoutId: NodeJS.Timeout;

  if (open === true && reportNewRef.current) {
    // 清理之前的定时器
    timeoutId = setTimeout(() => {
      testDownload();
    }, 1000);
  }

  // 清理函数
  return () => {
    if (timeoutId) {
      clearTimeout(timeoutId);
    }
  };
}, [open, reportNewRef]); // 只有最后一次触发会执行


// 点击下载按钮
<Button key="download" type="primary" icon={<DownloadOutlined />}
    onClick={() => {
         //这里触发下载函数 
       setOpen(true)
    }}
>
 下载PDF
</Button>


//下载内容  通过控制元素显隐和绝对定位使其元素位置隐藏显示元素
 {open && (
   <div className="absolute top-[-200vh] w-[1000px] z-50 bg-white">
      <div>下载内容</div>
   </div>
)}
相关推荐
kyriewen9 小时前
Anthropic 估值逼近万亿美元,Claude Sonnet 5 + Claude Science 一天两连发
前端·ai编程·claude
小徐_233310 小时前
Wot UI 2.2.0 发布:Button 新增 subtle,VideoPreview 预览体验继续增强
前端·微信小程序·uni-app
天蓝色的鱼鱼12 小时前
关于 CSS 你可能不知道的属性,但关键时刻很有用
前端·css
泯泷13 小时前
第 2 篇:设计第一套字节码:Opcode、Instruction 与 Constant Pool
前端·javascript·安全
妙码生花13 小时前
从 PHP 到 AI + Golang,程序员自救转型手记(十五):优化细节、网络请求封装
前端·后端·ai编程
泯泷13 小时前
第 1 篇:从 1 + 2 开始:亲手写出第一台 JSVM
前端·javascript·安全
团团崽_七分甜13 小时前
Spring Boot 核心知识点总结
前端
lichenyang45313 小时前
从一个按钮开始,理解 ASCF 框架到底在做什么
前端
古夕14 小时前
第三方 SSO 接入实践:redirect_uri 编码、回调一致性与跨项目联调
前端·vue.js