58 lines
1.4 KiB
Rust
58 lines
1.4 KiB
Rust
use actix_web::{post, web::Json, HttpResponse};
|
|
use anyhow::Result;
|
|
use serde::{Deserialize, Serialize};
|
|
use std::fs::File;
|
|
use std::process::Command;
|
|
use std::{
|
|
io::Write,
|
|
time::{SystemTime, UNIX_EPOCH},
|
|
};
|
|
use uuid::Uuid;
|
|
|
|
#[derive(Deserialize, Debug)]
|
|
pub struct PostPdfRequest {
|
|
pub html: String,
|
|
}
|
|
|
|
#[derive(Serialize)]
|
|
pub struct PostPdfResponse {
|
|
pub error: Option<String>,
|
|
pub filename: Option<String>,
|
|
}
|
|
|
|
fn gen_pdf(html: &str, path: &str) -> Result<()> {
|
|
let dir = tempfile::tempdir()?;
|
|
let file_path = dir.path().join("index.html");
|
|
let mut file = File::create(&file_path)?;
|
|
file.write_all(html.as_bytes())?;
|
|
|
|
Command::new("wkhtmltopdf")
|
|
.arg(file_path)
|
|
.arg(path)
|
|
.output()?;
|
|
|
|
dir.close()?;
|
|
|
|
Ok(())
|
|
}
|
|
|
|
#[post("/v1/pdf")]
|
|
async fn post_pdf(data: Json<PostPdfRequest>) -> HttpResponse {
|
|
let start = SystemTime::now();
|
|
let since_epoch = start
|
|
.duration_since(UNIX_EPOCH)
|
|
.expect("Time went backwards");
|
|
let filename = format!("/static/{}_{}.pdf", since_epoch.as_secs(), Uuid::new_v4());
|
|
if let Err(x) = gen_pdf(&data.html, &filename) {
|
|
return HttpResponse::InternalServerError().json(PostPdfResponse {
|
|
error: Some(x.to_string()),
|
|
filename: None,
|
|
});
|
|
}
|
|
|
|
HttpResponse::Created().json(PostPdfResponse {
|
|
error: None,
|
|
filename: Some(filename),
|
|
})
|
|
}
|