ovlach_pdf/src/routes/pdf.rs

55 lines
1.8 KiB
Rust
Raw Normal View History

2023-11-28 17:17:11 +00:00
use core::panic;
use std::{fs, io::Write};
2023-11-27 19:38:32 +00:00
use headless_chrome::Browser;
2023-11-28 17:17:11 +00:00
use headless_chrome::types::PrintToPdfOptions;
use nanobyte_opentelemetry::rocket::TracingSpan;
use rocket::{get, fs::NamedFile};
use tracing::{info_span, info};
2023-11-27 21:56:10 +00:00
use crate::chromium::rocket::BrowserHolder;
fn generate_pdf(browser: Browser) {
2023-11-27 19:38:32 +00:00
let tab = browser.new_tab().unwrap();
2023-11-28 16:09:50 +00:00
info_span!("open_pdf").in_scope(|| {
tab.navigate_to("file:///home/6a6996c0-1609-48b6-8ca6-affbef1b4d1d/Devel/Nanobyte/ovlach/ovlach_pdf/template.html").unwrap().wait_until_navigated().unwrap();
});
2023-11-27 19:38:32 +00:00
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));
2023-11-28 16:09:50 +00:00
let bytes = info_span!("print_pdf").in_scope(|| {
tab.print_to_pdf(Some(options)).unwrap()
});
info_span!("write_temporary_file").in_scope(|| {
let mut file = fs::OpenOptions::new()
// .create(true) // To create a new file
.write(true)
// either use the ? operator or unwrap since it returns a Result
.open("/tmp/foo.pdf").unwrap();
file.write_all(&bytes).unwrap();
});
2023-11-27 19:38:32 +00:00
}
#[get("/cv/<username>/pdf")]
2023-11-28 08:45:03 +00:00
pub async fn render_pdf_cv(username: &str, browser: BrowserHolder, tracing: TracingSpan) -> NamedFile {
let entered_span = tracing.0.enter();
let span = info_span!("render_pdf", username = username);
info!("generate PDF");
2023-11-28 16:09:50 +00:00
span.in_scope(||{
generate_pdf(browser.browser);
});
2023-11-28 08:45:03 +00:00
info!("done generating");
drop(entered_span);
2023-11-27 19:38:32 +00:00
NamedFile::open("/tmp/foo.pdf").await.expect("failed to open foo.pdf")
}