首页 > 其他分享 >批量导出多个页面为pdf文件

批量导出多个页面为pdf文件

时间:2023-11-15 16:13:43浏览次数:29  
标签:useRef code const menu 导出 return import pdf 页面

添加多个页面组件ref,每个页面组件加一个回调函数来判断此页面数据是否已经加载完毕,加载完毕所有页面后执行导出

import React, { useContext, useEffect, useRef, useState } from 'react';
import styles from './index.less';
import context from '@/layouts/context';
import { DownloadOutlined } from '@ant-design/icons';
import CurrencyTable from './components/currencyTable';
import DistributionTable from './components/distributionTable';
import ChartTwo from './components/chartTwo';
import ChartOne from './components/chartOne';
import BranchTable from './components/branchTable';
import GeneralTable from './components/generalTable';
import CreditorTable from './components/creditorTable';
import DepositedFunds from './components/depositedFunds';
import SecurityOne from './components/securityOne';
import Security from './components/security';
import SecurityTableOne from './components/securityTableOne';
import SecurityTableTwo from './components/securityTableTwo';
import SecurityTableThree from './components/securityTableThree';
import SecurityTableFour from './components/securityTableFour';
import icon from '@/assets/font/iconfont.css';
import { Checkbox, Button, Form, Popover, Spin } from 'antd';
import { plainOptions } from './vieModal';
import useCompToPDF from '@/hooks/use-pdf-hooks/usePDFHooks';
import whiteTheme from '@/themes/whiteTheme';

const IndexPage: React.FC<{ location: any }> = (props) => {
  const [form] = Form.useForm();
  const { indexInfo } = useContext(context);
  const [menu, setMenu] = useState<any[]>([]);
  const [currentIndex, setCurrentIndex] = useState(0); //导出弹窗的切换【pdf与excl之间的切换】
  const [divList, setDivList] = useState<any>([]); //动态添加的div
  const activeExportRef = useRef<any>([]);
  // 是否显示加载中的图标
  const [load, setLoad] = useState<boolean>(false);
  const [exportPDfName, setExportPDfName] = useState<string>('批量导出');
  const [openPopver, setOpenPopver] = useState<boolean>(false); //控制导出弹窗
  const [activeMenu, setActiveMenu] = useState({
    title: '有息债务',
    code: 'gfgs_cwzb_yxzw_item06',
  });
  const { exportPDf } = useCompToPDF({ fileName: exportPDfName });
  const yxzwRef = useRef<any>(); //有息债务
  const dbsxRef = useRef<any>(); //担保授信
  const fbbRef = useRef<any>(); //分布表
  const qxbzjgbRef = useRef<any>(); //期限币种结构表
  const zqrjgbRef = useRef<any>(); //债权人结构表
  const zbyxzwbdqkbRef = useRef<any>(); //总部有息债务变动情况表
  const fgsRef = useRef<any>(); //分公司合并报表单位债务变动情况表
  const scjeRef = useRef<any>(); //上存资金与负息资金明细表
  const dbt1Ref = useRef<any>(); //担保图1
  const dbt2Ref = useRef<any>(); //担保图2
  const fxb1Ref = useRef<any>(); //分析表1
  const fxb2Ref = useRef<any>(); //分析表2
  const fxb3Ref = useRef<any>(); //分析表3
  const fxb4Ref = useRef<any>(); //分析表4
  const ref1 = useRef<any>();
  let refGroup = {
    yxzwRef,
    dbsxRef,
    fbbRef,
    qxbzjgbRef,
    zqrjgbRef,
    zbyxzwbdqkbRef,
    fgsRef,
    scjeRef,
    dbt1Ref,
    dbt2Ref,
    fxb1Ref,
    fxb2Ref,
    fxb3Ref,
    fxb4Ref,
  };
  let callBackIdsRef = useRef<any>([]); //担保授信
  const [allowExport, setAllowExport] = useState<boolean>(false); //选中的导出页面是否加载完毕,加载完毕后调用导出pdf方法
  useEffect(() => {
    if (indexInfo && indexInfo.children) {
      //获取菜单信息
      let menuData: any[] = [];
      indexInfo.children.forEach((item: any) => {
        menuData.push({
          title: item.title,
          code: item.code,
        });
      });
      setMenu(menuData);
    }
  }, [indexInfo]);

  //新div加载完回调函数
  const useCallBackExport = (id: string) => {
    callBackIdsRef.current = [...callBackIdsRef.current, id];
    if (callBackIdsRef.current.length === activeExportRef.current.length) {
      // 图的页面如果只导出一个,导出的标题是这个页面的名字,导出多个显示批量导出
      if (activeExportRef.current.length > 1) {
        setExportPDfName('批量导出');
      } else {
        if (id === 'yxzwRef') {
          setExportPDfName('有息债务');
        } else if (id === 'dbsxRef') {
          setExportPDfName('担保授信');
        } else if (id === 'dbt1Ref') {
          setExportPDfName('担保图1');
        } else if (id === 'dbt2Ref') {
          setExportPDfName('担保图2');
        }
      }
      //页面全部返回加载完毕信息
      setAllowExport(true);
    }
  };
  //批量导出pdf点击确定事件
  const sumbitArticle = (nameGroup: string[]) => {
    if (!nameGroup) {
      return;
    }
    activeExportRef.current = nameGroup;
    callBackIdsRef.current = [];
    let newDiv = nameGroup.map((item: string, index: number) => {
      return getBottomContentView({ title: '', code: '' }, item);
    });
    setLoad(true); //添加loading
    setDivList(newDiv);
  };

  //允许导出
  useEffect(() => {
    if (divList.length > 0) {
      let dataParam: any[] = [];
      activeExportRef.current.forEach((item: string) => {
        let isTable = true;
        if (
          item === 'yxzwRef' ||
          item === 'dbsxRef' ||
          item === 'dbt1Ref' ||
          item === 'dbt2Ref'
        ) {
          isTable = false;
        }
        if (!isTable) {
          dataParam.push({ ref: (refGroup as any)[item].current });
        }
      });
      setLoad(false); //loading结束
      if (dataParam.length > 0) {
        exportPDf(dataParam);
      }

      form.resetFields(); //清空选中数据
      setOpenPopver(false); //关闭弹窗
      //清空
      callBackIdsRef.current = [];
      activeExportRef.current = [];
      setAllowExport(false);
      setDivList([]);
    }
  }, [allowExport]);

  // 获取具体页面
  const getBottomContentView = (
    menu: { title: string; code: string },
    exportId?: string,
  ) => {
    if (menu.code === 'gfgs_cwzb_yxzw_item01' || exportId === 'fbbRef') {
      //分布表
      return (
        <div ref={fbbRef} className={styles.charts}>
          <DistributionTable
            exportId={exportId ?? undefined}
            useCallBackExport={useCallBackExport}
          />
        </div>
      );
    } else if (
      menu.code === 'gfgs_cwzb_yxzw_item02' ||
      exportId === 'qxbzjgbRef'
    ) {
      //币种结构表
      return (
        <div ref={qxbzjgbRef} className={styles.charts}>
          <CurrencyTable
            exportId={exportId ?? undefined}
            useCallBackExport={useCallBackExport}
          />
        </div>
      );
    } else if (
      menu.code === 'gfgs_cwzb_yxzw_item03' ||
      exportId === 'zqrjgbRef'
    ) {
      //债权人结构表
      return (
        <div ref={zqrjgbRef} className={styles.charts}>
          <CreditorTable
            useCallBackExport={useCallBackExport}
            exportId={exportId ?? undefined}
          />
        </div>
      );
    } else if (
      menu.code === 'gfgs_cwzb_yxzw_item04' ||
      exportId === 'zbyxzwbdqkbRef'
    ) {
      //总部有息债务变动情况表
      return (
        <div ref={zbyxzwbdqkbRef} className={styles.charts}>
          <GeneralTable
            useCallBackExport={useCallBackExport}
            exportId={exportId ?? undefined}
          />
        </div>
      );
    } else if (menu.code === 'gfgs_cwzb_yxzw_item05' || exportId === 'fgsRef') {
      //分公司合并报表单位债务变动情况表
      return (
        <div ref={fgsRef} className={styles.charts}>
          <BranchTable
            useCallBackExport={useCallBackExport}
            exportId={exportId ?? undefined}
          />
        </div>
      );
    } else if (
      menu.code === 'gfgs_cwzb_yxzw_item06' ||
      exportId === 'yxzwRef'
    ) {
      //图形名称1

      return (
        <div
          ref={yxzwRef}
          className={styles.charts}
          id={exportId ? 'exportCharts' : 'charts'}
        >
          <ChartOne
            useCallBackExport={useCallBackExport}
            exportId={exportId ?? undefined}
          />
        </div>
      );
    } else if (
      menu.code === 'gfgs_cwzb_yxzw_item07' ||
      exportId === 'dbsxRef'
    ) {
      //图形名称2
      return (
        // 导出的数据
        <div
          ref={dbsxRef}
          className={styles.charts}
          id={exportId ? 'exportCharts2' : 'charts'}
        >
          <ChartTwo
            useCallBackExport={useCallBackExport}
            exportId={exportId ?? undefined}
          />
        </div>
      );
    } else if (
      menu.code === 'gfgs_cwzb_yxzw_item08' ||
      exportId === 'scjeRef'
    ) {
      //上存资金与负息资金明细表
      return (
        <div ref={scjeRef} className={styles.charts}>
          <DepositedFunds
            useCallBackExport={useCallBackExport}
            exportId={exportId ?? undefined}
          />
        </div>
      );
    } else if (
      menu.code === 'gfgs_cwzb_yxzw_item09' ||
      exportId === 'dbt1Ref'
    ) {
      //担保图1
      return (
        <div
          ref={dbt1Ref}
          className={styles.charts}
          id={exportId ? 'exportCharts3' : ''}
        >
          <SecurityOne
            useCallBackExport={useCallBackExport}
            exportId={exportId ?? undefined}
          />
        </div>
      );
    } else if (
      menu.code === 'gfgs_cwzb_yxzw_item10' ||
      exportId === 'dbt2Ref'
    ) {
      //担保图2
      return (
        <div
          ref={dbt2Ref}
          className={styles.charts}
          id={exportId ? 'exportCharts4' : 'charts'}
        >
          <Security
            useCallBackExport={useCallBackExport}
            exportId={exportId ?? undefined}
          />
        </div>
      );
    } else if (
      menu.code === 'gfgs_cwzb_yxzw_item11' ||
      exportId === 'fxb1Ref'
    ) {
      //担保种类分析表1
      return (
        <div ref={fxb1Ref} className={styles.charts}>
          <SecurityTableOne
            useCallBackExport={useCallBackExport}
            exportId={exportId ?? undefined}
          />
        </div>
      );
    } else if (
      menu.code === 'gfgs_cwzb_yxzw_item12' ||
      exportId === 'fxb2Ref'
    ) {
      //担保方式分析表2
      return (
        <div ref={fxb2Ref} className={styles.charts}>
          <SecurityTableTwo
            useCallBackExport={useCallBackExport}
            exportId={exportId ?? undefined}
          />
        </div>
      );
    } else if (
      menu.code === 'gfgs_cwzb_yxzw_item13' ||
      exportId === 'fxb3Ref'
    ) {
      //担保期限分析表3
      return (
        <div ref={fxb3Ref} className={styles.charts}>
          <SecurityTableThree
            useCallBackExport={useCallBackExport}
            exportId={exportId ?? undefined}
          />
        </div>
      );
    } else if (
      menu.code === 'gfgs_cwzb_yxzw_item14' ||
      exportId === 'fxb4Ref'
    ) {
      //担保期限分析表4
      return (
        <div ref={fxb4Ref} className={styles.charts}>
          <SecurityTableFour
            useCallBackExport={useCallBackExport}
            exportId={exportId ?? undefined}
          />
        </div>
      );
    }
  };
// 表单提交时
  const onFinish = (values: any) => {
    sumbitArticle(values.checkbox_group); //调用方法获取子组件的dom结构
  };
  // 表单点击取消时
  const onReset = () => {
    form.resetFields();
    setOpenPopver(false); //关闭弹窗
  };
  // 一键导出弹窗内容

  const content = () => {
    return (
      <div className={styles.exportBody}>
        {load && (
          <div className={styles.spin}>
            <Spin size="large" />
          </div>
        )}

        <div className={styles.tabBody}>
          <div>
            <Form form={form} name="control-hooks" onFinish={onFinish}>
              <Form.Item name="checkbox_group">
                <Checkbox.Group>
                  {plainOptions[0].map((data: any) => {
                    return (
                      <Checkbox value={data.value} disabled={data.disabled}>
                        {data.label}
                      </Checkbox>
                    );
                  })}
                </Checkbox.Group>
              </Form.Item>
              <div className={styles.bottomButton}>
                <Button
                  className={styles.okButton}
                  type="primary"
                  htmlType="submit"
                >
                  确定
                </Button>
                <Button
                  className={styles.okButton}
                  htmlType="button"
                  onClick={onReset}
                >
                  取消
                </Button>
              </div>
            </Form>
          </div>
        </div>
      </div>
    );
  };

  const handleOpenChange = (newOpen: boolean) => {
    setOpenPopver(newOpen);
  };
  return (
    <div className={styles.container}>
      <div className={styles.menu}>
        {/* 导出按钮 */}
        <div className={styles.exportButton}>
          <Popover
            content={content}
            trigger="click"
            open={openPopver}
            overlayClassName={styles.popstyle}
            onOpenChange={handleOpenChange}
          >
            <div className={styles.button}>
              <DownloadOutlined twoToneColor="#eb2f96" />
              &nbsp; 一键导出
            </div>
          </Popover>
        
        </div>
      </div>

      <div className={styles.content} ref={ref1}>
        {activeMenu && getBottomContentView(activeMenu)}
        {divList}
      </div>
    </div>
  );
};

export default IndexPage;

导出组件

import html2canvas from 'html2canvas';
import jsPDF from 'jspdf';

interface CompToPDFProps {
  fileName: string;
}
const PDFFile = {
  A4: [592.28, 841.89],
};

//自定义的hooks函数
/**
 *
 * @param props
 * @param isTable 是否是导出表格
 * @returns
 */
const useCompToPDF = (props: CompToPDFProps) => {
  const { fileName } = props;
  const exportPDf = (elementAll: any[]) => {
    if (elementAll) {
      let pdf = new jsPDF('l', 'pt', PDFFile.A4); //方向p竖直 l横向,尺寸ponits,格式a4
      let promises: any = [];
      elementAll.forEach((element: any) => {
        var promise = html2canvas(element.ref, {
          scrollX: -window.scrollX, // 设置滚动的水平位置
          scrollY: -window.scrollY, // 设置滚动的垂直位置
        });
        promises.push(promise);
      });
      Promise.all(promises).then((canvases) => {
        canvases.forEach((canvas, index: number) => {
          //获取画布的宽高
          let canvasWidth = canvas.width;
          let canvasHeight = canvas.height;
          //一页PDF显示html生成的canvas高度
          let pdfPageHeight = (PDFFile.A4[1] / PDFFile.A4[0]) * canvasWidth;
          //未生成pdf的html页面内高度
          let pdfAllHeight = canvasHeight;
          let position = 0; //页面偏移
          //转换图片为dataURL,参数:图片格式和清晰度(0-1)
          let pageData: any;
          let blackWhiteCanvas = document.createElement('canvas');
          let bwContext = blackWhiteCanvas.getContext('2d');
          blackWhiteCanvas.width = canvasWidth;
          blackWhiteCanvas.height = canvasHeight;
          // 将原始彩色图像绘制到黑白Canvas上
          if (bwContext) {
            // 将原始彩色图像绘制到黑白Canvas上
            bwContext.drawImage(canvas, 0, 0, canvasWidth, canvasHeight);
            /// 获取黑白图像的图像数据
            let imageData = bwContext.getImageData(
              0,
              0,
              canvasWidth,
              canvasHeight,
            );
            let data = imageData.data;
            //图片整体替换彩色替换成黑白色
            // 定义待替换的颜色数组
            const targetColors = [[20, 62, 961]];

            // 定义目标颜色数组,与 targetColors 数组一一对应
            const replaceColors = [[0, 0, 0]];

            // 遍历每个像素
            for (let i = 0; i < data.length; i += 4) {
              const r = data[i];
              const g = data[i + 1];
              const b = data[i + 2];
              let avg = (r + g + b) / 3;
              data[i] = avg; // R
              data[i + 1] = avg; // G
              data[i + 2] = avg; // B
              // 检查像素颜色是否与待替换的颜色匹配
              for (let j = 0; j < targetColors.length; j++) {
                const targetColor = targetColors[j];
                const replaceColor = replaceColors[j];
                if (
                  r === targetColor[0] &&
                  g === targetColor[1] &&
                  b === targetColor[2]
                ) {
                  // 将颜色修改为目标颜色
                  data[i] = replaceColor[0];
                  data[i + 1] = replaceColor[1];
                  data[i + 2] = replaceColor[2];
                  // 不修改透明度,不修改 data[i + 3]
                  break;
                }
              }
            }

            // 将处理后的黑白图像数据重新绘制到黑白Canvas上
            bwContext.putImageData(imageData, 0, 0);
            // 转换为黑白图像的dataURL
            pageData = blackWhiteCanvas.toDataURL('image/jpeg', 1.0);
          } else {
            pageData = canvas.toDataURL('image/jpeg', 1.0);
          }
          //html页面生成的canvas在pdf中图片的宽高
          let imgWidth = PDFFile.A4[0] - 60; //减去边距宽度
          let imgHeight = (canvasHeight / canvasWidth) * PDFFile.A4[0];
          //当内容未超过pdf一页显示的范围,无需分页
          if (pdfAllHeight < pdfPageHeight && index === 0) {
            // 从图片顶部开始打印   30 左右边距, 0 上下边距
            pdf.addImage(
              pageData,
              'jpeg',
              30,
              30,
              imgWidth * 1.48,
              imgHeight * 1.48,
            );
          } else {
            if (index !== 0) {
              pdf.addPage();
            }
            while (pdfAllHeight > 0) {
              pdf.addImage(
                pageData,
                'jpeg',
                30,
                30,
                imgWidth * 1.48,
                imgHeight * 1.48,
              );
              pdfAllHeight -= pdfPageHeight;
              position -= PDFFile.A4[1];
              //避免添加空白页
              if (pdfAllHeight > 0) {
                pdf.addPage();
              }
            }
          }
        });
        pdf.save(`${fileName}.pdf`);
      });
    }
  };
  return {
    exportPDf,
  };
};

export default useCompToPDF;

组件页面需要加回调函数并把页面置成黑白

/*
 * @Author: gxx
 * @Date: 2023-03-15 15:41:03
 * @LastEditors: jld
 * @LastEditTime: 2023-11-02 17:35:57
 * @FilePath: \business-analysis-report-stock\src\pages\GFGS\gfgs_cwzb\debt\components\chartOne\index.tsx
 * @Description: 文件描述
 */
import {
  forwardRef,
  useContext,
  useEffect,
  useImperativeHandle,
  useRef,
  useState,
} from 'react';
import PandectCard from './components/pandectCard';
import styles from './index.less';
import context from '@/layouts/context';
import { getPandectInfo } from './viewModal';
import whiteTheme from '@/themes/whiteTheme';

const ChartOne: React.FC<{
  useCallBackExport?: (id: string) => void;
  exportId?: string | undefined;
}> = (props) => {
  const { instDate } = useContext(context);
  const { useCallBackExport, exportId } = props;
//如果有exportId证明是要导出功能的操作,需要先把页面置成黑白
if (exportId) { let themeStyle1 = whiteTheme; themeStyle1.forEach((item, index) => { const myDiv = document.getElementById('exportCharts'); if (myDiv) { myDiv.style.setProperty(item.property, item.value); } }); } const [pandectInfo, setPandectInfo] = useState<any>([]); // 点击同比环比按钮切换 const [switchButton, setSwitchButton] = useState('QOQ'); useEffect(() => { //获取数据 const getData = async () => {
//接口数据 let pandectInfoTemp = await getPandectInfo( instDate ); setPandectInfo(pandectInfoTemp);
数据加载完之后调用回调函数返回这个页面的id if (useCallBackExport && exportId) { setTimeout(() => { useCallBackExport('yxzwRef');//调用导出的回调函数 }, 500); } }; getData(); }, [instDate, switchButton]); return ( <div className={styles.box}> 内容 </div> ); }; export default ChartOne;

 

/*  * @Author: gxx  * @Date: 2023-03-15 14:49:49  * @LastEditors: jld  * @LastEditTime: 2023-11-02 18:02:35  * @FilePath: \business-analysis-report-stock\src\pages\GFGS\gfgs_cwzb\debt\index.tsx  * @Description: 文件描述  */
import React, { useContext, useEffect, useRef, useState } from 'react'; import styles from './index.less'; import context from '@/layouts/context'; import { DownloadOutlined } from '@ant-design/icons'; import CurrencyTable from './components/currencyTable'; import DistributionTable from './components/distributionTable'; import ChartTwo from './components/chartTwo'; import ChartOne from './components/chartOne'; import BranchTable from './components/branchTable'; import GeneralTable from './components/generalTable'; import CreditorTable from './components/creditorTable'; import DepositedFunds from './components/depositedFunds'; import SecurityOne from './components/securityOne'; import Security from './components/security'; import SecurityTableOne from './components/securityTableOne'; import SecurityTableTwo from './components/securityTableTwo'; import SecurityTableThree from './components/securityTableThree'; import SecurityTableFour from './components/securityTableFour'; import icon from '@/assets/font/iconfont.css'; import { Checkbox, Button, Form, Popover, Spin } from 'antd'; import { plainOptions } from './vieModal'; import useCompToPDF from '@/hooks/use-pdf-hooks/usePDFHooks'; import whiteTheme from '@/themes/whiteTheme';
const IndexPage: React.FC<{ location: any }> = (props) => {   const [form] = Form.useForm();   const { indexInfo } = useContext(context);   const [menu, setMenu] = useState<any[]>([]);   const [currentIndex, setCurrentIndex] = useState(0); //导出弹窗的切换【pdf与excl之间的切换】   const [divList, setDivList] = useState<any>([]); //动态添加的div   const activeExportRef = useRef<any>([]);   // 是否显示加载中的图标   const [load, setLoad] = useState<boolean>(false);   const [exportPDfName, setExportPDfName] = useState<string>('批量导出');   const [openPopver, setOpenPopver] = useState<boolean>(false); //控制导出弹窗   const [activeMenu, setActiveMenu] = useState({     title: '有息债务',     code: 'gfgs_cwzb_yxzw_item06',   });   const { exportPDf } = useCompToPDF({ fileName: exportPDfName });   const yxzwRef = useRef<any>(); //有息债务   const dbsxRef = useRef<any>(); //担保授信   const fbbRef = useRef<any>(); //分布表   const qxbzjgbRef = useRef<any>(); //期限币种结构表   const zqrjgbRef = useRef<any>(); //债权人结构表   const zbyxzwbdqkbRef = useRef<any>(); //总部有息债务变动情况表   const fgsRef = useRef<any>(); //分公司合并报表单位债务变动情况表   const scjeRef = useRef<any>(); //上存资金与负息资金明细表   const dbt1Ref = useRef<any>(); //担保图1   const dbt2Ref = useRef<any>(); //担保图2   const fxb1Ref = useRef<any>(); //分析表1   const fxb2Ref = useRef<any>(); //分析表2   const fxb3Ref = useRef<any>(); //分析表3   const fxb4Ref = useRef<any>(); //分析表4   const ref1 = useRef<any>();   let refGroup = {     yxzwRef,     dbsxRef,     fbbRef,     qxbzjgbRef,     zqrjgbRef,     zbyxzwbdqkbRef,     fgsRef,     scjeRef,     dbt1Ref,     dbt2Ref,     fxb1Ref,     fxb2Ref,     fxb3Ref,     fxb4Ref,   };   let callBackIdsRef = useRef<any>([]); //担保授信   const [allowExport, setAllowExport] = useState<boolean>(false); //选中的导出页面是否加载完毕,加载完毕后调用导出pdf方法   useEffect(() => {     if (indexInfo && indexInfo.children) {       //获取菜单信息       let menuData: any[] = [];       indexInfo.children.forEach((item: any) => {         menuData.push({           title: item.title,           code: item.code,         });       });       setMenu(menuData);     }   }, [indexInfo]);
  //新div加载完回调函数   const useCallBackExport = (id: string) => {     callBackIdsRef.current = [...callBackIdsRef.current, id];     if (callBackIdsRef.current.length === activeExportRef.current.length) {       // 图的页面如果只导出一个,导出的标题是这个页面的名字,导出多个显示批量导出       if (activeExportRef.current.length > 1) {         setExportPDfName('批量导出');       } else {         if (id === 'yxzwRef') {           setExportPDfName('有息债务');         } else if (id === 'dbsxRef') {           setExportPDfName('担保授信');         } else if (id === 'dbt1Ref') {           setExportPDfName('担保图1');         } else if (id === 'dbt2Ref') {           setExportPDfName('担保图2');         }       }       //页面全部返回加载完毕信息       setAllowExport(true);     }   };   //批量导出pdf点击确定事件   const sumbitArticle = (nameGroup: string[]) => {     if (!nameGroup) {       return;     }     activeExportRef.current = nameGroup;     callBackIdsRef.current = [];     let newDiv = nameGroup.map((item: string, index: number) => {       return getBottomContentView({ title: '', code: '' }, item);     });     setLoad(true); //添加loading     setDivList(newDiv);   };
  //允许导出   useEffect(() => {     if (divList.length > 0) {       let dataParam: any[] = [];       activeExportRef.current.forEach((item: string) => {         let isTable = true;         if (           item === 'yxzwRef' ||           item === 'dbsxRef' ||           item === 'dbt1Ref' ||           item === 'dbt2Ref'         ) {           isTable = false;         }         if (!isTable) {           dataParam.push({ ref: (refGroup as any)[item].current });         }       });       setLoad(false); //loading结束       if (dataParam.length > 0) {         exportPDf(dataParam);       }
      form.resetFields(); //清空选中数据       setOpenPopver(false); //关闭弹窗       //清空       callBackIdsRef.current = [];       activeExportRef.current = [];       setAllowExport(false);       setDivList([]);     }   }, [allowExport]);
  // 获取具体页面   const getBottomContentView = (     menu: { title: string; code: string },     exportId?: string,   ) => {     if (menu.code === 'gfgs_cwzb_yxzw_item01' || exportId === 'fbbRef') {       //分布表       return (         <div ref={fbbRef} className={styles.charts}>           <DistributionTable             exportId={exportId ?? undefined}             useCallBackExport={useCallBackExport}           />         </div>       );     } else if (       menu.code === 'gfgs_cwzb_yxzw_item02' ||       exportId === 'qxbzjgbRef'     ) {       //币种结构表       return (         <div ref={qxbzjgbRef} className={styles.charts}>           <CurrencyTable             exportId={exportId ?? undefined}             useCallBackExport={useCallBackExport}           />         </div>       );     } else if (       menu.code === 'gfgs_cwzb_yxzw_item03' ||       exportId === 'zqrjgbRef'     ) {       //债权人结构表       return (         <div ref={zqrjgbRef} className={styles.charts}>           <CreditorTable             useCallBackExport={useCallBackExport}             exportId={exportId ?? undefined}           />         </div>       );     } else if (       menu.code === 'gfgs_cwzb_yxzw_item04' ||       exportId === 'zbyxzwbdqkbRef'     ) {       //总部有息债务变动情况表       return (         <div ref={zbyxzwbdqkbRef} className={styles.charts}>           <GeneralTable             useCallBackExport={useCallBackExport}             exportId={exportId ?? undefined}           />         </div>       );     } else if (menu.code === 'gfgs_cwzb_yxzw_item05' || exportId === 'fgsRef') {       //分公司合并报表单位债务变动情况表       return (         <div ref={fgsRef} className={styles.charts}>           <BranchTable             useCallBackExport={useCallBackExport}             exportId={exportId ?? undefined}           />         </div>       );     } else if (       menu.code === 'gfgs_cwzb_yxzw_item06' ||       exportId === 'yxzwRef'     ) {       //图形名称1
      return (         <div           ref={yxzwRef}           className={styles.charts}           id={exportId ? 'exportCharts' : 'charts'}         >           <ChartOne             useCallBackExport={useCallBackExport}             exportId={exportId ?? undefined}           />         </div>       );     } else if (       menu.code === 'gfgs_cwzb_yxzw_item07' ||       exportId === 'dbsxRef'     ) {       //图形名称2       return (         // 导出的数据         <div           ref={dbsxRef}           className={styles.charts}           id={exportId ? 'exportCharts2' : 'charts'}         >           <ChartTwo             useCallBackExport={useCallBackExport}             exportId={exportId ?? undefined}           />         </div>       );     } else if (       menu.code === 'gfgs_cwzb_yxzw_item08' ||       exportId === 'scjeRef'     ) {       //上存资金与负息资金明细表       return (         <div ref={scjeRef} className={styles.charts}>           <DepositedFunds             useCallBackExport={useCallBackExport}             exportId={exportId ?? undefined}           />         </div>       );     } else if (       menu.code === 'gfgs_cwzb_yxzw_item09' ||       exportId === 'dbt1Ref'     ) {       //担保图1       return (         <div           ref={dbt1Ref}           className={styles.charts}           id={exportId ? 'exportCharts3' : ''}         >           <SecurityOne             useCallBackExport={useCallBackExport}             exportId={exportId ?? undefined}           />         </div>       );     } else if (       menu.code === 'gfgs_cwzb_yxzw_item10' ||       exportId === 'dbt2Ref'     ) {       //担保图2       return (         <div           ref={dbt2Ref}           className={styles.charts}           id={exportId ? 'exportCharts4' : 'charts'}         >           <Security             useCallBackExport={useCallBackExport}             exportId={exportId ?? undefined}           />         </div>       );     } else if (       menu.code === 'gfgs_cwzb_yxzw_item11' ||       exportId === 'fxb1Ref'     ) {       //担保种类分析表1       return (         <div ref={fxb1Ref} className={styles.charts}>           <SecurityTableOne             useCallBackExport={useCallBackExport}             exportId={exportId ?? undefined}           />         </div>       );     } else if (       menu.code === 'gfgs_cwzb_yxzw_item12' ||       exportId === 'fxb2Ref'     ) {       //担保方式分析表2       return (         <div ref={fxb2Ref} className={styles.charts}>           <SecurityTableTwo             useCallBackExport={useCallBackExport}             exportId={exportId ?? undefined}           />         </div>       );     } else if (       menu.code === 'gfgs_cwzb_yxzw_item13' ||       exportId === 'fxb3Ref'     ) {       //担保期限分析表3       return (         <div ref={fxb3Ref} className={styles.charts}>           <SecurityTableThree             useCallBackExport={useCallBackExport}             exportId={exportId ?? undefined}           />         </div>       );     } else if (       menu.code === 'gfgs_cwzb_yxzw_item14' ||       exportId === 'fxb4Ref'     ) {       //担保期限分析表4       return (         <div ref={fxb4Ref} className={styles.charts}>           <SecurityTableFour             useCallBackExport={useCallBackExport}             exportId={exportId ?? undefined}           />         </div>       );     }   };   const prevSlide = () => {     setCurrentIndex((prevIndex) =>       // 第一页点上一页要跳转到最后一页       // prevIndex === 0 ? menu.length - 10 : prevIndex - 1,       // 第一页点上一页无效       prevIndex === 0 ? 0 : prevIndex - 1,     );   };
  const nextSlide = () => {     setCurrentIndex((prevIndex) =>       // prevIndex === menu.length - 10 ? 0 : prevIndex + 1,       prevIndex === menu.length - 11 ? prevIndex : prevIndex + 1,     );   };   // 计算当前显示的轮播图范围   const startIdx = currentIndex;   const endIdx = currentIndex + 11;   const displayedImages = menu.slice(startIdx, endIdx);
  // 表单提交时   const onFinish = (values: any) => {     sumbitArticle(values.checkbox_group); //调用方法获取子组件的dom结构   };   // 表单点击取消时   const onReset = () => {     form.resetFields();     setOpenPopver(false); //关闭弹窗   };   // 一键导出弹窗内容
  const content = () => {     return (       <div className={styles.exportBody}>         {load && (           <div className={styles.spin}>             <Spin size="large" />           </div>         )}
        <div className={styles.tabBody}>           <div>             <Form form={form} name="control-hooks" onFinish={onFinish}>               <Form.Item name="checkbox_group">                 <Checkbox.Group>                   {plainOptions[0].map((data: any) => {                     return (                       <Checkbox value={data.value} disabled={data.disabled}>                         {data.label}                       </Checkbox>                     );                   })}                 </Checkbox.Group>               </Form.Item>               <div className={styles.bottomButton}>                 <Button                   className={styles.okButton}                   type="primary"                   htmlType="submit"                 >                   确定                 </Button>                 <Button                   className={styles.okButton}                   htmlType="button"                   onClick={onReset}                 >                   取消                 </Button>               </div>             </Form>           </div>         </div>       </div>     );   };
  const handleOpenChange = (newOpen: boolean) => {     setOpenPopver(newOpen);   };   return (     <div className={styles.container}>       <div className={styles.menu}>         {menu && menu?.length > 0 && (           <ul className={styles.subNavList}>             {displayedImages.map((item) => {               // 处理菜单               return (                 <li                   className={`${styles.subNavItem}${                     item.code === activeMenu.code ? styles.active : ''                   }`}                   onClick={() => {                     setActiveMenu(item);                   }}                   key={`${item.code}`}                 >                   {item.title}                 </li>               );             })}           </ul>         )}         <div className={styles.arrow}>           <div className={styles.prev} onClick={prevSlide}>             <span               className={`${icon.iconfont}${icon.icon_fanhuijiantou}`}             ></span>           </div>           <div className={styles.next} onClick={nextSlide}>             <span               className={`${icon.iconfont}${icon.icon_jinrujiantou}`}             ></span>           </div>         </div>         {/* 导出按钮 */}         <div className={styles.exportButton}>           <Popover             content={content}             trigger="click"             open={openPopver}             overlayClassName={styles.popstyle}             onOpenChange={handleOpenChange}           >             <div className={styles.button}>               <DownloadOutlined twoToneColor="#eb2f96" />               &nbsp; 一键导出             </div>           </Popover>           <div className={styles.totalUnit}>             {activeMenu.code === 'gfgs_cwzb_yxzw_item07' ||             activeMenu.code === 'gfgs_cwzb_yxzw_item06'               ? '单位:亿元'               : ''}           </div>         </div>       </div>
      <div className={styles.content} ref={ref1}>         {activeMenu && getBottomContentView(activeMenu)}         {divList}       </div>     </div>   ); };
export default IndexPage;

标签:useRef,code,const,menu,导出,return,import,pdf,页面
From: https://www.cnblogs.com/111wdh/p/17833923.html

相关文章

  • 导出当前页面为PDF文件
    html2canvas+jspdfimportuseCompToPDFfrom'@/hooks/use-pdf-hooks/usePDFHooks';constref=useRef<HTMLDivElement>(null);const{exportPDf}=useCompToPDF({fileName:'导出文件'});<buttononClick={()=>{exportPDf(ref.cur......
  • TienChin-课程管理-课程导出
    更改Course.java:/***课程ID*/@TableId(value="course_id",type=IdType.AUTO)@NotNull(message="{course.id.notnull}")@Excel(name="课程编号")privateIntegercourseId;/***课程类型1.舞蹈类2.游泳类3.拳击类*/@NotNull(message=......
  • weblogic导出excel遇到的问题记录
    weblogic使用poi导入jar包冲突解决:https://www.cnblogs.com/ljch/p/12045160.htmlhttps://blog.csdn.net/teigakushi/article/details/17305533https://blog.csdn.net/liushengbaba/article/details/84632236仅针对10.3及以上版本。在WEB-INF下面添加weblogic.xml文件:https......
  • 批量导入和导出docker镜像文件
    维护服务器时,如果服务器没有网络,还需要批量加载多个Docker镜像文件,我们可以使用脚本通过循环来自动化这个操作过程。批量导入docker镜像文件创建一个文本文件,列出你要加载的所有镜像文件路径。每行一个文件路径。创建一个Shell脚本(例如load_images.sh),并打开它。在脚本中,使用docker......
  • 【专题】2023食品行业营销数智化洞察报告PDF合集分享(附原数据表)
    原文链接:https://tecdat.cn/?p=34250原文出处:拓端数据部落公众号近日,一份《2023食品行业营销数智化洞察报告合集》发布,该报告从多个角度对市场、行业、企业进行了数据分析,并预测了2023年营销走势及增长点。阅读原文,获取专题报告合集全文,解锁文末140份食品营销数智化相关行业研究......
  • 【专题】2023年中国汽车出海研究报告PDF合集分享(附原数据表)
    原文链接:https://tecdat.cn/?p=34260原文出处:拓端数据部落公众号近年来,我国汽车出口需求旺盛,并保持强劲增长趋势,至2023年一季度,汽车出口总量首超日本,中国汽车“破浪出海”正当时。本报告合集旨在通过梳理中国汽车的出海背景,分析汽车厂商出海的现状及特点,洞察中国汽车出海的风险......
  • MySQL 导出表结构(含列名、数据类型、字段备注注释)导出成Excel
    SELECTCOLUMN_NAME列名,COLUMN_COMMENT名称,column_key主键,--COLUMN_TYPE数据类型,DATA_TYPE字段类型,CHARACTER_MAXIMUM_LENGTH长度,IS_NULLABLE是否必填,--COLUMN_DEFAULT描述FROMINFORMATION_SCHEMA.COLUMNSwhere--developer......
  • java 使用documents4j将word转pdf
    documents4j简介document4j是一个用来进行文档格式转换的Java工具库,它通过借助本机中支持指定文件格式到目标文件格式转换的应用,来实现整个转换的过程。document4j实现了MicrosoftWord、Excel的适配功能,可以将docx文件转换为pdf文件,并且在这个过程中不会出现非微软文件转换出......
  • js处理前端页面复选框多页复选同时生效的问题
    虽然是后端开发,但在实际的工作中难免会碰到一些前端相关的任务需要自己处理,下面就是本人开发工作中处理的前端相关分页复选的问题。总结一下,以备日后重复遇到:<scripttype="text/javascript">//初始化数据$(function(){$('#queryButton').removeAttr('disabled'......
  • cshtml页面中动态生成URL,Url.RouteUrl()与 Url.Action()有什么区别
    原文链接:http://cn.voidcc.com/question/p-yrfdusit-kx.htmlRouteUrl根据路由名称生成url。如果您有多个参数相似的路由,则Action方法可能会选择错误的路由-它会根据路由定义的顺序工作。这可能发生在您的路线具有可选参数时。如果您想确保使用某个路由网址,您需要呼叫RouteUrl......