mirror of
https://github.com/patdelphi/suanming.git
synced 2026-02-28 05:33:11 +08:00
feat: 重新开发PDF下载功能
- 使用puppeteer替代html-pdf库实现真正的PDF生成 - 改进Markdown到HTML的转换逻辑,支持表格和列表 - 添加PDF专用CSS样式,优化打印效果 - 修复Buffer到字符串的转换问题 - 优化puppeteer启动参数,提高稳定性 - 支持A4格式,适当边距和分页控制 - 测试验证PDF生成功能正常工作
This commit is contained in:
706
package-lock.json
generated
706
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -62,6 +62,7 @@
|
|||||||
"lucide-react": "^0.364.0",
|
"lucide-react": "^0.364.0",
|
||||||
"next-themes": "^0.4.4",
|
"next-themes": "^0.4.4",
|
||||||
"nodemon": "^3.0.2",
|
"nodemon": "^3.0.2",
|
||||||
|
"puppeteer": "^24.17.0",
|
||||||
"react": "^18.3.1",
|
"react": "^18.3.1",
|
||||||
"react-day-picker": "8.10.1",
|
"react-day-picker": "8.10.1",
|
||||||
"react-dom": "^18.3.1",
|
"react-dom": "^18.3.1",
|
||||||
|
|||||||
@@ -2,10 +2,9 @@ const express = require('express');
|
|||||||
const { authenticate } = require('../middleware/auth.cjs');
|
const { authenticate } = require('../middleware/auth.cjs');
|
||||||
const { dbManager } = require('../database/index.cjs');
|
const { dbManager } = require('../database/index.cjs');
|
||||||
|
|
||||||
// 临时注释生成器导入,先测试路由基本功能
|
const { generateMarkdown } = require('../services/generators/markdownGenerator.cjs');
|
||||||
// const { generateMarkdown } = require('../services/generators/markdownGenerator.cjs');
|
const { generatePDF } = require('../services/generators/pdfGenerator.cjs');
|
||||||
// const { generatePDF } = require('../services/generators/pdfGenerator.cjs');
|
const { generatePNG } = require('../services/generators/pngGenerator.cjs');
|
||||||
// const { generatePNG } = require('../services/generators/pngGenerator.cjs');
|
|
||||||
|
|
||||||
const router = express.Router();
|
const router = express.Router();
|
||||||
|
|
||||||
@@ -50,43 +49,60 @@ router.post('/', authenticate, async (req, res) => {
|
|||||||
let fileExtension;
|
let fileExtension;
|
||||||
let filename;
|
let filename;
|
||||||
|
|
||||||
// 生成文件名
|
// 生成文件名 - 格式:"分析类型_用户名_日期_时间"(使用分析记录创建时间)
|
||||||
const timestamp = new Date().toISOString().slice(0, 19).replace(/[:-]/g, '');
|
// 优先使用分析记录的创建时间,如果没有则使用当前时间
|
||||||
const analysisTypeLabel = {
|
let analysisDate;
|
||||||
'bazi': '八字命理',
|
if (analysisData.created_at) {
|
||||||
'ziwei': '紫微斗数',
|
analysisDate = new Date(analysisData.created_at);
|
||||||
'yijing': '易经占卜'
|
} else if (analysisData.basic_info?.created_at) {
|
||||||
}[analysisType];
|
analysisDate = new Date(analysisData.basic_info.created_at);
|
||||||
|
} else {
|
||||||
|
// 如果没有创建时间,使用当前时间作为备用
|
||||||
|
analysisDate = new Date();
|
||||||
|
}
|
||||||
|
|
||||||
const baseFilename = `${analysisTypeLabel}_${userName || 'user'}_${timestamp}`;
|
const year = analysisDate.getFullYear();
|
||||||
|
const month = String(analysisDate.getMonth() + 1).padStart(2, '0');
|
||||||
|
const day = String(analysisDate.getDate()).padStart(2, '0');
|
||||||
|
const hour = String(analysisDate.getHours()).padStart(2, '0');
|
||||||
|
const minute = String(analysisDate.getMinutes()).padStart(2, '0');
|
||||||
|
const second = String(analysisDate.getSeconds()).padStart(2, '0');
|
||||||
|
|
||||||
|
const dateStr = `${year}-${month}-${day}`;
|
||||||
|
const timeStr = `${hour}${minute}${second}`;
|
||||||
|
|
||||||
|
// 分析类型映射
|
||||||
|
const analysisTypeMap = {
|
||||||
|
'bazi': '八字命理',
|
||||||
|
'ziwei': '紫微斗数',
|
||||||
|
'yijing': '易经占卜'
|
||||||
|
};
|
||||||
|
|
||||||
|
const analysisTypeName = analysisTypeMap[analysisType] || analysisType;
|
||||||
|
const baseFilename = `${analysisTypeName}_${userName || 'user'}_${dateStr}_${timeStr}`;
|
||||||
|
// 文件名格式: 八字命理_午饭_2025-08-21_133105
|
||||||
|
|
||||||
try {
|
try {
|
||||||
switch (format) {
|
switch (format) {
|
||||||
case 'markdown':
|
case 'markdown':
|
||||||
// 临时简单实现
|
fileBuffer = await generateMarkdown(analysisData, analysisType, userName);
|
||||||
const markdownContent = `# ${analysisTypeLabel}分析报告\n\n**姓名:** ${userName || '用户'}\n**生成时间:** ${new Date().toLocaleString('zh-CN')}\n\n## 分析结果\n\n这是一个测试文件。\n\n---\n\n*本报告由神机阁AI命理分析平台生成*`;
|
|
||||||
fileBuffer = Buffer.from(markdownContent, 'utf8');
|
|
||||||
contentType = 'text/markdown';
|
contentType = 'text/markdown';
|
||||||
fileExtension = 'md';
|
fileExtension = 'md';
|
||||||
filename = `${baseFilename}.md`;
|
filename = `${baseFilename}.md`;
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case 'pdf':
|
case 'pdf':
|
||||||
// 临时返回HTML内容
|
fileBuffer = await generatePDF(analysisData, analysisType, userName);
|
||||||
const htmlContent = `<!DOCTYPE html><html><head><meta charset="UTF-8"><title>${analysisTypeLabel}分析报告</title></head><body><h1>${analysisTypeLabel}分析报告</h1><p><strong>姓名:</strong>${userName || '用户'}</p><p><strong>生成时间:</strong>${new Date().toLocaleString('zh-CN')}</p><h2>分析结果</h2><p>这是一个测试文件。</p></body></html>`;
|
contentType = 'application/pdf';
|
||||||
fileBuffer = Buffer.from(htmlContent, 'utf8');
|
fileExtension = 'pdf';
|
||||||
contentType = 'text/html';
|
filename = `${baseFilename}.pdf`;
|
||||||
fileExtension = 'html';
|
|
||||||
filename = `${baseFilename}.html`;
|
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case 'png':
|
case 'png':
|
||||||
// 临时返回SVG内容
|
fileBuffer = await generatePNG(analysisData, analysisType, userName);
|
||||||
const svgContent = `<svg width="400" height="300" xmlns="http://www.w3.org/2000/svg"><rect width="400" height="300" fill="#f9f9f9"/><text x="200" y="50" text-anchor="middle" font-size="24" fill="#dc2626">${analysisTypeLabel}分析报告</text><text x="200" y="100" text-anchor="middle" font-size="16" fill="#333">姓名:${userName || '用户'}</text><text x="200" y="130" text-anchor="middle" font-size="14" fill="#666">生成时间:${new Date().toLocaleString('zh-CN')}</text><text x="200" y="180" text-anchor="middle" font-size="16" fill="#333">这是一个测试文件</text></svg>`;
|
contentType = 'image/png';
|
||||||
fileBuffer = Buffer.from(svgContent, 'utf8');
|
fileExtension = 'png';
|
||||||
contentType = 'image/svg+xml';
|
filename = `${baseFilename}.png`;
|
||||||
fileExtension = 'svg';
|
|
||||||
filename = `${baseFilename}.svg`;
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
} catch (generationError) {
|
} catch (generationError) {
|
||||||
|
|||||||
@@ -1,44 +1,177 @@
|
|||||||
/**
|
/**
|
||||||
* PDF格式生成器
|
* PDF格式生成器
|
||||||
* 将分析结果转换为PDF文档
|
* 将分析结果转换为PDF文档
|
||||||
* 使用html-pdf库进行转换
|
* 使用puppeteer进行HTML到PDF的转换
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
const puppeteer = require('puppeteer');
|
||||||
|
const { generateMarkdown } = require('./markdownGenerator.cjs');
|
||||||
|
|
||||||
const generatePDF = async (analysisData, analysisType, userName) => {
|
const generatePDF = async (analysisData, analysisType, userName) => {
|
||||||
|
let browser;
|
||||||
try {
|
try {
|
||||||
// 生成HTML内容
|
// 生成Markdown内容
|
||||||
const htmlContent = generateHTML(analysisData, analysisType, userName);
|
const markdownBuffer = await generateMarkdown(analysisData, analysisType, userName);
|
||||||
|
|
||||||
// 由于html-pdf库需要额外安装,这里先返回HTML转PDF的占位符
|
// 将Buffer转换为字符串
|
||||||
// 在实际部署时需要安装 html-pdf 或 puppeteer
|
const markdownString = Buffer.isBuffer(markdownBuffer) ? markdownBuffer.toString('utf8') : String(markdownBuffer);
|
||||||
|
|
||||||
// 临时解决方案:返回HTML内容作为PDF(实际应该转换为PDF)
|
// 将Markdown转换为HTML
|
||||||
const Buffer = require('buffer').Buffer;
|
const htmlContent = convertMarkdownToHTML(markdownString, analysisType, userName);
|
||||||
return Buffer.from(htmlContent, 'utf8');
|
|
||||||
|
|
||||||
// 正式实现应该是:
|
// 启动puppeteer浏览器
|
||||||
// const pdf = require('html-pdf');
|
browser = await puppeteer.launch({
|
||||||
// return new Promise((resolve, reject) => {
|
headless: 'new',
|
||||||
// pdf.create(htmlContent, {
|
args: [
|
||||||
// format: 'A4',
|
'--no-sandbox',
|
||||||
// border: {
|
'--disable-setuid-sandbox',
|
||||||
// top: '0.5in',
|
'--disable-dev-shm-usage',
|
||||||
// right: '0.5in',
|
'--disable-gpu',
|
||||||
// bottom: '0.5in',
|
'--no-first-run',
|
||||||
// left: '0.5in'
|
'--disable-extensions',
|
||||||
// }
|
'--disable-plugins',
|
||||||
// }).toBuffer((err, buffer) => {
|
'--disable-images',
|
||||||
// if (err) reject(err);
|
'--disable-javascript',
|
||||||
// else resolve(buffer);
|
'--run-all-compositor-stages-before-draw',
|
||||||
// });
|
'--disable-background-timer-throttling',
|
||||||
// });
|
'--disable-renderer-backgrounding',
|
||||||
|
'--disable-backgrounding-occluded-windows',
|
||||||
|
'--disable-ipc-flooding-protection'
|
||||||
|
],
|
||||||
|
timeout: 30000
|
||||||
|
});
|
||||||
|
|
||||||
|
const page = await browser.newPage();
|
||||||
|
|
||||||
|
// 设置页面内容
|
||||||
|
await page.setContent(htmlContent, {
|
||||||
|
waitUntil: 'networkidle0'
|
||||||
|
});
|
||||||
|
|
||||||
|
// 生成PDF
|
||||||
|
const pdfBuffer = await page.pdf({
|
||||||
|
format: 'A4',
|
||||||
|
margin: {
|
||||||
|
top: '20mm',
|
||||||
|
right: '15mm',
|
||||||
|
bottom: '20mm',
|
||||||
|
left: '15mm'
|
||||||
|
},
|
||||||
|
printBackground: true,
|
||||||
|
preferCSSPageSize: true
|
||||||
|
});
|
||||||
|
|
||||||
|
return pdfBuffer;
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('生成PDF失败:', error);
|
console.error('生成PDF失败:', error);
|
||||||
throw error;
|
throw error;
|
||||||
|
} finally {
|
||||||
|
if (browser) {
|
||||||
|
await browser.close();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 将Markdown内容转换为适合PDF的HTML
|
||||||
|
*/
|
||||||
|
const convertMarkdownToHTML = (markdownContent, analysisType, userName) => {
|
||||||
|
// 预处理:分离表格
|
||||||
|
const lines = markdownContent.split('\n');
|
||||||
|
let html = '';
|
||||||
|
let inTable = false;
|
||||||
|
let tableRows = [];
|
||||||
|
|
||||||
|
for (let i = 0; i < lines.length; i++) {
|
||||||
|
const line = lines[i];
|
||||||
|
|
||||||
|
// 检测表格开始
|
||||||
|
if (line.includes('|') && line.includes('---')) {
|
||||||
|
inTable = true;
|
||||||
|
// 添加表格头(前一行)
|
||||||
|
if (i > 0 && lines[i-1].includes('|')) {
|
||||||
|
const headerCells = lines[i-1].split('|').map(cell => cell.trim()).filter(cell => cell);
|
||||||
|
tableRows.push('<tr>' + headerCells.map(cell => `<th>${cell}</th>`).join('') + '</tr>');
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 处理表格行
|
||||||
|
if (inTable && line.includes('|')) {
|
||||||
|
const cells = line.split('|').map(cell => cell.trim()).filter(cell => cell);
|
||||||
|
if (cells.length > 0) {
|
||||||
|
tableRows.push('<tr>' + cells.map(cell => `<td>${cell}</td>`).join('') + '</tr>');
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 表格结束
|
||||||
|
if (inTable && !line.includes('|')) {
|
||||||
|
html += '<table>' + tableRows.join('') + '</table>\n';
|
||||||
|
tableRows = [];
|
||||||
|
inTable = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 处理非表格行
|
||||||
|
if (!inTable) {
|
||||||
|
html += line + '\n';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 处理未结束的表格
|
||||||
|
if (tableRows.length > 0) {
|
||||||
|
html += '<table>' + tableRows.join('') + '</table>\n';
|
||||||
|
}
|
||||||
|
|
||||||
|
// Markdown到HTML转换
|
||||||
|
html = html
|
||||||
|
// 标题转换
|
||||||
|
.replace(/^# (.+)$/gm, '<h1>$1</h1>')
|
||||||
|
.replace(/^## (.+)$/gm, '<h2>$1</h2>')
|
||||||
|
.replace(/^### (.+)$/gm, '<h3>$1</h3>')
|
||||||
|
.replace(/^#### (.+)$/gm, '<h4>$1</h4>')
|
||||||
|
// 加粗文本
|
||||||
|
.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')
|
||||||
|
// 处理列表
|
||||||
|
.replace(/^- (.+)$/gm, '<li>$1</li>')
|
||||||
|
// 将连续的li包装在ul中
|
||||||
|
.replace(/(<li>.*<\/li>\s*)+/gs, (match) => {
|
||||||
|
return '<ul>' + match + '</ul>';
|
||||||
|
})
|
||||||
|
// 水平分割线
|
||||||
|
.replace(/^---$/gm, '<hr>')
|
||||||
|
// 段落处理
|
||||||
|
.replace(/\n\s*\n/g, '</p><p>')
|
||||||
|
.replace(/^(?!<[h1-6]|<ul|<table|<hr)(.+)$/gm, '<p>$1</p>')
|
||||||
|
// 清理多余的p标签
|
||||||
|
.replace(/<p><\/p>/g, '')
|
||||||
|
.replace(/<p>(<[^>]+>)/g, '$1')
|
||||||
|
.replace(/(<\/[^>]+>)<\/p>/g, '$1')
|
||||||
|
// 换行处理
|
||||||
|
.replace(/\n/g, '');
|
||||||
|
|
||||||
|
// 包装在完整的HTML文档中
|
||||||
|
return `
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="zh-CN">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<title>${getAnalysisTypeLabel(analysisType)}分析报告</title>
|
||||||
|
<style>
|
||||||
|
${getPDFCSS()}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div class="container">
|
||||||
|
${html}
|
||||||
|
</div>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
`;
|
||||||
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 生成HTML内容
|
* 生成HTML内容
|
||||||
*/
|
*/
|
||||||
@@ -617,7 +750,156 @@ const getAnalysisTypeLabel = (analysisType) => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 获取CSS样式
|
* 获取PDF专用CSS样式
|
||||||
|
*/
|
||||||
|
const getPDFCSS = () => {
|
||||||
|
return `
|
||||||
|
* {
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
box-sizing: border-box;
|
||||||
|
}
|
||||||
|
|
||||||
|
body {
|
||||||
|
font-family: 'Microsoft YaHei', '微软雅黑', 'SimSun', '宋体', Arial, sans-serif;
|
||||||
|
line-height: 1.6;
|
||||||
|
color: #333;
|
||||||
|
background-color: white;
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.container {
|
||||||
|
max-width: 100%;
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
h1 {
|
||||||
|
font-size: 24px;
|
||||||
|
color: #2c3e50;
|
||||||
|
text-align: center;
|
||||||
|
margin: 20px 0;
|
||||||
|
padding: 15px;
|
||||||
|
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||||
|
color: white;
|
||||||
|
border-radius: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
h2 {
|
||||||
|
font-size: 18px;
|
||||||
|
color: #34495e;
|
||||||
|
margin: 20px 0 10px 0;
|
||||||
|
padding: 10px 0;
|
||||||
|
border-bottom: 2px solid #3498db;
|
||||||
|
page-break-after: avoid;
|
||||||
|
}
|
||||||
|
|
||||||
|
h3 {
|
||||||
|
font-size: 16px;
|
||||||
|
color: #2980b9;
|
||||||
|
margin: 15px 0 8px 0;
|
||||||
|
padding-left: 10px;
|
||||||
|
border-left: 4px solid #3498db;
|
||||||
|
page-break-after: avoid;
|
||||||
|
}
|
||||||
|
|
||||||
|
h4 {
|
||||||
|
font-size: 14px;
|
||||||
|
color: #27ae60;
|
||||||
|
margin: 12px 0 6px 0;
|
||||||
|
page-break-after: avoid;
|
||||||
|
}
|
||||||
|
|
||||||
|
p {
|
||||||
|
margin: 8px 0;
|
||||||
|
line-height: 1.6;
|
||||||
|
text-align: justify;
|
||||||
|
}
|
||||||
|
|
||||||
|
strong {
|
||||||
|
color: #2c3e50;
|
||||||
|
font-weight: bold;
|
||||||
|
}
|
||||||
|
|
||||||
|
ul, ol {
|
||||||
|
margin: 10px 0;
|
||||||
|
padding-left: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
li {
|
||||||
|
margin: 4px 0;
|
||||||
|
line-height: 1.5;
|
||||||
|
}
|
||||||
|
|
||||||
|
table {
|
||||||
|
width: 100%;
|
||||||
|
border-collapse: collapse;
|
||||||
|
margin: 15px 0;
|
||||||
|
font-size: 11px;
|
||||||
|
page-break-inside: avoid;
|
||||||
|
}
|
||||||
|
|
||||||
|
th, td {
|
||||||
|
border: 1px solid #bdc3c7;
|
||||||
|
padding: 8px;
|
||||||
|
text-align: left;
|
||||||
|
}
|
||||||
|
|
||||||
|
th {
|
||||||
|
background-color: #ecf0f1;
|
||||||
|
font-weight: bold;
|
||||||
|
color: #2c3e50;
|
||||||
|
}
|
||||||
|
|
||||||
|
tr:nth-child(even) {
|
||||||
|
background-color: #f8f9fa;
|
||||||
|
}
|
||||||
|
|
||||||
|
.section {
|
||||||
|
margin: 20px 0;
|
||||||
|
page-break-inside: avoid;
|
||||||
|
}
|
||||||
|
|
||||||
|
.page-break {
|
||||||
|
page-break-before: always;
|
||||||
|
}
|
||||||
|
|
||||||
|
.no-break {
|
||||||
|
page-break-inside: avoid;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 打印优化 */
|
||||||
|
@page {
|
||||||
|
margin: 20mm 15mm;
|
||||||
|
size: A4;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media print {
|
||||||
|
body {
|
||||||
|
font-size: 11px;
|
||||||
|
}
|
||||||
|
|
||||||
|
h1 {
|
||||||
|
font-size: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
h2 {
|
||||||
|
font-size: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
h3 {
|
||||||
|
font-size: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.section {
|
||||||
|
break-inside: avoid;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
`;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取原有CSS样式(保持兼容性)
|
||||||
*/
|
*/
|
||||||
const getCSS = () => {
|
const getCSS = () => {
|
||||||
return `
|
return `
|
||||||
|
|||||||
@@ -266,6 +266,16 @@ const CompleteYijingAnalysis: React.FC<CompleteYijingAnalysisProps> = ({
|
|||||||
<div className="min-h-screen bg-gradient-to-br from-red-50 to-yellow-50 py-8">
|
<div className="min-h-screen bg-gradient-to-br from-red-50 to-yellow-50 py-8">
|
||||||
<div className="max-w-7xl mx-auto px-4 space-y-8">
|
<div className="max-w-7xl mx-auto px-4 space-y-8">
|
||||||
|
|
||||||
|
{/* 下载按钮 */}
|
||||||
|
<div className="flex justify-end">
|
||||||
|
<DownloadButton
|
||||||
|
analysisData={analysisData}
|
||||||
|
analysisType="yijing"
|
||||||
|
userName={question ? `占卜_${question.substring(0, 10)}` : 'user'}
|
||||||
|
className="sticky top-4 z-10"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
{/* 标题和基本信息 */}
|
{/* 标题和基本信息 */}
|
||||||
<Card className="chinese-card-decoration dragon-corner border-2 border-yellow-400">
|
<Card className="chinese-card-decoration dragon-corner border-2 border-yellow-400">
|
||||||
<CardHeader className="text-center">
|
<CardHeader className="text-center">
|
||||||
@@ -722,15 +732,7 @@ const CompleteYijingAnalysis: React.FC<CompleteYijingAnalysisProps> = ({
|
|||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
{/* 下载按钮 */}
|
|
||||||
<div className="flex justify-end mb-8">
|
|
||||||
<DownloadButton
|
|
||||||
analysisData={analysisData}
|
|
||||||
analysisType="yijing"
|
|
||||||
userName={question ? `占卜_${question.substring(0, 10)}` : 'user'}
|
|
||||||
className="sticky top-4 z-10"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* 免责声明 */}
|
{/* 免责声明 */}
|
||||||
<Card className="chinese-card-decoration border-2 border-gray-300">
|
<Card className="chinese-card-decoration border-2 border-gray-300">
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import React, { useState } from 'react';
|
import React, { useState } from 'react';
|
||||||
|
import { createPortal } from 'react-dom';
|
||||||
import { Download, FileText, FileImage, File, Loader2, ChevronDown } from 'lucide-react';
|
import { Download, FileText, FileImage, File, Loader2, ChevronDown } from 'lucide-react';
|
||||||
import { ChineseButton } from './ChineseButton';
|
import { ChineseButton } from './ChineseButton';
|
||||||
import { cn } from '../../lib/utils';
|
import { cn } from '../../lib/utils';
|
||||||
@@ -111,7 +112,28 @@ const DownloadButton: React.FC<DownloadButtonProps> = ({
|
|||||||
|
|
||||||
// 获取文件名(从响应头或生成默认名称)
|
// 获取文件名(从响应头或生成默认名称)
|
||||||
const contentDisposition = response.headers.get('Content-Disposition');
|
const contentDisposition = response.headers.get('Content-Disposition');
|
||||||
let filename = `${getAnalysisTypeLabel()}_${userName || 'user'}_${new Date().toISOString().slice(0, 10)}.${format === 'markdown' ? 'md' : format}`;
|
// 生成与后端一致的文件名格式:分析类型_用户名_日期_时间(使用分析记录创建时间)
|
||||||
|
// 优先使用分析记录的创建时间,如果没有则使用当前时间
|
||||||
|
let analysisDate;
|
||||||
|
if (analysisData.created_at) {
|
||||||
|
analysisDate = new Date(analysisData.created_at);
|
||||||
|
} else if (analysisData.basic_info?.created_at) {
|
||||||
|
analysisDate = new Date(analysisData.basic_info.created_at);
|
||||||
|
} else {
|
||||||
|
// 如果没有创建时间,使用当前时间作为备用
|
||||||
|
analysisDate = new Date();
|
||||||
|
}
|
||||||
|
|
||||||
|
const year = analysisDate.getFullYear();
|
||||||
|
const month = String(analysisDate.getMonth() + 1).padStart(2, '0');
|
||||||
|
const day = String(analysisDate.getDate()).padStart(2, '0');
|
||||||
|
const hour = String(analysisDate.getHours()).padStart(2, '0');
|
||||||
|
const minute = String(analysisDate.getMinutes()).padStart(2, '0');
|
||||||
|
const second = String(analysisDate.getSeconds()).padStart(2, '0');
|
||||||
|
|
||||||
|
const dateStr = `${year}-${month}-${day}`;
|
||||||
|
const timeStr = `${hour}${minute}${second}`;
|
||||||
|
let filename = `${getAnalysisTypeLabel()}_${userName || 'user'}_${dateStr}_${timeStr}.${format === 'markdown' ? 'md' : format}`;
|
||||||
|
|
||||||
if (contentDisposition) {
|
if (contentDisposition) {
|
||||||
const filenameMatch = contentDisposition.match(/filename[^;=\n]*=(['"]?)([^'"\n]*?)\1/);
|
const filenameMatch = contentDisposition.match(/filename[^;=\n]*=(['"]?)([^'"\n]*?)\1/);
|
||||||
@@ -182,89 +204,91 @@ const DownloadButton: React.FC<DownloadButtonProps> = ({
|
|||||||
className="flex items-center space-x-2 bg-gradient-to-r from-yellow-500 to-yellow-600 hover:from-yellow-600 hover:to-yellow-700 text-white border-0 shadow-lg"
|
className="flex items-center space-x-2 bg-gradient-to-r from-yellow-500 to-yellow-600 hover:from-yellow-600 hover:to-yellow-700 text-white border-0 shadow-lg"
|
||||||
>
|
>
|
||||||
{isDownloading ? (
|
{isDownloading ? (
|
||||||
<Loader2 className="h-4 w-4 animate-spin" />
|
<Loader2 className="h-3 w-3 sm:h-4 sm:w-4 animate-spin" />
|
||||||
) : (
|
) : (
|
||||||
<Download className="h-4 w-4" />
|
<Download className="h-3 w-3 sm:h-4 sm:w-4" />
|
||||||
)}
|
)}
|
||||||
<span className="font-medium">
|
<span className="font-medium hidden sm:inline">
|
||||||
{isDownloading ? `正在生成${getFormatLabel(downloadingFormat!)}...` : '下载分析结果'}
|
{isDownloading ? `正在生成${getFormatLabel(downloadingFormat!)}...` : '下载'}
|
||||||
</span>
|
</span>
|
||||||
<ChevronDown className={cn(
|
<ChevronDown className={cn(
|
||||||
'h-4 w-4 transition-transform duration-200',
|
'h-3 w-3 sm:h-4 sm:w-4 transition-transform duration-200',
|
||||||
showDropdown ? 'rotate-180' : ''
|
showDropdown ? 'rotate-180' : ''
|
||||||
)} />
|
)} />
|
||||||
</ChineseButton>
|
</ChineseButton>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* 下拉菜单 */}
|
{/* 使用Portal渲染弹出层到body,脱离父容器限制 */}
|
||||||
{showDropdown && (
|
{showDropdown && createPortal(
|
||||||
<div className="absolute top-full left-0 mt-2 w-80 bg-white rounded-lg shadow-xl border border-gray-200 z-50">
|
<>
|
||||||
<div className="p-3 border-b border-gray-100">
|
{/* 背景遮罩 */}
|
||||||
<h3 className="font-bold text-gray-800 text-sm">选择下载格式</h3>
|
<div
|
||||||
<p className="text-xs text-gray-600 mt-1">{getAnalysisTypeLabel()}分析结果</p>
|
className="fixed inset-0 z-[999998] bg-black bg-opacity-20"
|
||||||
</div>
|
onClick={() => setShowDropdown(false)}
|
||||||
|
/>
|
||||||
|
|
||||||
<div className="p-2">
|
{/* 弹出层 - 固定定位到屏幕中央 */}
|
||||||
{formatOptions.map((option) => {
|
<div className="fixed top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 w-80 bg-white rounded-lg shadow-xl border border-gray-200 z-[999999] max-h-96 overflow-y-auto">
|
||||||
const Icon = option.icon;
|
<div className="p-3 border-b border-gray-100">
|
||||||
const isCurrentlyDownloading = isDownloading && downloadingFormat === option.format;
|
<h3 className="font-bold text-gray-800 text-sm">选择下载格式</h3>
|
||||||
|
<p className="text-xs text-gray-600 mt-1">{getAnalysisTypeLabel()}分析结果</p>
|
||||||
return (
|
</div>
|
||||||
<button
|
|
||||||
key={option.format}
|
<div className="p-2">
|
||||||
onClick={() => handleDownload(option.format)}
|
{formatOptions.map((option) => {
|
||||||
disabled={disabled || isDownloading}
|
const Icon = option.icon;
|
||||||
className={cn(
|
const isCurrentlyDownloading = isDownloading && downloadingFormat === option.format;
|
||||||
'w-full flex items-center space-x-3 p-3 rounded-lg transition-all duration-200',
|
|
||||||
option.bgColor,
|
return (
|
||||||
'border border-transparent hover:border-gray-300',
|
<button
|
||||||
disabled || isDownloading ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer'
|
key={option.format}
|
||||||
)}
|
onClick={() => handleDownload(option.format)}
|
||||||
>
|
disabled={disabled || isDownloading}
|
||||||
<div className={cn(
|
className={cn(
|
||||||
'w-10 h-10 rounded-full flex items-center justify-center',
|
'w-full flex items-center space-x-3 p-3 rounded-lg transition-all duration-200',
|
||||||
option.bgColor.replace('hover:', '').replace('bg-', 'bg-').replace('-50', '-100')
|
option.bgColor,
|
||||||
)}>
|
'border border-transparent hover:border-gray-300',
|
||||||
{isCurrentlyDownloading ? (
|
disabled || isDownloading ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer'
|
||||||
<Loader2 className={cn('h-5 w-5 animate-spin', option.color)} />
|
|
||||||
) : (
|
|
||||||
<Icon className={cn('h-5 w-5', option.color)} />
|
|
||||||
)}
|
)}
|
||||||
</div>
|
>
|
||||||
|
<div className={cn(
|
||||||
<div className="flex-1 text-left">
|
'w-10 h-10 rounded-full flex items-center justify-center',
|
||||||
<div className={cn('font-medium text-sm', option.color)}>
|
option.bgColor.replace('hover:', '').replace('bg-', 'bg-').replace('-50', '-100')
|
||||||
{option.label}
|
)}>
|
||||||
|
{isCurrentlyDownloading ? (
|
||||||
|
<Loader2 className={cn('h-5 w-5 animate-spin', option.color)} />
|
||||||
|
) : (
|
||||||
|
<Icon className={cn('h-5 w-5', option.color)} />
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
<div className="text-xs text-gray-600 mt-1">
|
|
||||||
{option.description}
|
<div className="flex-1 text-left">
|
||||||
|
<div className={cn('font-medium text-sm', option.color)}>
|
||||||
|
{option.label}
|
||||||
|
</div>
|
||||||
|
<div className="text-xs text-gray-600 mt-1">
|
||||||
|
{option.description}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
|
||||||
|
{isCurrentlyDownloading && (
|
||||||
{isCurrentlyDownloading && (
|
<div className="text-xs text-gray-500">
|
||||||
<div className="text-xs text-gray-500">
|
生成中...
|
||||||
生成中...
|
</div>
|
||||||
</div>
|
)}
|
||||||
)}
|
</button>
|
||||||
</button>
|
);
|
||||||
);
|
})}
|
||||||
})}
|
</div>
|
||||||
|
|
||||||
|
<div className="p-3 border-t border-gray-100 bg-gray-50 rounded-b-lg">
|
||||||
|
<p className="text-xs text-gray-500 text-center">
|
||||||
|
💡 提示:PDF和PNG格式包含完整的视觉设计,Markdown格式便于编辑
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
</>,
|
||||||
<div className="p-3 border-t border-gray-100 bg-gray-50 rounded-b-lg">
|
document.body
|
||||||
<p className="text-xs text-gray-500 text-center">
|
|
||||||
💡 提示:PDF和PNG格式包含完整的视觉设计,Markdown格式便于编辑
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* 点击外部关闭下拉菜单 */}
|
|
||||||
{showDropdown && (
|
|
||||||
<div
|
|
||||||
className="fixed inset-0 z-40"
|
|
||||||
onClick={() => setShowDropdown(false)}
|
|
||||||
/>
|
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -6,8 +6,9 @@ import { ChineseCard, ChineseCardContent, ChineseCardHeader, ChineseCardTitle }
|
|||||||
import { ChineseEmpty } from '../components/ui/ChineseEmpty';
|
import { ChineseEmpty } from '../components/ui/ChineseEmpty';
|
||||||
import { ChineseLoading } from '../components/ui/ChineseLoading';
|
import { ChineseLoading } from '../components/ui/ChineseLoading';
|
||||||
import AnalysisResultDisplay from '../components/AnalysisResultDisplay';
|
import AnalysisResultDisplay from '../components/AnalysisResultDisplay';
|
||||||
|
import DownloadButton from '../components/ui/DownloadButton';
|
||||||
import { toast } from 'sonner';
|
import { toast } from 'sonner';
|
||||||
import { History, Calendar, User, Sparkles, Star, Compass, Eye, Trash2 } from 'lucide-react';
|
import { History, Calendar, User, Sparkles, Star, Compass, Eye, Trash2, Download } from 'lucide-react';
|
||||||
import { NumerologyReading } from '../types';
|
import { NumerologyReading } from '../types';
|
||||||
import { cn } from '../lib/utils';
|
import { cn } from '../lib/utils';
|
||||||
|
|
||||||
@@ -261,22 +262,32 @@ const HistoryPage: React.FC = () => {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex items-center space-x-2 self-end sm:self-center">
|
<div className="flex items-center space-x-1 sm:space-x-2 self-end sm:self-center">
|
||||||
<ChineseButton
|
<ChineseButton
|
||||||
variant="outline"
|
variant="outline"
|
||||||
size="md"
|
size="md"
|
||||||
onClick={() => handleViewReading(reading)}
|
onClick={() => handleViewReading(reading)}
|
||||||
|
className="px-3 sm:px-6 text-xs sm:text-sm"
|
||||||
>
|
>
|
||||||
<Eye className="mr-1 h-4 w-4" />
|
<Eye className="mr-1 h-3 w-3 sm:h-4 sm:w-4" />
|
||||||
查看
|
<span className="hidden sm:inline">查看</span>
|
||||||
</ChineseButton>
|
</ChineseButton>
|
||||||
|
<DownloadButton
|
||||||
|
analysisData={{
|
||||||
|
...(reading.analysis || reading.results),
|
||||||
|
created_at: reading.created_at
|
||||||
|
}}
|
||||||
|
analysisType={reading.reading_type as 'bazi' | 'ziwei' | 'yijing'}
|
||||||
|
userName={reading.name}
|
||||||
|
className="min-h-[44px] px-3 sm:px-6 py-2.5 text-xs sm:text-sm"
|
||||||
|
/>
|
||||||
<ChineseButton
|
<ChineseButton
|
||||||
variant="ghost"
|
variant="ghost"
|
||||||
size="md"
|
size="md"
|
||||||
onClick={() => handleDeleteReading(reading.id)}
|
onClick={() => handleDeleteReading(reading.id)}
|
||||||
className="text-red-600 hover:text-red-700 hover:bg-red-50"
|
className="text-red-600 hover:text-red-700 hover:bg-red-50 px-2 sm:px-3"
|
||||||
>
|
>
|
||||||
<Trash2 className="h-4 w-4" />
|
<Trash2 className="h-3 w-3 sm:h-4 sm:w-4" />
|
||||||
</ChineseButton>
|
</ChineseButton>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
Reference in New Issue
Block a user