206 lines
6.8 KiB
Python
206 lines
6.8 KiB
Python
# -*- coding: utf-8 -*-
|
|
"""
|
|
동물약 복약안내 PDF 렌더러
|
|
"""
|
|
|
|
import os
|
|
import json
|
|
import asyncio
|
|
from datetime import datetime
|
|
from typing import List, Dict, Optional
|
|
from jinja2 import Environment, FileSystemLoader
|
|
|
|
|
|
class AnimalMedRenderer:
|
|
"""동물약 복약안내 PDF 렌더링 API"""
|
|
|
|
def __init__(self, data_path: str = None, template_path: str = None):
|
|
base_dir = os.path.dirname(os.path.dirname(__file__))
|
|
|
|
self.data_path = data_path or os.path.join(base_dir, 'data', 'mock_drugs.json')
|
|
self.template_dir = template_path or os.path.join(base_dir, 'templates')
|
|
|
|
# Jinja2 템플릿 환경
|
|
self.jinja_env = Environment(
|
|
loader=FileSystemLoader(self.template_dir),
|
|
autoescape=True
|
|
)
|
|
|
|
# 약품 데이터 로드
|
|
self._load_drug_data()
|
|
|
|
def _load_drug_data(self):
|
|
"""약품 데이터 로드"""
|
|
with open(self.data_path, 'r', encoding='utf-8') as f:
|
|
data = json.load(f)
|
|
|
|
self.drugs = {drug['apc_code']: drug for drug in data['drugs']}
|
|
self.metadata = data.get('metadata', {})
|
|
|
|
def get_drug(self, apc_code: str) -> Optional[Dict]:
|
|
"""APC 코드로 약품 조회"""
|
|
return self.drugs.get(apc_code)
|
|
|
|
def get_drugs(self, apc_codes: List[str]) -> List[Dict]:
|
|
"""여러 APC 코드로 약품 조회"""
|
|
result = []
|
|
for code in apc_codes:
|
|
drug = self.get_drug(code)
|
|
if drug:
|
|
result.append(drug)
|
|
return result
|
|
|
|
def render_html(
|
|
self,
|
|
apc_codes: List[str],
|
|
patient_name: str = "홍길동",
|
|
pet_name: str = "뽀삐",
|
|
pet_species: str = "개",
|
|
pet_age: str = "3세",
|
|
pharmacy_name: str = "청춘약국",
|
|
pharmacy_tel: str = "033-481-7390",
|
|
pharmacy_address: str = "강원 양구군 양구읍 양구새싹로 7-3"
|
|
) -> str:
|
|
"""
|
|
APC 코드 배열을 받아 HTML 복약안내문 렌더링
|
|
|
|
Args:
|
|
apc_codes: 약품 APC 코드 배열
|
|
patient_name: 보호자명
|
|
pet_name: 반려동물 이름
|
|
pet_species: 동물 종류
|
|
pet_age: 나이
|
|
pharmacy_name: 약국명
|
|
pharmacy_tel: 전화번호
|
|
pharmacy_address: 주소
|
|
|
|
Returns:
|
|
렌더링된 HTML 문자열
|
|
"""
|
|
drugs = self.get_drugs(apc_codes)
|
|
|
|
if not drugs:
|
|
raise ValueError(f"유효한 약품을 찾을 수 없습니다: {apc_codes}")
|
|
|
|
template = self.jinja_env.get_template('medication_guide.html')
|
|
|
|
html = template.render(
|
|
drugs=drugs,
|
|
patient_name=patient_name,
|
|
pet_name=pet_name,
|
|
pet_species=pet_species,
|
|
pet_age=pet_age,
|
|
pharmacy_name=pharmacy_name,
|
|
pharmacy_tel=pharmacy_tel,
|
|
pharmacy_address=pharmacy_address,
|
|
issue_date=datetime.now().strftime('%Y년 %m월 %d일')
|
|
)
|
|
|
|
return html
|
|
|
|
def render_to_pdf(
|
|
self,
|
|
apc_codes: List[str],
|
|
output_path: str = None,
|
|
**kwargs
|
|
) -> Dict:
|
|
"""
|
|
APC 코드 배열을 받아 PDF 복약안내문 생성
|
|
|
|
Args:
|
|
apc_codes: 약품 APC 코드 배열
|
|
output_path: 출력 PDF 경로
|
|
**kwargs: render_html에 전달할 추가 인자
|
|
|
|
Returns:
|
|
{
|
|
'success': True,
|
|
'pdf_path': '/path/to/file.pdf',
|
|
'drug_count': 3,
|
|
'drugs': [약품명 목록]
|
|
}
|
|
"""
|
|
# HTML 렌더링
|
|
html_content = self.render_html(apc_codes, **kwargs)
|
|
|
|
# 출력 경로
|
|
if not output_path:
|
|
import tempfile
|
|
import time
|
|
output_path = os.path.join(tempfile.gettempdir(), f'animal_med_{int(time.time())}.pdf')
|
|
|
|
# HTML → PDF
|
|
async def _convert():
|
|
from playwright.async_api import async_playwright
|
|
|
|
async with async_playwright() as p:
|
|
browser = await p.chromium.launch(headless=True)
|
|
|
|
# A4 크기 viewport (210mm x 297mm @ 96dpi)
|
|
page = await browser.new_page(viewport={'width': 794, 'height': 1123})
|
|
|
|
await page.set_content(html_content, wait_until='networkidle')
|
|
|
|
# 콘텐츠 크기 확인
|
|
rect = await page.evaluate('''() => {
|
|
const el = document.querySelector('.container');
|
|
const rect = el.getBoundingClientRect();
|
|
return { width: rect.width, height: rect.height };
|
|
}''')
|
|
|
|
# A4 (595 x 842 pt)에 맞는 scale 계산
|
|
content_width_pt = rect['width'] * 0.75
|
|
content_height_pt = rect['height'] * 0.75
|
|
|
|
scale_x = 595 / content_width_pt if content_width_pt > 0 else 1
|
|
scale_y = 842 / content_height_pt if content_height_pt > 0 else 1
|
|
scale = min(scale_x, scale_y, 1.0) # 최대 1.0
|
|
|
|
# PDF 생성
|
|
await page.pdf(
|
|
path=output_path,
|
|
format='A4',
|
|
print_background=True,
|
|
margin={'top': '0', 'right': '0', 'bottom': '0', 'left': '0'},
|
|
scale=scale
|
|
)
|
|
|
|
await browser.close()
|
|
|
|
try:
|
|
try:
|
|
loop = asyncio.get_running_loop()
|
|
except RuntimeError:
|
|
loop = None
|
|
|
|
if loop and loop.is_running():
|
|
import concurrent.futures
|
|
with concurrent.futures.ThreadPoolExecutor() as executor:
|
|
future = executor.submit(asyncio.run, _convert())
|
|
future.result()
|
|
else:
|
|
asyncio.run(_convert())
|
|
|
|
drugs = self.get_drugs(apc_codes)
|
|
|
|
return {
|
|
'success': True,
|
|
'pdf_path': output_path,
|
|
'drug_count': len(drugs),
|
|
'drugs': [d['name'] for d in drugs]
|
|
}
|
|
except Exception as e:
|
|
return {'success': False, 'error': str(e)}
|
|
|
|
def list_drugs(self) -> List[Dict]:
|
|
"""모든 약품 목록 반환"""
|
|
return [
|
|
{
|
|
'apc_code': d['apc_code'],
|
|
'name': d['name'],
|
|
'category': d['category'],
|
|
'target_animal': d['target_animal']
|
|
}
|
|
for d in self.drugs.values()
|
|
]
|