SevdanurGenc's picture
Upload 300 files
9438a57 verified
Raw History Blame Contribute Delete
4.25 kB
"""HTML raporlarını PDF'e çevirir.
Web arayüzü sandbox'ındaki (Playwright + Chromium) başsız tarayıcı kullanılır: Docker kipinde ağ erişimi kapalı
geçici bir konteynerde, yerel kipte LTA_CHROMIUM ile verilen Chromium'la. Tarayıcı yoksa False döner; HTML
raporlar yine de kaydedilir (içlerindeki "PDF olarak kaydet" düğmesi tarayıcıdan PDF üretir).
"""
from __future__ import annotations
import shutil
import uuid
from pathlib import Path
from typing import Optional
from .config import settings
from .sandbox.executor import get_executor
PDF_JS = r"""
const path = require('path');
let pw;
try { pw = require('playwright-core'); } catch (e) { pw = require('@playwright/test'); }
(async () => {
const opts = process.env.LTA_CHROMIUM
? { executablePath: process.env.LTA_CHROMIUM, args: ['--no-sandbox', '--disable-gpu'] }
: { args: ['--no-sandbox'] };
const browser = await pw.chromium.launch(opts);
const page = await browser.newPage({ viewport: { width: 1000, height: 1400 } });
for (const f of process.argv.slice(2)) {
await page.goto('file://' + path.resolve(f), { waitUntil: 'load' });
await page.emulateMedia({ media: 'print' });
// Kapalı ayrıntılar PDF'te görünmez: hepsini aç; yazdırma komut dosyalarını etkisiz bırak
const title = await page.evaluate(async () => {
document.querySelectorAll('details').forEach((d) => { d.open = true; });
document.documentElement.classList.add('pdf');
if (document.fonts && document.fonts.ready) await document.fonts.ready;
return document.title || '';
});
const esc = (s) => s.replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]));
await page.pdf({
path: f.replace(/\.html$/, '.pdf'), format: 'A4', printBackground: true,
margin: { top: '12mm', bottom: '14mm', left: '11mm', right: '11mm' },
displayHeaderFooter: true,
headerTemplate: '<span></span>',
footerTemplate: '<div style="width:100%;font:8px Segoe UI,Arial,sans-serif;color:#8590a6;padding:0 11mm;display:flex;justify-content:space-between">'
+ '<span>' + esc(title).slice(0, 120) + '</span><span><span class="pageNumber"></span> / <span class="totalPages"></span></span></div>',
});
console.log('ok ' + f);
}
await browser.close();
})().catch((e) => { console.error(String(e && e.stack || e)); process.exit(1); });
"""
def html_to_pdf(files: list[Path], timeout: Optional[int] = None) -> tuple[list[Path], str]:
"""Verilen HTML dosyalarının yanına aynı adlı .pdf dosyalarını yazar. Dönüş: (üretilen PDF'ler, günlük)."""
if not files:
return [], ""
timeout = timeout or min(1800, 90 + 8 * len(files))
ex = get_executor()
wd = settings.work_root / f"pdf-{uuid.uuid4().hex[:10]}"
wd.mkdir(parents=True, exist_ok=True)
try:
names = []
for i, f in enumerate(files):
name = f"r{i}.html"
shutil.copyfile(f, wd / name)
names.append(name)
(wd / "pdf.js").write_text(PDF_JS, encoding="utf-8")
cmd = f"ln -sfn {ex.node_toolchain}/node_modules node_modules && node pdf.js {' '.join(names)} 2>&1"
res = ex.run(cmd, wd, timeout, image=settings.docker_image_ui)
out: list[Path] = []
for f, name in zip(files, names):
pdf = wd / name.replace(".html", ".pdf")
if pdf.exists() and pdf.stat().st_size > 1000:
target = f.with_suffix(".pdf")
shutil.copyfile(pdf, target)
out.append(target)
return out, res.combined[-1500:]
except Exception as e: # noqa: BLE001
return [], str(e)
finally:
shutil.rmtree(wd, ignore_errors=True)
def render_pdf(html: str, name: str = "rapor") -> Optional[bytes]:
"""Tek bir HTML belgesini PDF'e çevirir; tarayıcı yoksa ya da başarısız olursa None."""
wd = settings.work_root / f"pdfsrc-{uuid.uuid4().hex[:10]}"
wd.mkdir(parents=True, exist_ok=True)
try:
f = wd / f"{name}.html"
f.write_text(html, encoding="utf-8")
out, _ = html_to_pdf([f])
return out[0].read_bytes() if out else None
finally:
shutil.rmtree(wd, ignore_errors=True)