use headless_chrome::Browser; use headless_chrome::types::PrintToPdfOptions; use nanobyte_opentelemetry::rocket::TracingSpan; use rocket::{get, response::stream::ByteStream, fairing::Fairing, fs::NamedFile, futures::TryFutureExt}; use tempfile::NamedTempFile; use tera::Context; use tracing::{info_span, error, debug}; use crate::{chromium::rocket::BrowserHolder, tools::{tera::NanoTera, pdf::PdfStream}}; use urlencoding::encode; // TODO: request-id fn generate_pdf(browser: Browser, file: &NamedTempFile) -> Vec { let tab = browser.new_tab().unwrap(); let path = format!("file://{}", file.path().to_str().unwrap()); info_span!("open_pdf").in_scope(|| { debug!("Render pdf from {}", &path); tab.navigate_to(&path).unwrap().wait_until_navigated().unwrap(); }); let options = PrintToPdfOptions{ margin_bottom: Some(0.0), margin_left: Some(0.0), margin_right: Some(0.0), margin_top: Some(0.0), print_background: Some(true), //paper_width: Some(29.7), //paper_height: Some(21.0), ..PrintToPdfOptions::default() }; //thread::sleep(Duration::from_secs(10)); let bytes = info_span!("print_pdf").in_scope(|| { tab.print_to_pdf(Some(options)).unwrap() }); return bytes; } #[tracing::instrument] fn render_template(template_name: &str, file: &NamedTempFile, tera: NanoTera) { // TODO: handle errors tera.0.render_to("two_column.html.tera", &Context::new(), file); } #[get("/cv//output.pdf")] pub async fn render_pdf_cv(username: &str, browser: BrowserHolder, tera: NanoTera, tracing: TracingSpan) -> PdfStream { let entered_span = tracing.0.enter(); let file = tempfile::Builder::new().suffix(".html").tempfile().unwrap(); render_template("two_column", &file, tera); let span = info_span!("render_pdf", username = username); let pdf = span.in_scope(||{ generate_pdf(browser.browser, &file) }); drop(entered_span); PdfStream::new(pdf) } /// Route only for debuging #[get("/cv//output.html")] pub async fn render_html_cv(username: &str, tera: NanoTera, tracing: TracingSpan) -> NamedFile { let entered_span = tracing.0.enter(); let file = tempfile::Builder::new().suffix(".html").tempfile().unwrap(); render_template("two_column", &file, tera); NamedFile::open(file.path()).await.unwrap() }