ovlach_pdf/src/routes/pdf.rs

54 lines
1.9 KiB
Rust
Raw Normal View History

2023-11-27 19:38:32 +00:00
use std::{fs, thread};
use std::{fs::File, time::Duration};
use std::io::prelude::*;
use headless_chrome::Browser;
use headless_chrome::{types::PrintToPdfOptions, LaunchOptions};
use rocket::{get, Response, futures::Stream, tokio::net::UnixStream, fs::NamedFile};
2023-11-28 08:45:03 +00:00
use tracing::{info_span, debug, info};
2023-11-27 19:38:32 +00:00
2023-11-27 21:56:10 +00:00
use crate::chromium::rocket::BrowserHolder;
2023-11-28 08:45:03 +00:00
use crate::tools::rocket::TracingSpan;
2023-11-27 21:56:10 +00:00
fn generate_pdf(browser: Browser) {
2023-11-27 19:38:32 +00:00
let tab = browser.new_tab().unwrap();
let tab = tab.navigate_to("file:///home/6a6996c0-1609-48b6-8ca6-affbef1b4d1d/Devel/Nanobyte/ovlach/ovlach_pdf/template.html").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 = tab.print_to_pdf(Some(options)).unwrap();
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();
}
#[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();
tracing.0.record(
"username",
username
);
let span = info_span!("render_pdf", username = username);
let entered_inner_span = span.enter();
info!("generate PDF");
2023-11-27 21:56:10 +00:00
generate_pdf(browser.browser);
2023-11-28 08:45:03 +00:00
info!("done generating");
drop(entered_inner_span);
drop(entered_span);
2023-11-27 19:38:32 +00:00
"foo!".to_string();
NamedFile::open("/tmp/foo.pdf").await.expect("failed to open foo.pdf")
}