bibby 0.1.0

The official Rust SDK for Bytebury — typed clients, smart .env initialization, and ergonomic macros for Geo, Images, PDF, Mailer, Uploader, Cron, Forms, Webhooks, Monitors, and Vault.
Documentation
//! Client and types for **Bytebury PDF** (`https://api.bytebury.com/pdf/v1`).
//!
//! Render HTML/CSS (with optional MiniJinja template data, custom fonts, and
//! embedded images) or print live web pages to PDF, with optional direct saving
//! to Bytebury Uploader.

use std::collections::BTreeMap;

use base64::Engine;
use base64::engine::general_purpose::STANDARD;
use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::client::Bibby;
use crate::error::Result;

const PRODUCT: &str = "pdf";

/// Client for **Bytebury PDF**.
///
/// Obtained via [`Bibby::pdf`].
#[derive(Debug, Clone, Copy)]
pub struct PdfClient<'a> {
    client: &'a Bibby,
}

impl<'a> PdfClient<'a> {
    pub(crate) fn new(client: &'a Bibby) -> Self {
        Self { client }
    }

    /// Renders HTML/CSS or a live URL into a PDF document.
    ///
    /// Use [`crate::pdf!`] for concise request construction.
    ///
    /// Calls `POST /pdf/v1/pdfs/render`.
    pub async fn render(&self, request: &RenderPdfRequest) -> Result<RenderedPdf> {
        self.client.post_json(PRODUCT, "pdfs/render", request).await
    }
}

/// Standard paper size for [`RenderPdfRequest`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum PageSize {
    /// ISO A4 (default).
    A4,
    /// US Letter.
    Letter,
    /// ISO A3.
    A3,
    /// Continuous single A4-wide page with no page breaks.
    None,
}

/// Gateway option for automatically saving a rendered PDF to Bytebury Uploader.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum UploaderSaveOption {
    /// `true` saves using your plan's default visibility; `false` disables saving.
    Default(bool),
    /// Saves with explicit public/private visibility.
    Visibility {
        /// Whether the saved Uploader file should have a permanent public URL.
        public: bool,
    },
}

impl UploaderSaveOption {
    /// Save to Uploader using your plan's default visibility.
    pub fn save() -> Self {
        Self::Default(true)
    }

    /// Save to Uploader as a public file.
    pub fn public() -> Self {
        Self::Visibility { public: true }
    }

    /// Save to Uploader as a private file.
    pub fn private() -> Self {
        Self::Visibility { public: false }
    }
}

/// Request body for [`PdfClient::render`].
///
/// Provide either [`html`](Self::html) or [`url`](Self::url).
#[derive(Debug, Clone, Default, Serialize)]
pub struct RenderPdfRequest {
    /// HTML document or MiniJinja template (up to 2 MB).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub html: Option<String>,
    /// Public web page URL to print with a real browser (paid plans only; counts as 5 requests).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub url: Option<String>,
    /// Template context passed to MiniJinja when rendering `html`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data: Option<Value>,
    /// Extra CSS applied after `<style>` tags (`@page` rules supported).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub css: Option<String>,
    /// Map of filename -> base64-encoded image bytes referenced as `<img src="name">`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub images: Option<BTreeMap<String, String>>,
    /// Base64-encoded font files (TTF, OTF, TTC, WOFF2).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub fonts: Option<Vec<String>>,
    /// Paper size (`a4`, `letter`, `a3`, or `none`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub page_size: Option<PageSize>,
    /// Render in landscape orientation (`false` by default).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub landscape: Option<bool>,
    /// Uniform page margin in millimeters (`0.0..=100.0`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub margin_mm: Option<f64>,
    /// PDF document metadata title (required when `accessible` is `true`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
    /// PDF document metadata author.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub author: Option<String>,
    /// BCP 47 language tag (e.g. `"en"`; required when `accessible` is `true`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub language: Option<String>,
    /// Generate PDF outline bookmarks from `h1`–`h6`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub bookmarks: Option<bool>,
    /// Emit tagged PDF/UA-1 output.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub accessible: Option<bool>,
    /// Output filename (`.pdf` appended automatically if omitted).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub file_name: Option<String>,
    /// Automatically persist the rendered PDF to Bytebury Uploader.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub uploader: Option<UploaderSaveOption>,
}

impl RenderPdfRequest {
    /// Creates a request that renders raw HTML (or a MiniJinja template).
    pub fn from_html(html: impl Into<String>) -> Self {
        Self {
            html: Some(html.into()),
            ..Self::default()
        }
    }

    /// Creates a request that prints a live web page URL (paid plans only).
    pub fn from_url(url: impl Into<String>) -> Self {
        Self {
            url: Some(url.into()),
            ..Self::default()
        }
    }

    /// Attaches JSON template context for MiniJinja rendering.
    pub fn data(mut self, data: Value) -> Self {
        self.data = Some(data);
        self
    }

    /// Adds extra CSS rules.
    pub fn css(mut self, css: impl Into<String>) -> Self {
        self.css = Some(css.into());
        self
    }

    /// Embeds a named binary image asset (encoded as base64) for `<img src="name">`.
    pub fn image_bytes(mut self, name: impl Into<String>, bytes: impl AsRef<[u8]>) -> Self {
        self.images
            .get_or_insert_with(BTreeMap::new)
            .insert(name.into(), STANDARD.encode(bytes.as_ref()));
        self
    }

    /// Embeds a binary font file (encoded as base64).
    pub fn font_bytes(mut self, bytes: impl AsRef<[u8]>) -> Self {
        self.fonts
            .get_or_insert_with(Vec::new)
            .push(STANDARD.encode(bytes.as_ref()));
        self
    }

    /// Sets the paper size.
    pub fn page_size(mut self, size: PageSize) -> Self {
        self.page_size = Some(size);
        self
    }

    /// Enables or disables landscape orientation.
    pub fn landscape(mut self, landscape: bool) -> Self {
        self.landscape = Some(landscape);
        self
    }

    /// Sets uniform margins in millimeters (`0..=100`).
    pub fn margin_mm(mut self, margin_mm: f64) -> Self {
        self.margin_mm = Some(margin_mm);
        self
    }

    /// Sets the PDF filename.
    pub fn file_name(mut self, file_name: impl Into<String>) -> Self {
        self.file_name = Some(file_name.into());
        self
    }

    /// Automatically saves the rendered PDF to Bytebury Uploader.
    pub fn save_to_uploader(mut self, option: UploaderSaveOption) -> Self {
        self.uploader = Some(option);
        self
    }
}

/// Summary of the file saved in Bytebury Uploader when `uploader` was requested.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SavedUploaderFile {
    /// Uploader file ID.
    pub id: i64,
    /// Saved filename.
    pub name: String,
    /// Permanent public URL, if saved as public.
    pub public_url: Option<String>,
}

/// Response returned by [`PdfClient::render`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RenderedPdf {
    /// Always `"application/pdf"`.
    pub mime_type: String,
    /// Generated filename (e.g. `"invoice.pdf"`).
    pub file_name: String,
    /// Decoded PDF size in bytes.
    pub size_bytes: i64,
    /// Base64-encoded PDF binary.
    pub data: String,
    /// Non-fatal warnings (for example, external assets that could not be fetched).
    #[serde(default)]
    pub warnings: Vec<String>,
    /// Populated when `uploader` was requested and saving succeeded.
    pub uploader_file: Option<SavedUploaderFile>,
    /// Populated when `uploader` was requested and saving failed (the PDF is still in `data`).
    pub uploader_error: Option<String>,
}

impl RenderedPdf {
    /// Decodes [`Self::data`] from base64 into raw PDF bytes.
    pub fn decode_bytes(&self) -> Result<Vec<u8>> {
        Ok(STANDARD.decode(&self.data)?)
    }
}