Skip to content

Commit

Permalink
bump html2pdf + add uuid to generated files + use async sleep
Browse files Browse the repository at this point in the history
  • Loading branch information
randommm committed Oct 17, 2023
1 parent e5d9dd2 commit 16fd994
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 8 deletions.
15 changes: 13 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,6 @@ dotenvy = "0.15"
dotenvy_macro = "0.15"
serde = { version = "1" }
serde_json = "1"
html2pdf = { git = "https://github.com/randommm/html2pdf.git" }
html2pdf = { version = "0.7" }
headless_chrome = "1"
uuid = { version = "1.3", features = ["v4"] }
16 changes: 11 additions & 5 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@ use dotenvy::var;
use headless_chrome::{types::PrintToPdfOptions, LaunchOptions};
use reqwest::{header::AUTHORIZATION, multipart};
use serde_json::Value;
use tokio::fs::File;
use std::io::Write;
use tokio::fs::File;
use tokio::time::{sleep, Duration};
use uuid::Uuid;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
Expand Down Expand Up @@ -33,7 +35,11 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
.ok_or("Could not find user id in response")?
.to_owned();

let file_id = Uuid::new_v4().to_string();
let filename_pdf = format!("/tmp/{file_id}.pdf");

if std::path::Path::new("/file.html").exists() {
let filename_pdf = filename_pdf.clone();
println!("Starting PDF conversion");
let handler = std::thread::spawn(|| {
let launch_options = LaunchOptions {
Expand All @@ -42,7 +48,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
};
html2pdf::html_to_pdf(
"/file.html",
"/tmp/file_to_send.pdf",
filename_pdf,
PrintToPdfOptions::default(),
launch_options,
None,
Expand All @@ -51,16 +57,16 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
while !handler.is_finished() {
print!(".");
std::io::stdout().flush().unwrap_or_default();
std::thread::sleep(std::time::Duration::from_millis(200));
sleep(Duration::from_millis(200)).await;
}
handler.join().map_err(|_| "thread error")??;
println!("\nFinished PDF conversion");
} else {
return Err("HTML file not found".into());
}

// Sent file to user on Slack
let file = File::open("/tmp/file_to_send.pdf").await?;
// Send file to user on Slack
let file = File::open(filename_pdf).await?;
let some_file = multipart::Part::stream(file)
.file_name("document.pdf")
.mime_str("text/plain")?;
Expand Down

0 comments on commit 16fd994

Please sign in to comment.