| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509 |
- import { useState, useRef } from 'react';
- import * as XLSX from 'xlsx';
- import PizZip from 'pizzip';
- import Docxtemplater from 'docxtemplater';
- import ImageModule from 'open-docxtemplater-image-module-2';
- import JSZip from 'jszip';
- import { Button } from '@/client/components/ui/button';
- import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/client/components/ui/card';
- import { Input } from '@/client/components/ui/input';
- import { Label } from '@/client/components/ui/label';
- import { Alert, AlertDescription } from '@/client/components/ui/alert';
- import {
- FileText, Upload, Download, Eye, FileWarning, FileSpreadsheet,
- RefreshCw, CheckCircle, AlertCircle, DownloadCloud, Image, Package,
- X, ZoomIn, ZoomOut, ChevronLeft, ChevronRight, Settings,
- CheckSquare, Square, Download, Archive, CheckCheck
- } from 'lucide-react';
- import { toast } from 'sonner';
- import WordViewer from '@/client/home/components/WordViewer';
- import { Badge } from '@/client/components/ui/badge';
- import { Progress } from '@/client/components/ui/progress';
- import {
- Dialog,
- DialogContent,
- DialogHeader,
- DialogTitle,
- } from '@/client/components/ui/dialog';
- interface WordFile {
- id: string;
- name: string;
- size: number;
- url: string;
- previewUrl?: string;
- }
- interface ExcelRow {
- [key: string]: string | number;
- }
- interface ImageMapping {
- [key: string]: {
- [imageName: string]: File;
- };
- }
- interface ImageSizeSettings {
- width: number;
- height: number;
- }
- interface ProcessingResult {
- originalFile: File;
- generatedFiles: Array<{
- name: string;
- content: Blob;
- fields: Record<string, string>;
- }>;
- total: number;
- }
- export default function WordPreview() {
- const [selectedWordFile, setSelectedWordFile] = useState<File | null>(null);
- const [selectedExcelFile, setSelectedExcelFile] = useState<File | null>(null);
- const [imageZipFile, setImageZipFile] = useState<File | null>(null);
- const [previewFile, setPreviewFile] = useState<WordFile | null>(null);
- const [isLoading, setIsLoading] = useState(false);
- const [previewLoading, setPreviewLoading] = useState(false);
- const [showPreview, setShowPreview] = useState(false);
- const [processingResult, setProcessingResult] = useState<ProcessingResult | null>(null);
- const [excelData, setExcelData] = useState<ExcelRow[]>([]);
- const [processingProgress, setProcessingProgress] = useState(0);
- const [imageMappings, setImageMappings] = useState<ImageMapping>({});
- const [imagePreviewUrls, setImagePreviewUrls] = useState<Record<string, Record<string, string>>>({});
- const [selectedImage, setSelectedImage] = useState<{
- url: string;
- name: string;
- folder: string;
- } | null>(null);
- const [currentImageIndex, setCurrentImageIndex] = useState(0);
- const [allImages, setAllImages] = useState<Array<{ url: string; name: string; folder: string }>>([]);
-
- const [imageSizeSettings, setImageSizeSettings] = useState<ImageSizeSettings>({ width: 200, height: 150 });
- const [showSizeSettings, setShowSizeSettings] = useState(false);
-
- // 新增状态:选择下载功能
- const [selectedFiles, setSelectedFiles] = useState<Set<number>>(new Set());
- const [isDownloading, setIsDownloading] = useState(false);
- const [downloadProgress, setDownloadProgress] = useState(0);
- const [mergeDownloading, setMergeDownloading] = useState(false);
- const [wordMergeDownloading, setWordMergeDownloading] = useState(false);
-
- const wordFileInputRef = useRef<HTMLInputElement>(null);
- const excelFileInputRef = useRef<HTMLInputElement>(null);
- const imageZipInputRef = useRef<HTMLInputElement>(null);
- // 文件选择处理
- const handleWordFileSelect = (event: React.ChangeEvent<HTMLInputElement>) => {
- const file = event.target.files?.[0];
- if (file) {
- const validTypes = [
- 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
- ];
- const maxSize = 10 * 1024 * 1024;
- if (!validTypes.includes(file.type)) {
- toast.error('请选择有效的Word文件(.docx格式)');
- return;
- }
- if (file.size > maxSize) {
- toast.error('文件大小超过10MB限制');
- return;
- }
- setSelectedWordFile(file);
- setShowPreview(false);
- toast.success('Word模板已选择');
- }
- };
- const handleExcelFileSelect = (event: React.ChangeEvent<HTMLInputElement>) => {
- const file = event.target.files?.[0];
- if (file) {
- const validTypes = [
- 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
- 'application/vnd.ms-excel'
- ];
- const maxSize = 10 * 1024 * 1024;
- if (!validTypes.includes(file.type)) {
- toast.error('请选择有效的Excel文件(.xlsx/.xls格式)');
- return;
- }
- if (file.size > maxSize) {
- toast.error('文件大小超过10MB限制');
- return;
- }
- setSelectedExcelFile(file);
- parseExcelFile(file);
- toast.success('Excel数据文件已选择');
- }
- };
- const handleImageZipSelect = async (event: React.ChangeEvent<HTMLInputElement>) => {
- const file = event.target.files?.[0];
- if (file) {
- const validTypes = ['application/zip', 'application/x-zip-compressed'];
- const maxSize = 50 * 1024 * 1024;
- if (!validTypes.includes(file.type)) {
- toast.error('请选择有效的ZIP压缩文件');
- return;
- }
- if (file.size > maxSize) {
- toast.error('压缩文件大小超过50MB限制');
- return;
- }
- setImageZipFile(file);
- await parseImageZip(file);
- toast.success('图片压缩文件已选择');
- }
- };
- // 解析Excel文件
- const parseExcelFile = async (file: File) => {
- try {
- const data = await file.arrayBuffer();
- const workbook = XLSX.read(data, { type: 'array' });
- const firstSheetName = workbook.SheetNames[0];
- const worksheet = workbook.Sheets[firstSheetName];
- const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 }) as any[][];
- if (jsonData.length < 2) {
- toast.error('Excel文件格式不正确,需要包含表头和至少一行数据');
- return;
- }
- const headers = jsonData[0] as string[];
- const rows: ExcelRow[] = [];
- for (let i = 1; i < jsonData.length; i++) {
- const row = jsonData[i];
- const rowData: ExcelRow = {};
- headers.forEach((header, index) => {
- rowData[header] = row[index] || '';
- });
- rows.push(rowData);
- }
- setExcelData(rows);
- toast.success(`成功解析 ${rows.length} 条数据记录`);
- } catch (error) {
- toast.error('Excel文件解析失败');
- console.error('Excel parsing error:', error);
- }
- };
- // 解析图片压缩文件
- const parseImageZip = async (file: File) => {
- try {
- const zip = new JSZip();
- const zipContent = await zip.loadAsync(file);
- const newImageMappings: ImageMapping = {};
- const newImagePreviewUrls: Record<string, Record<string, string>> = {};
- const allImages: Array<{ url: string; name: string; folder: string }> = [];
- // 解析文件夹结构:第一层为序号,第二层为图片
- for (const [path, zipEntry] of Object.entries(zipContent.files)) {
- if (!zipEntry.dir && isImageFile(path)) {
- const pathParts = path.split('/');
- if (pathParts.length >= 2) {
- const folderIndex = pathParts[0]; // 序号文件夹
- const imageName = pathParts[pathParts.length - 1].split('.')[0]; // 去掉扩展名的文件名
- const fullImageName = pathParts[pathParts.length - 1]; // 完整文件名
-
- if (!newImageMappings[folderIndex]) {
- newImageMappings[folderIndex] = {};
- newImagePreviewUrls[folderIndex] = {};
- }
-
- const imageFile = await zipEntry.async('blob');
- newImageMappings[folderIndex][imageName] = new File([imageFile], imageName, {
- type: getImageMimeType(path)
- });
-
- // 创建预览URL
- const previewUrl = URL.createObjectURL(imageFile);
- newImagePreviewUrls[folderIndex][imageName] = previewUrl;
-
- allImages.push({
- url: previewUrl,
- name: fullImageName,
- folder: folderIndex
- });
- }
- }
- }
- setImageMappings(newImageMappings);
- setImagePreviewUrls(newImagePreviewUrls);
- setAllImages(allImages);
- toast.success(`成功解析 ${Object.keys(newImageMappings).length} 个文件夹的图片`);
- } catch (error) {
- toast.error('图片压缩文件解析失败');
- console.error('Image zip parsing error:', error);
- }
- };
- // 工具函数
- const isImageFile = (filename: string): boolean => {
- const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp'];
- return imageExtensions.some(ext => filename.toLowerCase().endsWith(ext));
- };
- const getImageMimeType = (filename: string): string => {
- const extension = filename.toLowerCase().split('.').pop();
- const mimeTypes: Record<string, string> = {
- 'jpg': 'image/jpeg',
- 'jpeg': 'image/jpeg',
- 'png': 'image/png',
- 'gif': 'image/gif',
- 'bmp': 'image/bmp',
- 'webp': 'image/webp'
- };
- return mimeTypes[extension || ''] || 'image/jpeg';
- };
- // 不再需要从模板解析图片尺寸,使用用户设置
- // 计算保持比例的图片尺寸
- const calculateProportionalSize = (
- originalWidth: number,
- originalHeight: number,
- maxWidth: number,
- maxHeight: number
- ): [number, number] => {
- const widthRatio = maxWidth / originalWidth;
- const heightRatio = maxHeight / originalHeight;
-
- // 使用较小的比例以保持原始长宽比
- const ratio = Math.min(widthRatio, heightRatio, 1);
-
- const newWidth = Math.round(originalWidth * ratio);
- const newHeight = Math.round(originalHeight * ratio);
-
- return [newWidth, newHeight];
- };
- // 替换Word字段并插入图片
- const replaceFieldsInWord = async (wordFile: File, excelRow: ExcelRow, rowIndex: number): Promise<Blob> => {
- try {
- const arrayBuffer = await wordFile.arrayBuffer();
- const zip = new PizZip(arrayBuffer);
-
- // 预加载所有图片数据,避免Promise问题
- const folderIndex = (rowIndex + 1).toString();
- const imageDataMap: Record<string, ArrayBuffer> = {};
-
- // 预加载当前文件夹的所有图片
- if (imageMappings[folderIndex]) {
- for (const [imageName, imageFile] of Object.entries(imageMappings[folderIndex])) {
- try {
- imageDataMap[imageName] = await imageFile.arrayBuffer();
- } catch (error) {
- console.warn(`Failed to load image ${imageName}:`, error);
- }
- }
- }
-
- // 使用用户设置的图片尺寸限制
- const defaultLimit = imageSizeSettings;
-
- // 配置图片模块 - 使用实际图片尺寸并应用限制
- const imageSizeCache = new Map<string, [number, number]>();
-
- const imageOpts = {
- centered: false,
- getImage: (tagValue: string): ArrayBuffer | null => {
- if (tagValue && typeof tagValue === 'string') {
- return imageDataMap[tagValue] || null;
- }
- return null;
- },
- getSize: (img: ArrayBuffer, tagValue: string, tagName: string) => {
- try {
- const cacheKey = `${tagValue}_${img.byteLength}`;
-
- if (imageSizeCache.has(cacheKey)) {
- return imageSizeCache.get(cacheKey)!;
- }
-
- // 获取图片原始尺寸
- let originalWidth = 200;
- let originalHeight = 150;
-
- const view = new DataView(img);
-
- // PNG格式检测
- if (view.getUint32(0) === 0x89504E47 && view.getUint32(4) === 0x0D0A1A0A) {
- originalWidth = view.getUint32(16);
- originalHeight = view.getUint32(20);
- }
- // JPEG格式检测
- else if (view.getUint16(0) === 0xFFD8) {
- let offset = 2;
- while (offset < img.byteLength - 10) {
- if (view.getUint8(offset) === 0xFF) {
- const marker = view.getUint8(offset + 1);
- if (marker >= 0xC0 && marker <= 0xC3) {
- originalHeight = view.getUint16(offset + 5);
- originalWidth = view.getUint16(offset + 7);
- break;
- }
- const length = view.getUint16(offset + 2);
- offset += length + 2;
- continue;
- }
- offset++;
- }
- }
-
- // 计算符合尺寸限制的最终尺寸
- const [finalWidth, finalHeight] = calculateProportionalSize(
- originalWidth,
- originalHeight,
- defaultLimit.width,
- defaultLimit.height
- );
-
- const finalSize: [number, number] = [finalWidth, finalHeight];
- imageSizeCache.set(cacheKey, finalSize);
-
- return finalSize;
-
- } catch (error) {
- console.warn('Failed to get image size, using default:', error);
- return [defaultLimit.width, defaultLimit.height];
- }
- }
- };
-
- const imageModule = new ImageModule(imageOpts);
- // 创建Docxtemplater实例
- const doc = new Docxtemplater(zip, {
- modules: [imageModule],
- paragraphLoop: true,
- linebreaks: true,
- });
- // 处理嵌套数据结构
- const processedData: Record<string, any> = {};
-
- // 处理普通字段
- Object.entries(excelRow).forEach(([key, value]) => {
- if (key.includes('.')) {
- const parts = key.split('.');
- let current = processedData;
- for (let i = 0; i < parts.length - 1; i++) {
- if (!current[parts[i]]) {
- current[parts[i]] = {};
- }
- current = current[parts[i]];
- }
- current[parts[parts.length - 1]] = value;
- } else {
- processedData[key] = value;
- }
- });
- // 处理图片字段 - 确保图片名称正确传递给模板
- if (imageMappings[folderIndex]) {
- for (const [imageName] of Object.entries(imageMappings[folderIndex])) {
- // 确保图片名称作为标签值传递给模板
- processedData[imageName] = imageName;
- }
- }
- doc.render(processedData);
-
- const generatedDoc = doc.getZip().generate({
- type: 'blob',
- mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
- });
- return generatedDoc;
- } catch (error) {
- console.error('Word处理错误:', error);
- throw new Error(`Word文档处理失败,请检查模板格式: ${error instanceof Error ? error.message : String(error)}`);
- }
- };
- // 处理文件
- const processFiles = async () => {
- if (!selectedWordFile || !selectedExcelFile || excelData.length === 0) {
- toast.error('请先选择Word模板和Excel数据文件');
- return;
- }
- setIsLoading(true);
- setProcessingProgress(0);
-
- try {
- const generatedFiles: ProcessingResult['generatedFiles'] = [];
-
- for (let i = 0; i < excelData.length; i++) {
- const row = excelData[i];
- const processedBlob = await replaceFieldsInWord(selectedWordFile, row, i);
-
- const fileName = `processed_${i + 1}_${selectedWordFile.name}`;
- generatedFiles.push({
- name: fileName,
- content: processedBlob,
- fields: row
- });
- setProcessingProgress(((i + 1) / excelData.length) * 100);
- }
- const result: ProcessingResult = {
- originalFile: selectedWordFile,
- generatedFiles,
- total: generatedFiles.length
- };
- setProcessingResult(result);
- toast.success(`成功生成 ${generatedFiles.length} 个文档`);
-
- } catch (error) {
- toast.error('文档处理失败');
- console.error('Processing error:', error);
- } finally {
- setIsLoading(false);
- setProcessingProgress(0);
- }
- };
- // 预览功能
- const handlePreview = async () => {
- if (!selectedWordFile) {
- toast.error('请先选择Word文件');
- return;
- }
- setPreviewLoading(true);
- setShowPreview(true);
-
- try {
- const fileUrl = URL.createObjectURL(selectedWordFile);
- const wordFile: WordFile = {
- id: Date.now().toString(),
- name: selectedWordFile.name,
- size: selectedWordFile.size,
- url: fileUrl,
- previewUrl: fileUrl
- };
-
- setPreviewFile(wordFile);
- toast.success('正在预览Word模板...');
- } catch (error) {
- toast.error('文件预览失败');
- console.error('Preview error:', error);
- setShowPreview(false);
- } finally {
- setPreviewLoading(false);
- }
- };
- // 下载功能
- const downloadProcessedFile = (file: ProcessingResult['generatedFiles'][0]) => {
- const url = URL.createObjectURL(file.content);
- const a = document.createElement('a');
- a.href = url;
- a.download = file.name;
- document.body.appendChild(a);
- a.click();
- document.body.removeChild(a);
- URL.revokeObjectURL(url);
- };
- const downloadAllFiles = () => {
- if (!processingResult) return;
- processingResult.generatedFiles.forEach((file, index) => {
- setTimeout(() => {
- downloadProcessedFile(file);
- }, index * 500);
- });
- };
- // 新增:选择下载功能
- const toggleFileSelection = (index: number) => {
- const newSelectedFiles = new Set(selectedFiles);
- if (newSelectedFiles.has(index)) {
- newSelectedFiles.delete(index);
- } else {
- newSelectedFiles.add(index);
- }
- setSelectedFiles(newSelectedFiles);
- };
- const selectAllFiles = () => {
- if (!processingResult) return;
- const allIndices = new Set(Array.from({ length: processingResult.generatedFiles.length }, (_, i) => i));
- setSelectedFiles(allIndices);
- };
- const clearSelection = () => {
- setSelectedFiles(new Set());
- };
- const downloadSelectedFiles = async () => {
- if (!processingResult || selectedFiles.size === 0) return;
-
- setIsDownloading(true);
- setDownloadProgress(0);
-
- const filesToDownload = Array.from(selectedFiles)
- .sort((a, b) => a - b)
- .map(index => processingResult.generatedFiles[index]);
-
- for (let i = 0; i < filesToDownload.length; i++) {
- downloadProcessedFile(filesToDownload[i]);
- setDownloadProgress(((i + 1) / filesToDownload.length) * 100);
- await new Promise(resolve => setTimeout(resolve, 300)); // 添加延迟避免浏览器阻塞
- }
-
- setIsDownloading(false);
- setDownloadProgress(0);
- toast.success(`已下载 ${filesToDownload.length} 个文档`);
- };
- // 新增:Word文档合并下载功能
- const mergeAndDownloadFiles = async () => {
- if (!processingResult || selectedFiles.size === 0) return;
-
- setMergeDownloading(true);
-
- try {
- const filesToMerge = Array.from(selectedFiles)
- .sort((a, b) => a - b)
- .map(index => processingResult.generatedFiles[index]);
-
- // 创建一个新的JSZip实例来合并文件
- const JSZip = (await import('jszip')).default;
- const zip = new JSZip();
-
- // 将所有选中的文件添加到zip中
- filesToMerge.forEach((file, index) => {
- zip.file(file.name, file.content);
- });
-
- // 生成zip文件
- const zipContent = await zip.generateAsync({
- type: 'blob',
- compression: 'DEFLATE',
- compressionOptions: {
- level: 6
- }
- });
-
- // 下载合并的zip文件
- const url = URL.createObjectURL(zipContent);
- const a = document.createElement('a');
- a.href = url;
- a.download = `合并文档_${new Date().toISOString().slice(0, 10)}.zip`;
- document.body.appendChild(a);
- a.click();
- document.body.removeChild(a);
- URL.revokeObjectURL(url);
-
- toast.success(`已合并并下载 ${filesToMerge.length} 个文档`);
-
- } catch (error) {
- console.error('文档合并失败:', error);
- toast.error('文档合并失败,请重试');
- } finally {
- setMergeDownloading(false);
- }
- };
- // 新增:下载所有文件为zip
- const downloadAllAsZip = async () => {
- if (!processingResult) return;
-
- setMergeDownloading(true);
-
- try {
- const JSZip = (await import('jszip')).default;
- const zip = new JSZip();
-
- processingResult.generatedFiles.forEach((file, index) => {
- zip.file(file.name, file.content);
- });
-
- const zipContent = await zip.generateAsync({
- type: 'blob',
- compression: 'DEFLATE',
- compressionOptions: {
- level: 6
- }
- });
-
- const url = URL.createObjectURL(zipContent);
- const a = document.createElement('a');
- a.href = url;
- a.download = `全部文档_${new Date().toISOString().slice(0, 10)}.zip`;
- document.body.appendChild(a);
- a.click();
- document.body.removeChild(a);
- URL.revokeObjectURL(url);
-
- toast.success(`已下载全部 ${processingResult.generatedFiles.length} 个文档为压缩包`);
-
- } catch (error) {
- console.error('压缩包创建失败:', error);
- toast.error('压缩包创建失败,请重试');
- } finally {
- setMergeDownloading(false);
- }
- };
- // 新增:Word文档内容合并功能(将多个Word文档合并成一个Word文档)
- const mergeWordDocuments = async () => {
- if (!processingResult || selectedFiles.size === 0) return;
-
- setWordMergeDownloading(true);
-
- try {
- const filesToMerge = Array.from(selectedFiles)
- .sort((a, b) => a - b)
- .map(index => processingResult.generatedFiles[index]);
- // 加载docxtemplater和pizzip
- const PizZip = (await import('pizzip')).default;
- const Docxtemplater = (await import('docxtemplater')).default;
- // 创建一个新的空Word文档作为基础
- const baseArrayBuffer = await selectedWordFile!.arrayBuffer();
- const baseZip = new PizZip(baseArrayBuffer);
- const baseDoc = new Docxtemplater(baseZip, {
- paragraphLoop: true,
- linebreaks: true,
- });
- // 获取基础文档的内容
- baseDoc.render({});
- const baseContent = baseDoc.getZip().generate({
- type: 'blob',
- mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
- });
- // 创建一个新的JSZip实例来合并内容
- const JSZip = (await import('jszip')).default;
- const mergedZip = new JSZip();
-
- // 加载基础文档
- const baseDocx = await mergedZip.loadAsync(await baseContent.arrayBuffer());
-
- // 获取基础文档的word/document.xml内容
- let mergedContent = await baseDocx.file('word/document.xml').async('text');
-
- // 移除基础文档的结束标签,以便添加其他文档内容
- mergedContent = mergedContent.replace(/<\/w:body><\/w:document>$/, '');
-
- // 逐个添加其他文档的内容
- for (const file of filesToMerge) {
- const fileArrayBuffer = await file.content.arrayBuffer();
- const fileZip = await mergedZip.loadAsync(fileArrayBuffer);
- let fileContent = await fileZip.file('word/document.xml').async('text');
-
- // 提取文档主体内容(去掉xml声明和文档标签)
- const bodyMatch = fileContent.match(/<w:body[^>]*>([\s\S]*?)<\/w:body>/);
- if (bodyMatch && bodyMatch[1]) {
- mergedContent += bodyMatch[1];
- }
- }
-
- // 添加结束标签
- mergedContent += '</w:body></w:document>';
-
- // 更新合并后的内容
- baseDocx.file('word/document.xml', mergedContent);
-
- // 生成合并后的Word文档
- const mergedDoc = await baseDocx.generateAsync({
- type: 'blob',
- mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
- compression: 'DEFLATE',
- compressionOptions: { level: 6 }
- });
-
- // 下载合并后的Word文档
- const url = URL.createObjectURL(mergedDoc);
- const a = document.createElement('a');
- a.href = url;
- a.download = `合并Word文档_${new Date().toISOString().slice(0, 10)}.docx`;
- document.body.appendChild(a);
- a.click();
- document.body.removeChild(a);
- URL.revokeObjectURL(url);
-
- toast.success(`已成功合并 ${filesToMerge.length} 个Word文档为一个文件`);
-
- } catch (error) {
- console.error('Word文档合并失败:', error);
- toast.error('Word文档合并失败,请重试');
- } finally {
- setWordMergeDownloading(false);
- }
- };
- const clearAllFiles = () => {
- setSelectedWordFile(null);
- setSelectedExcelFile(null);
- setImageZipFile(null);
- setExcelData([]);
- setProcessingResult(null);
- setImageMappings({});
- setImagePreviewUrls({});
- setSelectedImage(null);
- setAllImages([]);
- setPreviewFile(null);
- setShowPreview(false);
-
- if (wordFileInputRef.current) wordFileInputRef.current.value = '';
- if (excelFileInputRef.current) excelFileInputRef.current.value = '';
- if (imageZipInputRef.current) imageZipInputRef.current.value = '';
-
- toast.success('已清除所有文件');
- };
- const formatFileSize = (bytes: number) => {
- if (bytes === 0) return '0 Bytes';
- const k = 1024;
- const sizes = ['Bytes', 'KB', 'MB', 'GB'];
- const i = Math.floor(Math.log(bytes) / Math.log(k));
- return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
- };
- // 图片预览功能
- const openImagePreview = (url: string, name: string, folder: string) => {
- const imageIndex = allImages.findIndex(img => img.url === url);
- setCurrentImageIndex(imageIndex !== -1 ? imageIndex : 0);
- setSelectedImage({ url, name, folder });
- };
- const closeImagePreview = () => {
- setSelectedImage(null);
- };
- const navigateImage = (direction: 'prev' | 'next') => {
- if (allImages.length === 0) return;
-
- let newIndex = currentImageIndex;
- if (direction === 'prev') {
- newIndex = currentImageIndex > 0 ? currentImageIndex - 1 : allImages.length - 1;
- } else {
- newIndex = currentImageIndex < allImages.length - 1 ? currentImageIndex + 1 : 0;
- }
-
- setCurrentImageIndex(newIndex);
- setSelectedImage(allImages[newIndex]);
- };
- const getTotalImages = () => {
- return Object.values(imagePreviewUrls).reduce((total, folder) => total + Object.keys(folder).length, 0);
- };
- return (
- <div className="space-y-6">
- <div>
- <h1 className="text-3xl font-bold tracking-tight">元亨Word批量处理增强版</h1>
- <p className="text-muted-foreground">支持图片压缩文件,自动生成替换字段和图片的文档</p>
- </div>
- {/* 文件上传区域 */}
- <div className="grid gap-6 md:grid-cols-3">
- {/* Word模板上传 */}
- <Card>
- <CardHeader>
- <CardTitle className="flex items-center gap-2">
- <FileText className="h-5 w-5" />
- 选择Word模板
- </CardTitle>
- <CardDescription>
- 支持 .docx 格式的Word文档,最大10MB
- </CardDescription>
- </CardHeader>
- <CardContent className="space-y-4">
- <div className="grid w-full items-center gap-1.5">
- <Label htmlFor="word-file">Word模板文件</Label>
- <Input
- ref={wordFileInputRef}
- id="word-file"
- type="file"
- accept=".docx,application/vnd.openxmlformats-officedocument.wordprocessingml.document"
- onChange={handleWordFileSelect}
- />
- </div>
- {selectedWordFile && (
- <Alert>
- <FileText className="h-4 w-4" />
- <AlertDescription>
- <div className="space-y-1">
- <p><strong>文件名:</strong> {selectedWordFile.name}</p>
- <p><strong>大小:</strong> {formatFileSize(selectedWordFile.size)}</p>
- </div>
- </AlertDescription>
- </Alert>
- )}
- </CardContent>
- </Card>
- {/* Excel数据上传 */}
- <Card>
- <CardHeader>
- <CardTitle className="flex items-center gap-2">
- <FileSpreadsheet className="h-5 w-5" />
- 选择Excel数据
- </CardTitle>
- <CardDescription>
- 支持 .xlsx/.xls 格式的Excel文档,最大10MB
- </CardDescription>
- </CardHeader>
- <CardContent className="space-y-4">
- <div className="grid w-full items-center gap-1.5">
- <Label htmlFor="excel-file">Excel数据文件</Label>
- <Input
- ref={excelFileInputRef}
- id="excel-file"
- type="file"
- accept=".xlsx,.xls,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
- onChange={handleExcelFileSelect}
- />
- </div>
- {selectedExcelFile && (
- <Alert>
- <FileSpreadsheet className="h-4 w-4" />
- <AlertDescription>
- <div className="space-y-1">
- <p><strong>文件名:</strong> {selectedExcelFile.name}</p>
- <p><strong>大小:</strong> {formatFileSize(selectedExcelFile.size)}</p>
- {excelData.length > 0 && (
- <p><strong>数据行数:</strong> {excelData.length}</p>
- )}
- </div>
- </AlertDescription>
- </Alert>
- )}
- </CardContent>
- </Card>
- {/* 图片压缩文件上传 */}
- <Card>
- <CardHeader>
- <CardTitle className="flex items-center gap-2">
- <Package className="h-5 w-5" />
- 选择图片压缩包
- </CardTitle>
- <CardDescription>
- 支持 .zip 格式压缩包,最大50MB
- </CardDescription>
- </CardHeader>
- <CardContent className="space-y-4">
- <div className="grid w-full items-center gap-1.5">
- <Label htmlFor="image-zip">图片压缩文件</Label>
- <Input
- ref={imageZipInputRef}
- id="image-zip"
- type="file"
- accept=".zip,application/zip,application/x-zip-compressed"
- onChange={handleImageZipSelect}
- />
- </div>
- {imageZipFile && (
- <Alert>
- <Image className="h-4 w-4" />
- <AlertDescription>
- <div className="space-y-1">
- <p><strong>文件名:</strong> {imageZipFile.name}</p>
- <p><strong>大小:</strong> {formatFileSize(imageZipFile.size)}</p>
- {Object.keys(imageMappings).length > 0 && (
- <p><strong>文件夹数:</strong> {Object.keys(imageMappings).length}</p>
- )}
- </div>
- </AlertDescription>
- </Alert>
- )}
- </CardContent>
- </Card>
- </div>
- {/* 操作按钮 */}
- <Card>
- <CardHeader>
- <CardTitle>操作区域</CardTitle>
- <CardDescription>选择文件后执行相应操作</CardDescription>
- </CardHeader>
- <CardContent className="space-y-4">
- <div className="flex gap-2 flex-wrap">
- <Button
- onClick={handlePreview}
- disabled={!selectedWordFile || previewLoading}
- variant="outline"
- >
- <Eye className="h-4 w-4 mr-2" />
- 预览模板
- </Button>
-
- <Button
- onClick={processFiles}
- disabled={!selectedWordFile || !selectedExcelFile || excelData.length === 0 || isLoading}
- className="bg-blue-600 hover:bg-blue-700"
- >
- {isLoading ? (
- <>
- <RefreshCw className="h-4 w-4 mr-2 animate-spin" />
- 处理中...
- </>
- ) : (
- <>
- <Upload className="h-4 w-4 mr-2" />
- 开始处理
- </>
- )}
- </Button>
- <Button
- onClick={clearAllFiles}
- variant="outline"
- className="text-red-600 hover:text-red-700"
- >
- 清除所有
- </Button>
- </div>
-
- {/* 图片尺寸设置 */}
- <div className="border-t pt-4 mt-4">
- <div className="flex items-center justify-between mb-3">
- <h4 className="font-medium">图片尺寸设置</h4>
- <Button
- variant="outline"
- size="sm"
- onClick={() => setShowSizeSettings(!showSizeSettings)}
- >
- <Settings className="h-4 w-4 mr-2" />
- {showSizeSettings ? '隐藏设置' : '设置尺寸'}
- </Button>
- </div>
-
- {showSizeSettings && (
- <div className="grid grid-cols-2 gap-4 p-4 bg-gray-50 rounded-lg">
- <div>
- <Label htmlFor="image-width">图片宽度 (像素)</Label>
- <Input
- id="image-width"
- type="number"
- min="0"
- max="1000"
- value={imageSizeSettings.width}
- onChange={(e) => setImageSizeSettings(prev => ({
- ...prev,
- width: Math.max(0, Math.min(1000, parseInt(e.target.value) || 0))
- }))}
- className="mt-1"
- />
- </div>
- <div>
- <Label htmlFor="image-height">图片高度 (像素)</Label>
- <Input
- id="image-height"
- type="number"
- min="0"
- max="1000"
- value={imageSizeSettings.height}
- onChange={(e) => setImageSizeSettings(prev => ({
- ...prev,
- height: Math.max(0, Math.min(1000, parseInt(e.target.value) || 0))
- }))}
- className="mt-1"
- />
- </div>
- <div className="col-span-2">
- <div className="text-sm text-muted-foreground">
- <p>• 当前设置:宽度 {imageSizeSettings.width}px,高度 {imageSizeSettings.height}px</p>
- <p>• 系统将自动保持图片长宽比例</p>
- <p>• 支持范围:0-1000 像素,可输入任意数值</p>
- <p>• 建议尺寸:单列620×1000像素,双列300×500像素</p>
- </div>
- </div>
- </div>
- )}
- </div>
- {isLoading && (
- <div className="space-y-2">
- <Progress value={processingProgress} className="w-full" />
- <p className="text-sm text-muted-foreground text-center">
- 正在处理文档... {Math.round(processingProgress)}%
- </p>
- </div>
- )}
- </CardContent>
- </Card>
- {/* 预览区域 */}
- {showPreview && selectedWordFile && (
- <Card>
- <CardHeader>
- <CardTitle className="flex items-center gap-2">
- <FileText className="h-5 w-5" />
- 文档预览
- </CardTitle>
- <CardDescription>
- {selectedWordFile.name}
- </CardDescription>
- </CardHeader>
- <CardContent>
- <WordViewer file={selectedWordFile} />
- </CardContent>
- </Card>
- )}
- {/* 图片映射预览 */}
- {Object.keys(imageMappings).length > 0 && (
- <Card>
- <CardHeader>
- <CardTitle className="flex items-center gap-2">
- <Image className="h-5 w-5" />
- 图片映射预览
- </CardTitle>
- <CardDescription>
- 共 {getTotalImages()} 张图片,点击缩略图查看大图
- </CardDescription>
- </CardHeader>
- <CardContent>
- <div className="space-y-4">
- {Object.entries(imagePreviewUrls).map(([folder, images]) => (
- <div key={folder} className="border rounded-lg p-4">
- <h4 className="font-semibold text-lg mb-3 flex items-center gap-2">
- <Package className="h-4 w-4" />
- 文件夹 {folder} ({Object.keys(images).length} 张图片)
- </h4>
- <div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-3">
- {Object.entries(images).map(([imageName, previewUrl]) => (
- <div
- key={imageName}
- className="group relative cursor-pointer"
- onClick={() => openImagePreview(previewUrl, imageName, folder)}
- >
- <div className="aspect-square rounded-lg overflow-hidden border hover:border-blue-500 transition-colors">
- <img
- src={previewUrl}
- alt={imageName}
- className="w-full h-full object-cover"
- />
- </div>
- <div className="mt-1">
- <p className="text-xs text-center truncate text-gray-600 group-hover:text-blue-600">
- {imageName}
- </p>
- </div>
- <div className="absolute inset-0 bg-black/0 group-hover:bg-black/20 transition-opacity rounded-lg flex items-center justify-center">
- <ZoomIn className="h-6 w-6 text-white opacity-0 group-hover:opacity-100 transition-opacity" />
- </div>
- </div>
- ))}
- </div>
- </div>
- ))}
- </div>
- </CardContent>
- </Card>
- )}
- {/* 数据预览 */}
- {excelData.length > 0 && (
- <Card>
- <CardHeader>
- <CardTitle className="flex items-center gap-2">
- <FileSpreadsheet className="h-5 w-5" />
- Excel数据预览
- </CardTitle>
- <CardDescription>
- 显示前5行数据,共 {excelData.length} 行
- </CardDescription>
- </CardHeader>
- <CardContent>
- <div className="overflow-x-auto">
- <table className="w-full text-sm">
- <thead>
- <tr className="border-b">
- {Object.keys(excelData[0]).map(header => (
- <th key={header} className="text-left p-2 font-medium">
- {header}
- </th>
- ))}
- </tr>
- </thead>
- <tbody>
- {excelData.slice(0, 5).map((row, index) => (
- <tr key={index} className="border-b">
- {Object.values(row).map((value, valueIndex) => (
- <td key={valueIndex} className="p-2">
- {String(value)}
- </td>
- ))}
- </tr>
- ))}
- </tbody>
- </table>
- {excelData.length > 5 && (
- <p className="text-sm text-muted-foreground mt-2 text-center">
- 还有 {excelData.length - 5} 行数据...
- </p>
- )}
- </div>
- </CardContent>
- </Card>
- )}
- {/* 处理结果预览 */}
- {processingResult && processingResult.generatedFiles.length > 0 && (
- <Card>
- <CardHeader>
- <CardTitle className="flex items-center gap-2">
- <FileText className="h-5 w-5" />
- 处理结果预览
- </CardTitle>
- <CardDescription>
- 预览第一个生成的文档
- </CardDescription>
- </CardHeader>
- <CardContent>
- <WordViewer file={processingResult.generatedFiles[0].content} />
- </CardContent>
- </Card>
- )}
- {/* 处理结果 */}
- {processingResult && (
- <Card>
- <CardHeader>
- <CardTitle className="flex items-center gap-2">
- <CheckCircle className="h-5 w-5 text-green-500" />
- 处理完成
- </CardTitle>
- <CardDescription>
- 共生成 {processingResult.total} 个文档
- </CardDescription>
- </CardHeader>
- <CardContent>
- <div className="space-y-4">
- {/* 批量操作工具栏 */}
- <div className="flex flex-wrap gap-2 items-center justify-between p-3 bg-blue-50 rounded-lg">
- <div className="flex items-center gap-2">
- <span className="text-sm font-medium">
- 已选择 {selectedFiles.size} 个文档
- </span>
- {selectedFiles.size > 0 && (
- <Button
- variant="ghost"
- size="sm"
- onClick={clearSelection}
- className="h-7 px-2 text-xs"
- >
- 取消选择
- </Button>
- )}
- </div>
-
- <div className="flex gap-2">
- <Button
- variant="outline"
- size="sm"
- onClick={selectAllFiles}
- className="h-7 px-2 text-xs"
- >
- <CheckSquare className="h-3 w-3 mr-1" />
- 全选
- </Button>
-
- {selectedFiles.size > 0 && (
- <>
- <Button
- onClick={downloadSelectedFiles}
- disabled={isDownloading || selectedFiles.size === 0}
- size="sm"
- className="h-7 px-2 text-xs bg-green-600 hover:bg-green-700"
- >
- {isDownloading ? (
- <RefreshCw className="h-3 w-3 mr-1 animate-spin" />
- ) : (
- <Download className="h-3 w-3 mr-1" />
- )}
- 下载选中 ({selectedFiles.size})
- </Button>
-
- <Button
- onClick={mergeAndDownloadFiles}
- disabled={mergeDownloading || selectedFiles.size === 0}
- size="sm"
- variant="outline"
- className="h-7 px-2 text-xs"
- >
- {mergeDownloading ? (
- <RefreshCw className="h-3 w-3 mr-1 animate-spin" />
- ) : (
- <Archive className="h-3 w-3 mr-1" />
- )}
- 打包为ZIP
- </Button>
-
- <Button
- onClick={mergeWordDocuments}
- disabled={wordMergeDownloading || selectedFiles.size === 0}
- size="sm"
- variant="outline"
- className="h-7 px-2 text-xs bg-green-600 hover:bg-green-700 text-white"
- >
- {wordMergeDownloading ? (
- <RefreshCw className="h-3 w-3 mr-1 animate-spin" />
- ) : (
- <FileText className="h-3 w-3 mr-1" />
- )}
- 合并为Word
- </Button>
- </>
- )}
- </div>
- </div>
- {/* 下载全部选项 */}
- <div className="grid grid-cols-2 gap-2">
- <Button
- onClick={downloadAllFiles}
- variant="outline"
- className="w-full"
- >
- <DownloadCloud className="h-4 w-4 mr-2" />
- 逐个下载全部
- </Button>
-
- <Button
- onClick={downloadAllAsZip}
- disabled={mergeDownloading}
- className="w-full bg-blue-600 hover:bg-blue-700"
- >
- {mergeDownloading ? (
- <RefreshCw className="h-4 w-4 mr-2 animate-spin" />
- ) : (
- <Archive className="h-4 w-4 mr-2" />
- )}
- 打包下载全部
- </Button>
- </div>
- {/* 下载进度显示 */}
- {(isDownloading || mergeDownloading) && (
- <div className="space-y-2">
- <Progress
- value={isDownloading ? downloadProgress : 100}
- className="w-full"
- />
- <p className="text-sm text-muted-foreground text-center">
- {isDownloading ? `正在下载文档... ${Math.round(downloadProgress)}%` : '正在打包文档...'}
- </p>
- </div>
- )}
- {/* 文档列表 */}
- <div className="space-y-2 max-h-64 overflow-y-auto">
- {processingResult.generatedFiles.map((file, index) => (
- <div
- key={index}
- className={`flex items-center justify-between p-3 rounded-lg border ${
- selectedFiles.has(index)
- ? 'bg-blue-50 border-blue-200'
- : 'bg-gray-50 border-gray-200'
- }`}
- >
- <div className="flex items-center gap-3 flex-1 min-w-0">
- <Button
- variant="ghost"
- size="icon"
- className="h-6 w-6 shrink-0"
- onClick={() => toggleFileSelection(index)}
- >
- {selectedFiles.has(index) ? (
- <CheckSquare className="h-4 w-4 text-blue-600" />
- ) : (
- <Square className="h-4 w-4 text-gray-400" />
- )}
- </Button>
-
- <div className="min-w-0 flex-1">
- <p className="font-medium truncate">{file.name}</p>
- <p className="text-sm text-muted-foreground">
- 包含 {Object.keys(file.fields).length} 个字段
- </p>
- </div>
- </div>
-
- <div className="flex items-center gap-1 shrink-0">
- <Button
- variant="ghost"
- size="sm"
- onClick={() => downloadProcessedFile(file)}
- className="h-7 w-7 p-0"
- title="单独下载"
- >
- <Download className="h-3 w-3" />
- </Button>
- </div>
- </div>
- ))}
- </div>
- </div>
- </CardContent>
- </Card>
- )}
- {/* 使用说明 */}
- <Card>
- <CardHeader>
- <CardTitle>使用说明(增强版)</CardTitle>
- </CardHeader>
- <CardContent>
- <div className="space-y-3 text-sm">
- <div>
- <h4 className="font-medium mb-1">1. 准备Word模板</h4>
- <p className="text-muted-foreground">
- 使用 {'{字段名}'} 格式作为文本占位符,使用 {'{%图片名}'} 格式作为图片占位符
- </p>
- </div>
-
- <div>
- <h4 className="font-medium mb-1">2. 设置图片尺寸(新增)</h4>
- <p className="text-muted-foreground">
- 使用"图片尺寸设置"按钮设置图片最大尺寸,系统将自动限制所有图片尺寸并保留长宽比例
- </p>
- </div>
-
- <div>
- <h4 className="font-medium mb-1">3. 准备Excel数据</h4>
- <p className="text-muted-foreground">
- Excel文件第一行为表头,列名应与Word模板中的字段名对应
- </p>
- </div>
-
- <div>
- <h4 className="font-medium mb-1">4. 准备图片压缩包</h4>
- <p className="text-muted-foreground">
- 压缩包结构:第一层为序号文件夹(1,2,3...对应Excel行),第二层为图片文件(文件名对应模板中的图片名)
- </p>
- </div>
-
- <div>
- <h4 className="font-medium mb-1">5. 图片命名规则</h4>
- <p className="text-muted-foreground">
- 例如:模板中使用 {'{%logo}'},则图片文件应命名为 logo.jpg/png等
- </p>
- </div>
- </div>
- </CardContent>
- </Card>
- {/* 注意事项 */}
- <Card>
- <CardHeader>
- <CardTitle className="flex items-center gap-2">
- <AlertCircle className="h-5 w-5" />
- 注意事项
- </CardTitle>
- </CardHeader>
- <CardContent>
- <div className="space-y-2 text-sm">
- <p>• Word模板中的字段名必须与Excel表头完全匹配</p>
- <p>• 图片文件名必须与模板中的图片占位符匹配(不含扩展名)</p>
- <p>• 文件夹序号必须与Excel行号对应(第1行对应文件夹"1")</p>
- <p>• 如果图片不存在,对应位置将留空</p>
- <p>• 支持jpg、jpeg、png、gif、bmp、webp格式图片</p>
- <p>• 图片占位符使用 {'{%图片名%}'} 格式,如 {'{%logo%}'}</p>
- </div>
- </CardContent>
- </Card>
- {/* 图片查看器模态框 */}
- <Dialog open={selectedImage !== null} onOpenChange={closeImagePreview}>
- <DialogContent className="max-w-4xl max-h-[90vh] p-0">
- <DialogHeader className="px-6 py-4 border-b">
- <DialogTitle className="flex items-center justify-between">
- <span>图片预览</span>
- <div className="flex items-center gap-2 text-sm text-muted-foreground">
- <span>{selectedImage?.folder} / {selectedImage?.name}</span>
- <span>({currentImageIndex + 1} / {allImages.length})</span>
- </div>
- </DialogTitle>
- </DialogHeader>
-
- {selectedImage && (
- <div className="relative">
- <div className="flex items-center justify-center p-4">
- <img
- src={selectedImage.url}
- alt={selectedImage.name}
- className="max-w-full max-h-[70vh] object-contain"
- />
- </div>
-
- {/* 导航按钮 */}
- {allImages.length > 1 && (
- <>
- <Button
- variant="ghost"
- size="icon"
- className="absolute left-2 top-1/2 -translate-y-1/2"
- onClick={() => navigateImage('prev')}
- >
- <ChevronLeft className="h-5 w-5" />
- </Button>
- <Button
- variant="ghost"
- size="icon"
- className="absolute right-2 top-1/2 -translate-y-1/2"
- onClick={() => navigateImage('next')}
- >
- <ChevronRight className="h-5 w-5" />
- </Button>
- </>
- )}
-
- {/* 底部信息 */}
- <div className="px-6 py-3 border-t bg-gray-50">
- <div className="flex items-center justify-between text-sm">
- <div>
- <span className="font-medium">文件名:</span> {selectedImage.name}
- </div>
- <Button
- variant="ghost"
- size="sm"
- onClick={() => {
- const a = document.createElement('a');
- a.href = selectedImage.url;
- a.download = selectedImage.name;
- a.click();
- }}
- >
- <Download className="h-4 w-4 mr-2" />
- 下载图片
- </Button>
- </div>
- </div>
- </div>
- )}
- </DialogContent>
- </Dialog>
- </div>
- );
- }
|