前端生成docx文档、excel表格、图片、pdf文件

发布于:2024-12-22 ⋅ 阅读:(10) ⋅ 点赞:(0)
一、前端将页面某区域内容下载为word文档:html-to-docx、file-saver插件组合使用
import HTMLtoDOCX from 'html-to-docx';
import { saveAs } from 'file-saver';

const exportTest = async () => {
    const fileBuffer = await HTMLtoDOCX(
      `<h2>文件标题</h2><br>文件内容222`,
      null,
      {
        table: { row: { cantSplit: true } },
        footer: true,
        pageNumber: true,
        font: '-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji',
      },
    );
    saveAs(fileBuffer, `测试下载文件.docx`);
  }
二、前端将数据导出成excel表格:XLSX插件
import * as XLSX from 'xlsx';

const downloadExcel = () => {
    const tableRows = [{‘表头1’:‘111’, ‘name’: 'zhangsan '}]
    const sheet = XLSX.utils.json_to_sheet(tableRows); //此处为表格的数据
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, sheet);
    XLSX.writeFile(wb, `${date.getTime()}.xlsx`);
  };
三、页面区域导出为图片:html2canvas插件
import html2canvas from 'html2canvas';
import { useEffect, useRef } from 'react';


export const TestPage = () => {
const testRef = useRef(null);

const html2image = (url: any, fileName: any) => {
  // 创建一个虚拟的a标签
  let link = document.createElement('a');
  link.href = url;
  link.download = fileName;
  document.body.appendChild(link);
  // 触发点击事件进行下载
  link.click();
  // 下载完成后删除a标签
  setTimeout(function () {
    document.body.removeChild(link);
  }, 100);
};

const downloadImg = () => {
    const dom = testRef.current;
    html2canvas(dom, {
      useCORS: true,
      allowTaint: true,
    }).then((canvas: any) => {
      const url = canvas.toDataURL('image/png');
      html2image(url, new Date().getTime().toString());
    });
  };

return (
    <>
        <div onClick={() =>{downloadImg ()}}>导出</div>
        <div ref={testRef}>需要导出的页面区域</div>
    </>
)
}


四、前端导出为pdf文件:jsPDF 
import jsPDF from 'jspdf';
const htmlStringToPdf = async (dom: HTMLElement, name: string) => {
  html2canvas(dom, {
    scale: 1,
    y: -10,
  }).then((canvas: any) => {
    const imgWidth = 200;
    const pageHeight = 300;
    const imgHeight = (canvas.height * imgWidth) / canvas.width;
    let heightLeft = imgHeight;
    let position = 0;
    heightLeft -= pageHeight;
    const doc = new jsPDF('p', 'mm', 'a4');
    doc.addImage(canvas, 'PNG', 0, position, imgWidth, imgHeight, '', 'FAST');
    while (heightLeft >= 0) {
      position = heightLeft - imgHeight;
      doc.addPage();
      doc.addImage(canvas, 'PNG', 0, position, imgWidth, imgHeight, '', 'FAST');
      heightLeft -= pageHeight;
    }
    doc.save(`${name}.pdf`);
  });
};