實作完整分享、刪除、下載報告功能
This commit is contained in:
89
lib/config.ts
Normal file
89
lib/config.ts
Normal file
@@ -0,0 +1,89 @@
|
||||
/**
|
||||
* 應用配置工具類
|
||||
* 用於管理環境變量和應用設置
|
||||
*/
|
||||
|
||||
// 資料庫配置
|
||||
export const dbConfig = {
|
||||
host: process.env.DB_HOST || 'mysql.theaken.com',
|
||||
port: parseInt(process.env.DB_PORT || '33306'),
|
||||
user: process.env.DB_USER || 'root',
|
||||
password: process.env.DB_PASSWORD || 'zh6161168',
|
||||
database: process.env.DB_NAME || 'db_AI_scoring',
|
||||
charset: 'utf8mb4',
|
||||
timezone: '+08:00',
|
||||
acquireTimeout: 60000,
|
||||
timeout: 60000,
|
||||
reconnect: true,
|
||||
multipleStatements: true,
|
||||
} as const
|
||||
|
||||
// AI 配置
|
||||
export const aiConfig = {
|
||||
geminiApiKey: process.env.GEMINI_API_KEY || 'AIzaSyAN3pEJr_Vn2xkCidGZAq9eQqsMVvpj8g4',
|
||||
modelName: process.env.GEMINI_MODEL || 'gemini-1.5-pro',
|
||||
maxTokens: parseInt(process.env.GEMINI_MAX_TOKENS || '8192'),
|
||||
} as const
|
||||
|
||||
// 獲取應用基礎 URL
|
||||
export function getAppUrl(): string {
|
||||
// 在客戶端使用 window.location.origin
|
||||
if (typeof window !== 'undefined') {
|
||||
return window.location.origin
|
||||
}
|
||||
|
||||
// 在服務端使用環境變量,如果沒有設置則使用 localhost:12024
|
||||
return process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:12024'
|
||||
}
|
||||
|
||||
// 獲取應用名稱
|
||||
export function getAppName(): string {
|
||||
return process.env.NEXT_PUBLIC_APP_NAME || 'AI 智能評審系統'
|
||||
}
|
||||
|
||||
// 生成分享連結
|
||||
export function generateShareUrl(evaluationId: string): string {
|
||||
const baseUrl = getAppUrl()
|
||||
return `${baseUrl}/results?id=${evaluationId}`
|
||||
}
|
||||
|
||||
// 生成當前頁面連結
|
||||
export function getCurrentUrl(): string {
|
||||
if (typeof window !== 'undefined') {
|
||||
return window.location.href
|
||||
}
|
||||
return getAppUrl()
|
||||
}
|
||||
|
||||
// 環境變量配置
|
||||
export const config = {
|
||||
appUrl: getAppUrl(),
|
||||
appName: getAppName(),
|
||||
isDevelopment: process.env.NODE_ENV === 'development',
|
||||
isProduction: process.env.NODE_ENV === 'production',
|
||||
database: dbConfig,
|
||||
ai: aiConfig,
|
||||
} as const
|
||||
|
||||
// 配置驗證
|
||||
export function validateConfig(): { isValid: boolean; errors: string[] } {
|
||||
const errors: string[] = []
|
||||
|
||||
// 檢查必要的環境變量
|
||||
if (!process.env.GEMINI_API_KEY) {
|
||||
errors.push('GEMINI_API_KEY 環境變量未設置')
|
||||
}
|
||||
|
||||
if (!process.env.DB_HOST) {
|
||||
errors.push('DB_HOST 環境變量未設置')
|
||||
}
|
||||
|
||||
if (!process.env.DB_NAME) {
|
||||
errors.push('DB_NAME 環境變量未設置')
|
||||
}
|
||||
|
||||
return {
|
||||
isValid: errors.length === 0,
|
||||
errors
|
||||
}
|
||||
}
|
@@ -1,19 +1,5 @@
|
||||
import mysql from 'mysql2/promise';
|
||||
|
||||
// 資料庫配置
|
||||
const dbConfig = {
|
||||
host: process.env.DB_HOST || 'mysql.theaken.com',
|
||||
port: parseInt(process.env.DB_PORT || '33306'),
|
||||
user: process.env.DB_USER || 'root',
|
||||
password: process.env.DB_PASSWORD || 'zh6161168',
|
||||
database: process.env.DB_NAME || 'db_AI_scoring',
|
||||
charset: 'utf8mb4',
|
||||
timezone: '+08:00',
|
||||
acquireTimeout: 60000,
|
||||
timeout: 60000,
|
||||
reconnect: true,
|
||||
multipleStatements: true,
|
||||
};
|
||||
import { dbConfig } from './config';
|
||||
|
||||
// 建立連接池
|
||||
const pool = mysql.createPool({
|
||||
|
@@ -1,7 +1,7 @@
|
||||
import { GoogleGenerativeAI } from '@google/generative-ai';
|
||||
import { aiConfig } from '../config';
|
||||
|
||||
const API_KEY = 'AIzaSyAN3pEJr_Vn2xkCidGZAq9eQqsMVvpj8g4';
|
||||
const genAI = new GoogleGenerativeAI(API_KEY);
|
||||
const genAI = new GoogleGenerativeAI(aiConfig.geminiApiKey);
|
||||
|
||||
export interface CriteriaItem {
|
||||
id: string;
|
||||
|
504
lib/utils/html-pdf-generator.ts
Normal file
504
lib/utils/html-pdf-generator.ts
Normal file
@@ -0,0 +1,504 @@
|
||||
import puppeteer from 'puppeteer';
|
||||
|
||||
export interface PDFReportData {
|
||||
projectTitle: string;
|
||||
overallScore: number;
|
||||
totalPossible: number;
|
||||
grade: string;
|
||||
analysisDate: string;
|
||||
criteria: Array<{
|
||||
name: string;
|
||||
score: number;
|
||||
maxScore: number;
|
||||
weight: number;
|
||||
weightedScore: number;
|
||||
percentage: number;
|
||||
feedback: string;
|
||||
strengths: string[];
|
||||
improvements: string[];
|
||||
}>;
|
||||
overview: {
|
||||
excellentItems: number;
|
||||
improvementItems: number;
|
||||
overallPerformance: number;
|
||||
};
|
||||
improvementSuggestions: {
|
||||
overallSuggestions: string;
|
||||
maintainStrengths: Array<{
|
||||
title: string;
|
||||
description: string;
|
||||
}>;
|
||||
keyImprovements: Array<{
|
||||
title: string;
|
||||
subtitle?: string;
|
||||
description?: string;
|
||||
suggestions: string[];
|
||||
}>;
|
||||
actionPlan: Array<{
|
||||
phase: string;
|
||||
description: string;
|
||||
}>;
|
||||
};
|
||||
}
|
||||
|
||||
export class HTMLPDFGenerator {
|
||||
private generateHTML(data: PDFReportData): string {
|
||||
return `
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-TW">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>AI 智能評審報告</title>
|
||||
<style>
|
||||
* {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: 'Microsoft JhengHei', 'PingFang TC', 'Helvetica Neue', Arial, sans-serif;
|
||||
line-height: 1.6;
|
||||
color: #333;
|
||||
background: white;
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
.header {
|
||||
text-align: center;
|
||||
margin-bottom: 30px;
|
||||
border-bottom: 2px solid #0891b2;
|
||||
padding-bottom: 20px;
|
||||
}
|
||||
|
||||
.title {
|
||||
font-size: 28px;
|
||||
font-weight: bold;
|
||||
color: #0891b2;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.subtitle {
|
||||
font-size: 16px;
|
||||
color: #666;
|
||||
}
|
||||
|
||||
.section {
|
||||
margin-bottom: 25px;
|
||||
}
|
||||
|
||||
.section-title {
|
||||
font-size: 18px;
|
||||
font-weight: bold;
|
||||
color: #0891b2;
|
||||
margin-bottom: 15px;
|
||||
border-left: 4px solid #0891b2;
|
||||
padding-left: 10px;
|
||||
}
|
||||
|
||||
.score-box {
|
||||
background: #f8f9fa;
|
||||
border: 2px solid #0891b2;
|
||||
border-radius: 8px;
|
||||
padding: 20px;
|
||||
text-align: center;
|
||||
margin: 20px 0;
|
||||
display: inline-block;
|
||||
min-width: 200px;
|
||||
}
|
||||
|
||||
.score-number {
|
||||
font-size: 36px;
|
||||
font-weight: bold;
|
||||
color: #0891b2;
|
||||
}
|
||||
|
||||
.score-grade {
|
||||
font-size: 20px;
|
||||
font-weight: bold;
|
||||
color: #10b981;
|
||||
margin-top: 5px;
|
||||
}
|
||||
|
||||
.stats-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, 1fr);
|
||||
gap: 20px;
|
||||
margin: 20px 0;
|
||||
}
|
||||
|
||||
.stat-card {
|
||||
background: #f8f9fa;
|
||||
border-radius: 8px;
|
||||
padding: 15px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.stat-number {
|
||||
font-size: 24px;
|
||||
font-weight: bold;
|
||||
color: #0891b2;
|
||||
}
|
||||
|
||||
.stat-label {
|
||||
font-size: 14px;
|
||||
color: #666;
|
||||
margin-top: 5px;
|
||||
}
|
||||
|
||||
.criteria-table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
margin: 20px 0;
|
||||
}
|
||||
|
||||
.criteria-table th,
|
||||
.criteria-table td {
|
||||
border: 1px solid #ddd;
|
||||
padding: 12px;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.criteria-table th {
|
||||
background: #0891b2;
|
||||
color: white;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.criteria-table tr:nth-child(even) {
|
||||
background: #f8f9fa;
|
||||
}
|
||||
|
||||
.criteria-item {
|
||||
background: white;
|
||||
border: 1px solid #e5e7eb;
|
||||
border-radius: 8px;
|
||||
padding: 20px;
|
||||
margin: 15px 0;
|
||||
}
|
||||
|
||||
.criteria-name {
|
||||
font-size: 16px;
|
||||
font-weight: bold;
|
||||
color: #0891b2;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.criteria-score {
|
||||
font-size: 18px;
|
||||
font-weight: bold;
|
||||
color: #10b981;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.criteria-feedback {
|
||||
margin: 10px 0;
|
||||
padding: 10px;
|
||||
background: #f8f9fa;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.strengths, .improvements {
|
||||
margin: 10px 0;
|
||||
}
|
||||
|
||||
.strengths h4, .improvements h4 {
|
||||
color: #10b981;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.improvements h4 {
|
||||
color: #f59e0b;
|
||||
}
|
||||
|
||||
.strengths ul, .improvements ul {
|
||||
margin-left: 20px;
|
||||
}
|
||||
|
||||
.strengths li, .improvements li {
|
||||
margin: 5px 0;
|
||||
}
|
||||
|
||||
.suggestions-section {
|
||||
background: #f8f9fa;
|
||||
border-radius: 8px;
|
||||
padding: 20px;
|
||||
margin: 20px 0;
|
||||
}
|
||||
|
||||
.suggestion-group {
|
||||
margin: 15px 0;
|
||||
}
|
||||
|
||||
.suggestion-title {
|
||||
font-weight: bold;
|
||||
color: #0891b2;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.suggestion-description {
|
||||
margin: 8px 0;
|
||||
}
|
||||
|
||||
.suggestion-list {
|
||||
margin-left: 20px;
|
||||
}
|
||||
|
||||
.action-plan {
|
||||
background: #e0f2fe;
|
||||
border-radius: 8px;
|
||||
padding: 20px;
|
||||
margin: 20px 0;
|
||||
}
|
||||
|
||||
.action-item {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
margin: 10px 0;
|
||||
}
|
||||
|
||||
.action-number {
|
||||
background: #0891b2;
|
||||
color: white;
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
border-radius: 50%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-weight: bold;
|
||||
margin-right: 12px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.action-content {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.action-phase {
|
||||
font-weight: bold;
|
||||
color: #0891b2;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.footer {
|
||||
margin-top: 40px;
|
||||
padding-top: 20px;
|
||||
border-top: 1px solid #e5e7eb;
|
||||
text-align: center;
|
||||
color: #666;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
@media print {
|
||||
body {
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.page-break {
|
||||
page-break-before: always;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="header">
|
||||
<h1 class="title">AI 智能評審報告</h1>
|
||||
<p class="subtitle">專案名稱:${data.projectTitle}</p>
|
||||
<p class="subtitle">分析日期:${data.analysisDate}</p>
|
||||
</div>
|
||||
|
||||
<div class="section">
|
||||
<h2 class="section-title">總評結果</h2>
|
||||
<div class="score-box">
|
||||
<div class="score-number">${data.overallScore}/${data.totalPossible}</div>
|
||||
<div class="score-grade">${data.grade}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="section">
|
||||
<h2 class="section-title">統計概覽</h2>
|
||||
<div class="stats-grid">
|
||||
<div class="stat-card">
|
||||
<div class="stat-number">${data.overview.excellentItems}</div>
|
||||
<div class="stat-label">優秀項目</div>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<div class="stat-number">${data.overview.improvementItems}</div>
|
||||
<div class="stat-label">待改進項目</div>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<div class="stat-number">${data.overview.overallPerformance}%</div>
|
||||
<div class="stat-label">整體表現</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="section">
|
||||
<h2 class="section-title">評分明細</h2>
|
||||
<table class="criteria-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>評分項目</th>
|
||||
<th>得分</th>
|
||||
<th>權重</th>
|
||||
<th>加權分</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
${data.criteria.map(item => `
|
||||
<tr>
|
||||
<td>${item.name}</td>
|
||||
<td>${item.score}/${item.maxScore}</td>
|
||||
<td>${item.weight}%</td>
|
||||
<td>${item.weightedScore.toFixed(1)}</td>
|
||||
</tr>
|
||||
`).join('')}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div class="section page-break">
|
||||
<h2 class="section-title">詳細分析</h2>
|
||||
${data.criteria.map(item => `
|
||||
<div class="criteria-item">
|
||||
<div class="criteria-name">${item.name}</div>
|
||||
<div class="criteria-score">得分:${item.score}/${item.maxScore} (${item.percentage.toFixed(1)}%)</div>
|
||||
<div class="criteria-feedback">
|
||||
<strong>AI 評語:</strong>${item.feedback}
|
||||
</div>
|
||||
${item.strengths.length > 0 ? `
|
||||
<div class="strengths">
|
||||
<h4>優點:</h4>
|
||||
<ul>
|
||||
${item.strengths.map(strength => `<li>${strength}</li>`).join('')}
|
||||
</ul>
|
||||
</div>
|
||||
` : ''}
|
||||
${item.improvements.length > 0 ? `
|
||||
<div class="improvements">
|
||||
<h4>改進建議:</h4>
|
||||
<ul>
|
||||
${item.improvements.map(improvement => `<li>${improvement}</li>`).join('')}
|
||||
</ul>
|
||||
</div>
|
||||
` : ''}
|
||||
</div>
|
||||
`).join('')}
|
||||
</div>
|
||||
|
||||
<div class="section page-break">
|
||||
<h2 class="section-title">整體改進建議</h2>
|
||||
<div class="suggestions-section">
|
||||
<p>${data.improvementSuggestions.overallSuggestions}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
${data.improvementSuggestions.maintainStrengths.length > 0 ? `
|
||||
<div class="section">
|
||||
<h2 class="section-title">繼續保持的優勢</h2>
|
||||
<div class="suggestions-section">
|
||||
${data.improvementSuggestions.maintainStrengths.map(strength => `
|
||||
<div class="suggestion-group">
|
||||
<div class="suggestion-title">${strength.title}</div>
|
||||
<div class="suggestion-description">${strength.description}</div>
|
||||
</div>
|
||||
`).join('')}
|
||||
</div>
|
||||
</div>
|
||||
` : ''}
|
||||
|
||||
${data.improvementSuggestions.keyImprovements.length > 0 ? `
|
||||
<div class="section page-break">
|
||||
<h2 class="section-title">重點改進方向</h2>
|
||||
<div class="suggestions-section">
|
||||
${data.improvementSuggestions.keyImprovements.map(improvement => `
|
||||
<div class="suggestion-group">
|
||||
<div class="suggestion-title">${improvement.title}</div>
|
||||
${improvement.description ? `<div class="suggestion-description">${improvement.description}</div>` : ''}
|
||||
${improvement.suggestions.length > 0 ? `
|
||||
<div class="suggestion-list">
|
||||
<ul>
|
||||
${improvement.suggestions.map(suggestion => `<li>${suggestion}</li>`).join('')}
|
||||
</ul>
|
||||
</div>
|
||||
` : ''}
|
||||
</div>
|
||||
`).join('')}
|
||||
</div>
|
||||
</div>
|
||||
` : ''}
|
||||
|
||||
${data.improvementSuggestions.actionPlan.length > 0 ? `
|
||||
<div class="section">
|
||||
<h2 class="section-title">下一步行動計劃</h2>
|
||||
<div class="action-plan">
|
||||
${data.improvementSuggestions.actionPlan.map((action, index) => `
|
||||
<div class="action-item">
|
||||
<div class="action-number">${index + 1}</div>
|
||||
<div class="action-content">
|
||||
<div class="action-phase">${action.phase}</div>
|
||||
<div>${action.description}</div>
|
||||
</div>
|
||||
</div>
|
||||
`).join('')}
|
||||
</div>
|
||||
</div>
|
||||
` : ''}
|
||||
|
||||
<div class="footer">
|
||||
<p>本報告由 AI 智能評審系統生成</p>
|
||||
<p>生成時間:${new Date().toLocaleString('zh-TW')}</p>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
`;
|
||||
}
|
||||
|
||||
public async generateReport(data: PDFReportData): Promise<Blob> {
|
||||
const browser = await puppeteer.launch({
|
||||
headless: true,
|
||||
args: [
|
||||
'--no-sandbox',
|
||||
'--disable-setuid-sandbox',
|
||||
'--disable-dev-shm-usage',
|
||||
'--disable-accelerated-2d-canvas',
|
||||
'--no-first-run',
|
||||
'--no-zygote',
|
||||
'--disable-gpu'
|
||||
],
|
||||
timeout: 30000
|
||||
});
|
||||
|
||||
try {
|
||||
const page = await browser.newPage();
|
||||
|
||||
// 設置頁面內容
|
||||
const html = this.generateHTML(data);
|
||||
await page.setContent(html, { waitUntil: 'networkidle0' });
|
||||
|
||||
// 生成 PDF
|
||||
const pdfBuffer = await page.pdf({
|
||||
format: 'A4',
|
||||
printBackground: true,
|
||||
margin: {
|
||||
top: '20mm',
|
||||
right: '20mm',
|
||||
bottom: '20mm',
|
||||
left: '20mm'
|
||||
}
|
||||
});
|
||||
|
||||
return new Blob([pdfBuffer], { type: 'application/pdf' });
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 便捷函數
|
||||
export async function generateHTMLPDFReport(data: PDFReportData): Promise<Blob> {
|
||||
const generator = new HTMLPDFGenerator();
|
||||
return generator.generateReport(data);
|
||||
}
|
319
lib/utils/pdf-generator-chinese.ts
Normal file
319
lib/utils/pdf-generator-chinese.ts
Normal file
@@ -0,0 +1,319 @@
|
||||
import jsPDF from 'jspdf';
|
||||
import 'jspdf-autotable';
|
||||
|
||||
export interface PDFReportData {
|
||||
projectTitle: string;
|
||||
overallScore: number;
|
||||
totalPossible: number;
|
||||
grade: string;
|
||||
analysisDate: string;
|
||||
criteria: Array<{
|
||||
name: string;
|
||||
score: number;
|
||||
maxScore: number;
|
||||
weight: number;
|
||||
weightedScore: number;
|
||||
percentage: number;
|
||||
feedback: string;
|
||||
strengths: string[];
|
||||
improvements: string[];
|
||||
}>;
|
||||
overview: {
|
||||
excellentItems: number;
|
||||
improvementItems: number;
|
||||
overallPerformance: number;
|
||||
};
|
||||
improvementSuggestions: {
|
||||
overallSuggestions: string;
|
||||
maintainStrengths: Array<{
|
||||
title: string;
|
||||
description: string;
|
||||
}>;
|
||||
keyImprovements: Array<{
|
||||
title: string;
|
||||
subtitle?: string;
|
||||
description?: string;
|
||||
suggestions: string[];
|
||||
}>;
|
||||
actionPlan: Array<{
|
||||
phase: string;
|
||||
description: string;
|
||||
}>;
|
||||
};
|
||||
}
|
||||
|
||||
export class ChinesePDFReportGenerator {
|
||||
private doc: jsPDF;
|
||||
private currentY: number = 20;
|
||||
private pageHeight: number = 280;
|
||||
private margin: number = 20;
|
||||
|
||||
constructor() {
|
||||
this.doc = new jsPDF('p', 'mm', 'a4');
|
||||
}
|
||||
|
||||
private addNewPageIfNeeded(requiredSpace: number = 20): void {
|
||||
if (this.currentY + requiredSpace > this.pageHeight) {
|
||||
this.doc.addPage();
|
||||
this.currentY = 20;
|
||||
}
|
||||
}
|
||||
|
||||
private addTitle(text: string, fontSize: number = 16, isBold: boolean = true): void {
|
||||
this.addNewPageIfNeeded(10);
|
||||
this.doc.setFontSize(fontSize);
|
||||
this.doc.setFont('helvetica', isBold ? 'bold' : 'normal');
|
||||
|
||||
// 將中文轉換為可顯示的格式
|
||||
const displayText = this.convertChineseText(text);
|
||||
this.doc.text(displayText, this.margin, this.currentY);
|
||||
this.currentY += fontSize + 5;
|
||||
}
|
||||
|
||||
private addSubtitle(text: string, fontSize: number = 12): void {
|
||||
this.addNewPageIfNeeded(8);
|
||||
this.doc.setFontSize(fontSize);
|
||||
this.doc.setFont('helvetica', 'bold');
|
||||
|
||||
const displayText = this.convertChineseText(text);
|
||||
this.doc.text(displayText, this.margin, this.currentY);
|
||||
this.currentY += fontSize + 3;
|
||||
}
|
||||
|
||||
private addText(text: string, fontSize: number = 10, isBold: boolean = false): void {
|
||||
this.addNewPageIfNeeded(6);
|
||||
this.doc.setFontSize(fontSize);
|
||||
this.doc.setFont('helvetica', isBold ? 'bold' : 'normal');
|
||||
|
||||
const displayText = this.convertChineseText(text);
|
||||
|
||||
// 處理長文本換行
|
||||
const maxWidth = 170;
|
||||
const lines = this.doc.splitTextToSize(displayText, maxWidth);
|
||||
|
||||
for (const line of lines) {
|
||||
this.addNewPageIfNeeded(6);
|
||||
this.doc.text(line, this.margin, this.currentY);
|
||||
this.currentY += 6;
|
||||
}
|
||||
}
|
||||
|
||||
private addBulletList(items: string[], fontSize: number = 10): void {
|
||||
for (const item of items) {
|
||||
this.addNewPageIfNeeded(6);
|
||||
this.doc.setFontSize(fontSize);
|
||||
this.doc.setFont('helvetica', 'normal');
|
||||
|
||||
const displayText = this.convertChineseText(item);
|
||||
this.doc.text(`• ${displayText}`, this.margin + 5, this.currentY);
|
||||
this.currentY += 6;
|
||||
}
|
||||
}
|
||||
|
||||
private addScoreBox(score: number, total: number, grade: string): void {
|
||||
this.addNewPageIfNeeded(25);
|
||||
|
||||
// 繪製分數框
|
||||
this.doc.setFillColor(240, 240, 240);
|
||||
this.doc.rect(this.margin, this.currentY, 50, 20, 'F');
|
||||
|
||||
// 分數文字
|
||||
this.doc.setFontSize(18);
|
||||
this.doc.setFont('helvetica', 'bold');
|
||||
this.doc.text(`${score}/${total}`, this.margin + 5, this.currentY + 12);
|
||||
|
||||
// 等級
|
||||
this.doc.setFontSize(12);
|
||||
this.doc.text(grade, this.margin + 5, this.currentY + 18);
|
||||
|
||||
this.currentY += 25;
|
||||
}
|
||||
|
||||
private addCriteriaTable(criteria: PDFReportData['criteria']): void {
|
||||
this.addNewPageIfNeeded(30);
|
||||
|
||||
// 準備表格數據
|
||||
const tableData = criteria.map(item => [
|
||||
this.convertChineseText(item.name),
|
||||
`${item.score}/${item.maxScore}`,
|
||||
`${item.weight}%`,
|
||||
item.weightedScore.toFixed(1)
|
||||
]);
|
||||
|
||||
// 使用 autoTable 插件創建表格
|
||||
(this.doc as any).autoTable({
|
||||
head: [['評分項目', '得分', '權重', '加權分']],
|
||||
body: tableData,
|
||||
startY: this.currentY,
|
||||
margin: { left: this.margin, right: this.margin },
|
||||
styles: { fontSize: 10 },
|
||||
headStyles: { fillColor: [66, 139, 202] },
|
||||
alternateRowStyles: { fillColor: [245, 245, 245] }
|
||||
});
|
||||
|
||||
// 更新當前 Y 位置
|
||||
this.currentY = (this.doc as any).lastAutoTable.finalY + 10;
|
||||
}
|
||||
|
||||
// 將中文字符轉換為可顯示的格式
|
||||
private convertChineseText(text: string): string {
|
||||
// 簡單的字符替換,將常見的中文字符替換為英文描述
|
||||
const chineseMap: { [key: string]: string } = {
|
||||
'評審結果': 'Evaluation Results',
|
||||
'AI 智能評審報告': 'AI Intelligent Evaluation Report',
|
||||
'專案名稱': 'Project Name',
|
||||
'分析日期': 'Analysis Date',
|
||||
'總評結果': 'Overall Results',
|
||||
'統計概覽': 'Statistical Overview',
|
||||
'優秀項目': 'Excellent Items',
|
||||
'待改進項目': 'Items to Improve',
|
||||
'整體表現': 'Overall Performance',
|
||||
'評分明細': 'Score Details',
|
||||
'評分項目': 'Evaluation Items',
|
||||
'得分': 'Score',
|
||||
'權重': 'Weight',
|
||||
'加權分': 'Weighted Score',
|
||||
'詳細分析': 'Detailed Analysis',
|
||||
'AI 評語': 'AI Comments',
|
||||
'優點': 'Strengths',
|
||||
'改進建議': 'Improvement Suggestions',
|
||||
'整體改進建議': 'Overall Improvement Suggestions',
|
||||
'繼續保持的優勢': 'Maintain Strengths',
|
||||
'重點改進方向': 'Key Improvement Areas',
|
||||
'下一步行動計劃': 'Next Action Plan',
|
||||
'本報告由 AI 智能評審系統生成': 'Generated by AI Intelligent Evaluation System',
|
||||
'生成時間': 'Generated Time',
|
||||
'內容品質': 'Content Quality',
|
||||
'視覺設計': 'Visual Design',
|
||||
'邏輯結構': 'Logical Structure',
|
||||
'創新性': 'Innovation',
|
||||
'實用性': 'Practicality'
|
||||
};
|
||||
|
||||
let result = text;
|
||||
|
||||
// 替換已知的中文詞彙
|
||||
for (const [chinese, english] of Object.entries(chineseMap)) {
|
||||
result = result.replace(new RegExp(chinese, 'g'), english);
|
||||
}
|
||||
|
||||
// 對於其他中文字符,使用 Unicode 轉換
|
||||
result = result.replace(/[\u4e00-\u9fff]/g, (char) => {
|
||||
const code = char.charCodeAt(0);
|
||||
return `[U+${code.toString(16).toUpperCase()}]`;
|
||||
});
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public generateReport(data: PDFReportData): Promise<Blob> {
|
||||
return new Promise((resolve, reject) => {
|
||||
try {
|
||||
// 標題頁
|
||||
this.addTitle('AI Intelligent Evaluation Report', 20);
|
||||
this.addText(`Project Name: ${data.projectTitle}`, 12, true);
|
||||
this.addText(`Analysis Date: ${data.analysisDate}`, 12);
|
||||
this.currentY += 10;
|
||||
|
||||
// 總分顯示
|
||||
this.addSubtitle('Overall Results');
|
||||
this.addScoreBox(data.overallScore, data.totalPossible, data.grade);
|
||||
|
||||
// 統計概覽
|
||||
this.addSubtitle('Statistical Overview');
|
||||
this.addText(`Excellent Items: ${data.overview.excellentItems} items`);
|
||||
this.addText(`Items to Improve: ${data.overview.improvementItems} items`);
|
||||
this.addText(`Overall Performance: ${data.overview.overallPerformance}%`);
|
||||
this.currentY += 10;
|
||||
|
||||
// 評分明細
|
||||
this.addSubtitle('Score Details');
|
||||
this.addCriteriaTable(data.criteria);
|
||||
|
||||
// 詳細分析
|
||||
this.addSubtitle('Detailed Analysis');
|
||||
for (const item of data.criteria) {
|
||||
this.addNewPageIfNeeded(20);
|
||||
this.doc.setFontSize(11);
|
||||
this.doc.setFont('helvetica', 'bold');
|
||||
this.doc.text(this.convertChineseText(item.name), this.margin, this.currentY);
|
||||
this.currentY += 8;
|
||||
|
||||
this.addText(`Score: ${item.score}/${item.maxScore} (${item.percentage.toFixed(1)}%)`, 10);
|
||||
this.addText(`AI Comments: ${item.feedback}`, 10);
|
||||
|
||||
if (item.strengths.length > 0) {
|
||||
this.addText('Strengths:', 10, true);
|
||||
this.addBulletList(item.strengths, 9);
|
||||
}
|
||||
|
||||
if (item.improvements.length > 0) {
|
||||
this.addText('Improvement Suggestions:', 10, true);
|
||||
this.addBulletList(item.improvements, 9);
|
||||
}
|
||||
|
||||
this.currentY += 10;
|
||||
}
|
||||
|
||||
// 改進建議
|
||||
this.addSubtitle('Overall Improvement Suggestions');
|
||||
this.addText(data.improvementSuggestions.overallSuggestions, 10);
|
||||
this.currentY += 10;
|
||||
|
||||
// 保持的優勢
|
||||
if (data.improvementSuggestions.maintainStrengths.length > 0) {
|
||||
this.addSubtitle('Maintain Strengths');
|
||||
for (const strength of data.improvementSuggestions.maintainStrengths) {
|
||||
this.addText(strength.title, 10, true);
|
||||
this.addText(strength.description, 9);
|
||||
this.currentY += 5;
|
||||
}
|
||||
}
|
||||
|
||||
// 重點改進方向
|
||||
if (data.improvementSuggestions.keyImprovements.length > 0) {
|
||||
this.addSubtitle('Key Improvement Areas');
|
||||
for (const improvement of data.improvementSuggestions.keyImprovements) {
|
||||
this.addText(improvement.title, 10, true);
|
||||
if (improvement.description) {
|
||||
this.addText(improvement.description, 9);
|
||||
}
|
||||
if (improvement.suggestions.length > 0) {
|
||||
this.addBulletList(improvement.suggestions, 9);
|
||||
}
|
||||
this.currentY += 5;
|
||||
}
|
||||
}
|
||||
|
||||
// 行動計劃
|
||||
if (data.improvementSuggestions.actionPlan.length > 0) {
|
||||
this.addSubtitle('Next Action Plan');
|
||||
for (let i = 0; i < data.improvementSuggestions.actionPlan.length; i++) {
|
||||
const action = data.improvementSuggestions.actionPlan[i];
|
||||
this.addText(`${i + 1}. ${action.phase}`, 10, true);
|
||||
this.addText(action.description, 9);
|
||||
this.currentY += 5;
|
||||
}
|
||||
}
|
||||
|
||||
// 頁腳
|
||||
this.doc.setFontSize(8);
|
||||
this.doc.setFont('helvetica', 'normal');
|
||||
this.doc.text('Generated by AI Intelligent Evaluation System', this.margin, this.pageHeight - 10);
|
||||
this.doc.text(`Generated Time: ${new Date().toLocaleString('en-US')}`, this.margin + 100, this.pageHeight - 10);
|
||||
|
||||
// 生成 PDF Blob
|
||||
const pdfBlob = this.doc.output('blob');
|
||||
resolve(pdfBlob);
|
||||
} catch (error) {
|
||||
reject(error);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 便捷函數
|
||||
export async function generateChinesePDFReport(data: PDFReportData): Promise<Blob> {
|
||||
const generator = new ChinesePDFReportGenerator();
|
||||
return generator.generateReport(data);
|
||||
}
|
269
lib/utils/pdf-generator.ts
Normal file
269
lib/utils/pdf-generator.ts
Normal file
@@ -0,0 +1,269 @@
|
||||
import jsPDF from 'jspdf';
|
||||
import 'jspdf-autotable';
|
||||
import html2canvas from 'html2canvas';
|
||||
|
||||
export interface PDFReportData {
|
||||
projectTitle: string;
|
||||
overallScore: number;
|
||||
totalPossible: number;
|
||||
grade: string;
|
||||
analysisDate: string;
|
||||
criteria: Array<{
|
||||
name: string;
|
||||
score: number;
|
||||
maxScore: number;
|
||||
weight: number;
|
||||
weightedScore: number;
|
||||
percentage: number;
|
||||
feedback: string;
|
||||
strengths: string[];
|
||||
improvements: string[];
|
||||
}>;
|
||||
overview: {
|
||||
excellentItems: number;
|
||||
improvementItems: number;
|
||||
overallPerformance: number;
|
||||
};
|
||||
improvementSuggestions: {
|
||||
overallSuggestions: string;
|
||||
maintainStrengths: Array<{
|
||||
title: string;
|
||||
description: string;
|
||||
}>;
|
||||
keyImprovements: Array<{
|
||||
title: string;
|
||||
subtitle?: string;
|
||||
description?: string;
|
||||
suggestions: string[];
|
||||
}>;
|
||||
actionPlan: Array<{
|
||||
phase: string;
|
||||
description: string;
|
||||
}>;
|
||||
};
|
||||
}
|
||||
|
||||
export class PDFReportGenerator {
|
||||
private doc: jsPDF;
|
||||
private currentY: number = 20;
|
||||
private pageHeight: number = 280;
|
||||
private margin: number = 20;
|
||||
|
||||
constructor() {
|
||||
this.doc = new jsPDF('p', 'mm', 'a4');
|
||||
// 設置支援中文的默認字體
|
||||
this.doc.setFont('helvetica');
|
||||
}
|
||||
|
||||
private addNewPageIfNeeded(requiredSpace: number = 20): void {
|
||||
if (this.currentY + requiredSpace > this.pageHeight) {
|
||||
this.doc.addPage();
|
||||
this.currentY = 20;
|
||||
}
|
||||
}
|
||||
|
||||
private addTitle(text: string, fontSize: number = 16, isBold: boolean = true): void {
|
||||
this.addNewPageIfNeeded(10);
|
||||
this.doc.setFontSize(fontSize);
|
||||
this.doc.setFont('helvetica', isBold ? 'bold' : 'normal');
|
||||
this.doc.text(text, this.margin, this.currentY);
|
||||
this.currentY += fontSize + 5;
|
||||
}
|
||||
|
||||
private addSubtitle(text: string, fontSize: number = 12): void {
|
||||
this.addNewPageIfNeeded(8);
|
||||
this.doc.setFontSize(fontSize);
|
||||
this.doc.setFont('helvetica', 'bold');
|
||||
this.doc.text(text, this.margin, this.currentY);
|
||||
this.currentY += fontSize + 3;
|
||||
}
|
||||
|
||||
private addText(text: string, fontSize: number = 10, isBold: boolean = false): void {
|
||||
this.addNewPageIfNeeded(6);
|
||||
this.doc.setFontSize(fontSize);
|
||||
this.doc.setFont('helvetica', isBold ? 'bold' : 'normal');
|
||||
|
||||
// 處理長文本換行
|
||||
const maxWidth = 170; // A4 寬度減去邊距
|
||||
const lines = this.doc.splitTextToSize(text, maxWidth);
|
||||
|
||||
for (const line of lines) {
|
||||
this.addNewPageIfNeeded(6);
|
||||
this.doc.text(line, this.margin, this.currentY);
|
||||
this.currentY += 6;
|
||||
}
|
||||
}
|
||||
|
||||
private addBulletList(items: string[], fontSize: number = 10): void {
|
||||
for (const item of items) {
|
||||
this.addNewPageIfNeeded(6);
|
||||
this.doc.setFontSize(fontSize);
|
||||
this.doc.setFont('helvetica', 'normal');
|
||||
this.doc.text(`• ${item}`, this.margin + 5, this.currentY);
|
||||
this.currentY += 6;
|
||||
}
|
||||
}
|
||||
|
||||
private addScoreBox(score: number, total: number, grade: string): void {
|
||||
this.addNewPageIfNeeded(25);
|
||||
|
||||
// 繪製分數框
|
||||
this.doc.setFillColor(240, 240, 240);
|
||||
this.doc.rect(this.margin, this.currentY, 50, 20, 'F');
|
||||
|
||||
// 分數文字
|
||||
this.doc.setFontSize(18);
|
||||
this.doc.setFont('helvetica', 'bold');
|
||||
this.doc.text(`${score}/${total}`, this.margin + 5, this.currentY + 12);
|
||||
|
||||
// 等級
|
||||
this.doc.setFontSize(12);
|
||||
this.doc.text(grade, this.margin + 5, this.currentY + 18);
|
||||
|
||||
this.currentY += 25;
|
||||
}
|
||||
|
||||
private addCriteriaTable(criteria: PDFReportData['criteria']): void {
|
||||
this.addNewPageIfNeeded(30);
|
||||
|
||||
// 表頭
|
||||
this.doc.setFontSize(10);
|
||||
this.doc.setFont('helvetica', 'bold');
|
||||
this.doc.text('評分項目', this.margin, this.currentY);
|
||||
this.doc.text('得分', this.margin + 100, this.currentY);
|
||||
this.doc.text('權重', this.margin + 130, this.currentY);
|
||||
this.doc.text('加權分', this.margin + 150, this.currentY);
|
||||
|
||||
this.currentY += 8;
|
||||
|
||||
// 分隔線
|
||||
this.doc.line(this.margin, this.currentY, this.margin + 170, this.currentY);
|
||||
this.currentY += 5;
|
||||
|
||||
// 數據行
|
||||
for (const item of criteria) {
|
||||
this.addNewPageIfNeeded(15);
|
||||
|
||||
this.doc.setFont('helvetica', 'normal');
|
||||
this.doc.text(item.name, this.margin, this.currentY);
|
||||
this.doc.text(`${item.score}/${item.maxScore}`, this.margin + 100, this.currentY);
|
||||
this.doc.text(`${item.weight}%`, this.margin + 130, this.currentY);
|
||||
this.doc.text(item.weightedScore.toFixed(1), this.margin + 150, this.currentY);
|
||||
|
||||
this.currentY += 6;
|
||||
}
|
||||
|
||||
this.currentY += 10;
|
||||
}
|
||||
|
||||
public generateReport(data: PDFReportData): Promise<Blob> {
|
||||
return new Promise((resolve, reject) => {
|
||||
try {
|
||||
// 標題頁
|
||||
this.addTitle('AI 智能評審報告', 20);
|
||||
this.addText(`專案名稱:${data.projectTitle}`, 12, true);
|
||||
this.addText(`分析日期:${data.analysisDate}`, 12);
|
||||
this.currentY += 10;
|
||||
|
||||
// 總分顯示
|
||||
this.addSubtitle('總評結果');
|
||||
this.addScoreBox(data.overallScore, data.totalPossible, data.grade);
|
||||
|
||||
// 統計概覽
|
||||
this.addSubtitle('統計概覽');
|
||||
this.addText(`優秀項目:${data.overview.excellentItems} 項`);
|
||||
this.addText(`待改進項目:${data.overview.improvementItems} 項`);
|
||||
this.addText(`整體表現:${data.overview.overallPerformance}%`);
|
||||
this.currentY += 10;
|
||||
|
||||
// 評分明細
|
||||
this.addSubtitle('評分明細');
|
||||
this.addCriteriaTable(data.criteria);
|
||||
|
||||
// 詳細分析
|
||||
this.addSubtitle('詳細分析');
|
||||
for (const item of data.criteria) {
|
||||
this.addNewPageIfNeeded(20);
|
||||
this.doc.setFontSize(11);
|
||||
this.doc.setFont('helvetica', 'bold');
|
||||
this.doc.text(item.name, this.margin, this.currentY);
|
||||
this.currentY += 8;
|
||||
|
||||
this.addText(`得分:${item.score}/${item.maxScore} (${item.percentage.toFixed(1)}%)`, 10);
|
||||
this.addText(`AI 評語:${item.feedback}`, 10);
|
||||
|
||||
if (item.strengths.length > 0) {
|
||||
this.addText('優點:', 10, true);
|
||||
this.addBulletList(item.strengths, 9);
|
||||
}
|
||||
|
||||
if (item.improvements.length > 0) {
|
||||
this.addText('改進建議:', 10, true);
|
||||
this.addBulletList(item.improvements, 9);
|
||||
}
|
||||
|
||||
this.currentY += 10;
|
||||
}
|
||||
|
||||
// 改進建議
|
||||
this.addSubtitle('整體改進建議');
|
||||
this.addText(data.improvementSuggestions.overallSuggestions, 10);
|
||||
this.currentY += 10;
|
||||
|
||||
// 保持的優勢
|
||||
if (data.improvementSuggestions.maintainStrengths.length > 0) {
|
||||
this.addSubtitle('繼續保持的優勢');
|
||||
for (const strength of data.improvementSuggestions.maintainStrengths) {
|
||||
this.addText(strength.title, 10, true);
|
||||
this.addText(strength.description, 9);
|
||||
this.currentY += 5;
|
||||
}
|
||||
}
|
||||
|
||||
// 重點改進方向
|
||||
if (data.improvementSuggestions.keyImprovements.length > 0) {
|
||||
this.addSubtitle('重點改進方向');
|
||||
for (const improvement of data.improvementSuggestions.keyImprovements) {
|
||||
this.addText(improvement.title, 10, true);
|
||||
if (improvement.description) {
|
||||
this.addText(improvement.description, 9);
|
||||
}
|
||||
if (improvement.suggestions.length > 0) {
|
||||
this.addBulletList(improvement.suggestions, 9);
|
||||
}
|
||||
this.currentY += 5;
|
||||
}
|
||||
}
|
||||
|
||||
// 行動計劃
|
||||
if (data.improvementSuggestions.actionPlan.length > 0) {
|
||||
this.addSubtitle('下一步行動計劃');
|
||||
for (let i = 0; i < data.improvementSuggestions.actionPlan.length; i++) {
|
||||
const action = data.improvementSuggestions.actionPlan[i];
|
||||
this.addText(`${i + 1}. ${action.phase}`, 10, true);
|
||||
this.addText(action.description, 9);
|
||||
this.currentY += 5;
|
||||
}
|
||||
}
|
||||
|
||||
// 頁腳
|
||||
this.doc.setFontSize(8);
|
||||
this.doc.setFont('helvetica', 'normal');
|
||||
this.doc.text('本報告由 AI 智能評審系統生成', this.margin, this.pageHeight - 10);
|
||||
this.doc.text(`生成時間:${new Date().toLocaleString('zh-TW')}`, this.margin + 100, this.pageHeight - 10);
|
||||
|
||||
// 生成 PDF Blob
|
||||
const pdfBlob = this.doc.output('blob');
|
||||
resolve(pdfBlob);
|
||||
} catch (error) {
|
||||
reject(error);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 便捷函數
|
||||
export async function generatePDFReport(data: PDFReportData): Promise<Blob> {
|
||||
const generator = new PDFReportGenerator();
|
||||
return generator.generateReport(data);
|
||||
}
|
Reference in New Issue
Block a user