68 lines
2.1 KiB
Python
68 lines
2.1 KiB
Python
import os
|
|
import shutil
|
|
from pathlib import Path
|
|
from typing import Optional
|
|
|
|
class TemplateService:
|
|
"""PDF模板管理服务"""
|
|
|
|
def __init__(self, template_dir: str = "templates/pdf"):
|
|
self.template_dir = Path(template_dir)
|
|
self.template_dir.mkdir(parents=True, exist_ok=True)
|
|
|
|
# 默认模板名称
|
|
self.default_template = "be_u_template.pdf"
|
|
|
|
def get_template_path(self, template_name: Optional[str] = None) -> Path:
|
|
"""获取模板文件路径"""
|
|
if template_name is None:
|
|
template_name = self.default_template
|
|
|
|
template_path = self.template_dir / template_name
|
|
|
|
if not template_path.exists():
|
|
raise FileNotFoundError(f"模板文件不存在: {template_path}")
|
|
|
|
return template_path
|
|
|
|
def save_template(self, source_path: str, template_name: Optional[str] = None) -> str:
|
|
"""
|
|
保存模板文件到系统
|
|
|
|
Args:
|
|
source_path: 源文件路径
|
|
template_name: 模板名称(可选)
|
|
|
|
Returns:
|
|
保存后的模板路径
|
|
"""
|
|
source_path = Path(source_path)
|
|
|
|
if not source_path.exists():
|
|
raise FileNotFoundError(f"源文件不存在: {source_path}")
|
|
|
|
if template_name is None:
|
|
template_name = self.default_template
|
|
|
|
dest_path = self.template_dir / template_name
|
|
|
|
# 复制文件
|
|
shutil.copy2(source_path, dest_path)
|
|
|
|
print(f"✓ 模板已保存: {dest_path}")
|
|
return str(dest_path)
|
|
|
|
def template_exists(self, template_name: Optional[str] = None) -> bool:
|
|
"""检查模板是否存在"""
|
|
if template_name is None:
|
|
template_name = self.default_template
|
|
|
|
return (self.template_dir / template_name).exists()
|
|
|
|
def list_templates(self) -> list:
|
|
"""列出所有可用模板"""
|
|
if not self.template_dir.exists():
|
|
return []
|
|
|
|
return [f.name for f in self.template_dir.glob("*.pdf")]
|