当前位置: 首页 > article >正文

记录:页面下载为png和pdf

记录贴,要下载为png和pdf的页面比较简单,只有文字,所以没遇到什么坑

下载为png

使用html2canvas
官网:https://html2canvas.hertzen.com/

npm i html2canvas

 import html2canvas from 'html2canvas';
 
 async function saveAsImage() {
    try {
      const bodyEl: HTMLElement = document.querySelector(
        '.body',
      ) as HTMLElement;

      const canvas = await html2canvas(bodyEl, {
        useCORS: true,
        scale: 2, // 提高渲染质量
      });
      fetch(canvas.toDataURL('image/png'))
        .then((response) => response.blob())
        .then((blob) => {
          // 创建一个 Blob URL
          const url = window.URL.createObjectURL(new Blob([blob]));
          // 创建一个隐藏的可下载链接
          const a = document.createElement('a');
          a.href = url;
          a.download = 'test.png';
          // 触发点击
          a.click();
          // 清理 URL
          setTimeout(() => {
            window.URL.revokeObjectURL(url);
            a.remove();
          }, 100); // 等待下载完成
        })
        .catch(console.error);
    } catch (error) {
      console.error('Error capturing the page:', error);
    }
  }

下载为pdf

使用html2pdf
文档:https://github.com/eKoopmans/html2pdf.js#options

npm install --save html2pdf.js

 import html2pdf from 'html2pdf.js';
 function savePdf() {
    const bodyEl: HTMLElement = document.querySelector(
      '.body',
    ) as HTMLElement;
    html2pdf()
      .set({
        pagebreak: { mode: ['avoid-all'] },
        html2canvas: {
          scale: 2,
          useCORS: true,
        },
      })
      .from(bodyEl)
      .save('test.pdf')
  }

http://www.kler.cn/a/571744.html

相关文章:

  • 【考研说】2025年研考上岸复试指南(地理学/测绘/遥感等)
  • 【零基础到精通Java合集】第十五集:Map集合框架与泛型
  • YK人工智能(九)——大语言模型微调介绍
  • 3D手眼标定转换详细实施步骤及原理概述
  • 【第13节】C++设计模式(行为模式)-Template(模板)模式
  • CogVLM: Visual Expert for Pretrained Language Models 简读
  • AI 大模型本身的(自己的)(如 GPT、BERT 等)的自动化测试
  • 我的AI工具箱Tauri版-通用音频转文本
  • JavaWeb后端基础(4)
  • Rust~String、str、str、String、Box<str> 或 Box<str>
  • FastGPT 引申:常见 Rerank 实现方案
  • 知识篇 | 低代码开发(Low-Code Development)是个什么东东?
  • 第40天:安全开发-JavaEE应用SpringBoot框架JWT身份鉴权打包部署JARWAR
  • Stiring-PDF:开源免费的PDF文件处理软件
  • Vue路由器的工作模式
  • PPT 小黑第34套
  • Metal学习笔记目录
  • DFT之SSN架构
  • 备赛蓝桥杯之第十五届职业院校组省赛第五题:悠然画境
  • 医疗AR眼镜:FPC如何赋能科技医疗的未来之眼?【新立电子】