feat: 重新开发PDF下载功能

- 使用puppeteer替代html-pdf库实现真正的PDF生成
- 改进Markdown到HTML的转换逻辑,支持表格和列表
- 添加PDF专用CSS样式,优化打印效果
- 修复Buffer到字符串的转换问题
- 优化puppeteer启动参数,提高稳定性
- 支持A4格式,适当边距和分页控制
- 测试验证PDF生成功能正常工作
This commit is contained in:
patdelphi
2025-08-21 18:25:11 +08:00
parent b58d0a0b1d
commit 1a58ab62b3
7 changed files with 1162 additions and 154 deletions

706
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -62,6 +62,7 @@
"lucide-react": "^0.364.0",
"next-themes": "^0.4.4",
"nodemon": "^3.0.2",
"puppeteer": "^24.17.0",
"react": "^18.3.1",
"react-day-picker": "8.10.1",
"react-dom": "^18.3.1",

View File

@@ -2,10 +2,9 @@ const express = require('express');
const { authenticate } = require('../middleware/auth.cjs');
const { dbManager } = require('../database/index.cjs');
// 临时注释生成器导入,先测试路由基本功能
// const { generateMarkdown } = require('../services/generators/markdownGenerator.cjs');
// const { generatePDF } = require('../services/generators/pdfGenerator.cjs');
// const { generatePNG } = require('../services/generators/pngGenerator.cjs');
const { generateMarkdown } = require('../services/generators/markdownGenerator.cjs');
const { generatePDF } = require('../services/generators/pdfGenerator.cjs');
const { generatePNG } = require('../services/generators/pngGenerator.cjs');
const router = express.Router();
@@ -50,43 +49,60 @@ router.post('/', authenticate, async (req, res) => {
let fileExtension;
let filename;
// 生成文件名
const timestamp = new Date().toISOString().slice(0, 19).replace(/[:-]/g, '');
const analysisTypeLabel = {
// 生成文件名 - 格式:"分析类型_用户名_日期_时间"(使用分析记录创建时间)
// 优先使用分析记录的创建时间,如果没有则使用当前时间
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}`;
// 分析类型映射
const analysisTypeMap = {
'bazi': '八字命理',
'ziwei': '紫微斗数',
'yijing': '易经占卜'
}[analysisType];
};
const baseFilename = `${analysisTypeLabel}_${userName || 'user'}_${timestamp}`;
const analysisTypeName = analysisTypeMap[analysisType] || analysisType;
const baseFilename = `${analysisTypeName}_${userName || 'user'}_${dateStr}_${timeStr}`;
// 文件名格式: 八字命理_午饭_2025-08-21_133105
try {
switch (format) {
case 'markdown':
// 临时简单实现
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');
fileBuffer = await generateMarkdown(analysisData, analysisType, userName);
contentType = 'text/markdown';
fileExtension = 'md';
filename = `${baseFilename}.md`;
break;
case 'pdf':
// 临时返回HTML内容
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>`;
fileBuffer = Buffer.from(htmlContent, 'utf8');
contentType = 'text/html';
fileExtension = 'html';
filename = `${baseFilename}.html`;
fileBuffer = await generatePDF(analysisData, analysisType, userName);
contentType = 'application/pdf';
fileExtension = 'pdf';
filename = `${baseFilename}.pdf`;
break;
case 'png':
// 临时返回SVG内容
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>`;
fileBuffer = Buffer.from(svgContent, 'utf8');
contentType = 'image/svg+xml';
fileExtension = 'svg';
filename = `${baseFilename}.svg`;
fileBuffer = await generatePNG(analysisData, analysisType, userName);
contentType = 'image/png';
fileExtension = 'png';
filename = `${baseFilename}.png`;
break;
}
} catch (generationError) {

View File

@@ -1,44 +1,177 @@
/**
* PDF格式生成器
* 将分析结果转换为PDF文档
* 使用html-pdf库进行转换
* 使用puppeteer进行HTML到PDF的转换
*/
const puppeteer = require('puppeteer');
const { generateMarkdown } = require('./markdownGenerator.cjs');
const generatePDF = async (analysisData, analysisType, userName) => {
let browser;
try {
// 生成HTML内容
const htmlContent = generateHTML(analysisData, analysisType, userName);
// 生成Markdown内容
const markdownBuffer = await generateMarkdown(analysisData, analysisType, userName);
// 由于html-pdf库需要额外安装这里先返回HTML转PDF的占位符
// 在实际部署时需要安装 html-pdf 或 puppeteer
// 将Buffer转换为字符串
const markdownString = Buffer.isBuffer(markdownBuffer) ? markdownBuffer.toString('utf8') : String(markdownBuffer);
// 临时解决方案返回HTML内容作为PDF实际应该转换为PDF
const Buffer = require('buffer').Buffer;
return Buffer.from(htmlContent, 'utf8');
// 将Markdown转换为HTML
const htmlContent = convertMarkdownToHTML(markdownString, analysisType, userName);
// 正式实现应该是:
// const pdf = require('html-pdf');
// return new Promise((resolve, reject) => {
// pdf.create(htmlContent, {
// format: 'A4',
// border: {
// top: '0.5in',
// right: '0.5in',
// bottom: '0.5in',
// left: '0.5in'
// }
// }).toBuffer((err, buffer) => {
// if (err) reject(err);
// else resolve(buffer);
// });
// });
// 启动puppeteer浏览器
browser = await puppeteer.launch({
headless: 'new',
args: [
'--no-sandbox',
'--disable-setuid-sandbox',
'--disable-dev-shm-usage',
'--disable-gpu',
'--no-first-run',
'--disable-extensions',
'--disable-plugins',
'--disable-images',
'--disable-javascript',
'--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) {
console.error('生成PDF失败:', 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内容
*/
@@ -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 = () => {
return `

View File

@@ -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="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">
<CardHeader className="text-center">
@@ -722,15 +732,7 @@ const CompleteYijingAnalysis: React.FC<CompleteYijingAnalysisProps> = ({
</CardContent>
</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">

View File

@@ -1,4 +1,5 @@
import React, { useState } from 'react';
import { createPortal } from 'react-dom';
import { Download, FileText, FileImage, File, Loader2, ChevronDown } from 'lucide-react';
import { ChineseButton } from './ChineseButton';
import { cn } from '../../lib/utils';
@@ -111,7 +112,28 @@ const DownloadButton: React.FC<DownloadButtonProps> = ({
// 获取文件名(从响应头或生成默认名称)
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) {
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"
>
{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">
{isDownloading ? `正在生成${getFormatLabel(downloadingFormat!)}...` : '下载分析结果'}
<span className="font-medium hidden sm:inline">
{isDownloading ? `正在生成${getFormatLabel(downloadingFormat!)}...` : '下载'}
</span>
<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' : ''
)} />
</ChineseButton>
</div>
{/* 下拉菜单 */}
{showDropdown && (
<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>
<p className="text-xs text-gray-600 mt-1">{getAnalysisTypeLabel()}</p>
</div>
{/* 使用Portal渲染弹出层到body脱离父容器限制 */}
{showDropdown && createPortal(
<>
{/* 背景遮罩 */}
<div
className="fixed inset-0 z-[999998] bg-black bg-opacity-20"
onClick={() => setShowDropdown(false)}
/>
<div className="p-2">
{formatOptions.map((option) => {
const Icon = option.icon;
const isCurrentlyDownloading = isDownloading && downloadingFormat === option.format;
{/* 弹出层 - 固定定位到屏幕中央 */}
<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">
<div className="p-3 border-b border-gray-100">
<h3 className="font-bold text-gray-800 text-sm"></h3>
<p className="text-xs text-gray-600 mt-1">{getAnalysisTypeLabel()}</p>
</div>
return (
<button
key={option.format}
onClick={() => handleDownload(option.format)}
disabled={disabled || isDownloading}
className={cn(
'w-full flex items-center space-x-3 p-3 rounded-lg transition-all duration-200',
option.bgColor,
'border border-transparent hover:border-gray-300',
disabled || isDownloading ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer'
)}
>
<div className={cn(
'w-10 h-10 rounded-full flex items-center justify-center',
option.bgColor.replace('hover:', '').replace('bg-', 'bg-').replace('-50', '-100')
)}>
{isCurrentlyDownloading ? (
<Loader2 className={cn('h-5 w-5 animate-spin', option.color)} />
) : (
<Icon className={cn('h-5 w-5', option.color)} />
<div className="p-2">
{formatOptions.map((option) => {
const Icon = option.icon;
const isCurrentlyDownloading = isDownloading && downloadingFormat === option.format;
return (
<button
key={option.format}
onClick={() => handleDownload(option.format)}
disabled={disabled || isDownloading}
className={cn(
'w-full flex items-center space-x-3 p-3 rounded-lg transition-all duration-200',
option.bgColor,
'border border-transparent hover:border-gray-300',
disabled || isDownloading ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer'
)}
</div>
>
<div className={cn(
'w-10 h-10 rounded-full flex items-center justify-center',
option.bgColor.replace('hover:', '').replace('bg-', 'bg-').replace('-50', '-100')
)}>
{isCurrentlyDownloading ? (
<Loader2 className={cn('h-5 w-5 animate-spin', option.color)} />
) : (
<Icon className={cn('h-5 w-5', option.color)} />
)}
</div>
<div className="flex-1 text-left">
<div className={cn('font-medium text-sm', option.color)}>
{option.label}
<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 className="text-xs text-gray-600 mt-1">
{option.description}
</div>
</div>
{isCurrentlyDownloading && (
<div className="text-xs text-gray-500">
...
</div>
)}
</button>
);
})}
{isCurrentlyDownloading && (
<div className="text-xs text-gray-500">
...
</div>
)}
</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 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>
)}
{/* 点击外部关闭下拉菜单 */}
{showDropdown && (
<div
className="fixed inset-0 z-40"
onClick={() => setShowDropdown(false)}
/>
</>,
document.body
)}
</div>
);

View File

@@ -6,8 +6,9 @@ import { ChineseCard, ChineseCardContent, ChineseCardHeader, ChineseCardTitle }
import { ChineseEmpty } from '../components/ui/ChineseEmpty';
import { ChineseLoading } from '../components/ui/ChineseLoading';
import AnalysisResultDisplay from '../components/AnalysisResultDisplay';
import DownloadButton from '../components/ui/DownloadButton';
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 { cn } from '../lib/utils';
@@ -261,22 +262,32 @@ const HistoryPage: React.FC = () => {
</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
variant="outline"
size="md"
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>
<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
variant="ghost"
size="md"
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>
</div>
</div>