Pdf

Struct Pdf 

Source
pub struct Pdf {
    input: Vec<Token>,
    style: StyleMatch,
    font_family: FontFamily<FontData>,
    code_font_family: FontFamily<FontData>,
    font_fallback_chain: Option<FontFamily<FontFallbackChain>>,
    code_font_fallback_chain: Option<FontFamily<FontFallbackChain>>,
    image_loader: RefCell<Option<ImageLoader>>,
}
Expand description

The main PDF document generator that orchestrates the conversion process from markdown to PDF. This struct serves as the central coordinator for document generation, managing the overall structure, styling application, and proper sequencing of content elements. It stores the input markdown tokens that will be processed into PDF content, along with style configuration that controls the visual appearance and layout of the generated document. The generator maintains two separate font families - a main text font used for regular document content and a specialized monospace font specifically for code sections. These fonts are loaded based on the style configuration and stored internally for use during the PDF generation process.

Fields§

§input: Vec<Token>§style: StyleMatch§font_family: FontFamily<FontData>§code_font_family: FontFamily<FontData>§font_fallback_chain: Option<FontFamily<FontFallbackChain>>§code_font_fallback_chain: Option<FontFamily<FontFallbackChain>>§image_loader: RefCell<Option<ImageLoader>>

Implementations§

Source§

impl Pdf

Source

pub fn new( input: Vec<Token>, style: StyleMatch, font_config: Option<&FontConfig>, ) -> Self

Creates a new PDF generator instance to process markdown tokens. The generator maintains document structure and applies styling/layout rules during conversion.

It automatically loads two font families based on the style configuration:

  • A main text font for regular content
  • A code font specifically for code blocks and inline code segments

Font loading is handled automatically but will panic if the specified fonts cannot be loaded successfully. The generator internally stores the input tokens, style configuration, and loaded font families for use during PDF generation.

Through the style configuration, the generator controls all visual aspects of the output PDF including typography, dimensions, colors and spacing between elements. The style settings determine the complete visual appearance and layout characteristics of the final generated PDF document.

§Arguments
  • input - The markdown tokens to convert
  • style - Style configuration for the document
  • font_config - Optional font configuration with custom paths and font overrides
  • document_path - Optional path to the markdown document (for resolving relative image paths)
Source

pub fn with_document_path( input: Vec<Token>, style: StyleMatch, font_config: Option<&FontConfig>, document_path: Option<&Path>, ) -> Self

Creates a new PDF generator instance with document path support for image resolution.

Similar to new() but accepts an optional document path, which is used to resolve relative image references and enable loading of local and remote images.

§Arguments
  • input - The markdown tokens to convert
  • style - Style configuration for the document
  • font_config - Optional font configuration with custom paths and font overrides
  • document_path - Path to the markdown document (for resolving relative image paths)
Source

pub fn render(document: Document, path: &str) -> Option<String>

Finalizes and outputs the processed document to a PDF file at the specified path. Provides comprehensive error handling to catch and report any issues during the final rendering phase.

Source

pub fn render_to_bytes(document: Document) -> Result<Vec<u8>, String>

Renders the processed document to bytes and returns the PDF data as a Vec. This method provides the same PDF generation as render but returns the content directly as bytes instead of writing to a file, making it suitable for cases where you need to handle the PDF data in memory or send it over a network.

§Arguments
  • document - The generated PDF document to render
§Returns
  • Ok(Vec<u8>) containing the PDF data on successful rendering
  • Err(String) with error message if rendering fails
§Example
// This example shows the basic usage pattern, but render_to_bytes
// is typically called internally by parse_into_bytes
use markdown2pdf::{parse_into_bytes, config::ConfigSource};

let markdown = "# Test\nSome content".to_string();
let pdf_bytes = parse_into_bytes(markdown, ConfigSource::Default, None).unwrap();
// Use the bytes as needed (save, send, etc.)
assert!(!pdf_bytes.is_empty());
Source

pub fn render_into_document(&self) -> Document

Initializes and returns a new PDF document with configured styling and layout.

Creates a new document instance with the main font family and configures the page decorator with margins from the style settings. The document’s base font size is set according to the text style configuration.

The function processes all input tokens and renders them into the document structure before returning the complete document ready for final output. The document contains all content with proper styling, formatting and layout applied according to the style configuration.

Through the style configuration, this method controls the overall document appearance including:

  • Page margins and layout
  • Base font size
  • Content processing and rendering
Source

fn process_tokens(&self, doc: &mut Document)

Processes and renders tokens directly into the document structure.

This method iterates through all input tokens and renders them into the document, handling each token type appropriately according to its semantic meaning. Block-level elements like headings, list items, and code blocks trigger the flushing of any accumulated inline tokens into paragraphs before being rendered themselves.

The method maintains a buffer of current tokens that gets flushed into paragraphs when block-level elements are encountered or when explicit paragraph breaks are needed. This ensures proper document flow and maintains correct spacing between different content elements while preserving the intended document structure.

Through careful token processing and rendering, this method builds up the complete document content with appropriate styling, formatting and layout applied according to the configured style settings.

Source

fn flush_paragraph(&self, doc: &mut Document, tokens: &[Token])

Renders accumulated tokens as a paragraph in the document.

This method takes a document and a slice of tokens, and renders them as a paragraph with appropriate styling. If the tokens slice is empty, no paragraph is rendered. After rendering the paragraph content, it adds spacing after the paragraph according to the configured text style.

Source

fn render_heading(&self, doc: &mut Document, content: &[Token], level: usize)

Renders a heading with the appropriate level styling.

This method takes a document, heading content tokens, and a level number to render a heading with the corresponding style settings. It applies font size, bold/italic effects, and text color based on the heading level configuration. After rendering the heading, it adds the configured spacing.

Source

fn render_inline_content_with_style( &self, para: &mut Paragraph, tokens: &[Token], style: Style, doc: &mut Document, )

Renders inline content with a specified style.

This method processes a sequence of inline tokens and renders them with the given style. It handles various inline elements like plain text, emphasis, strong emphasis, links, and inline code, applying appropriate styling modifications for each type while maintaining the base style properties.

Source

fn render_inline_content_with_style_simple( &self, para: &mut Paragraph, tokens: &[Token], style: Style, )

Version without Document - for headings and other places where we can’t render images

Source

fn render_inline_content( &self, para: &mut Paragraph, tokens: &[Token], doc: &mut Document, )

Source

fn render_code_block(&self, doc: &mut Document, lang: &str, content: &str)

Renders inline content with a specified style. Renders a code block with appropriate styling.

This method handles multi-line code blocks, rendering each line as a separate paragraph with the configured code style. It applies the code font size and text color settings, and adds the configured spacing after the block.

Source

fn render_highlighted_line( &self, doc: &mut Document, indent: &str, tokens: &[(String, HighlightColor, bool, bool)], )

Renders a single line of highlighted code

Source

fn render_list_item( &self, doc: &mut Document, content: &[Token], ordered: bool, number: Option<usize>, nesting_level: usize, )

Renders a list item with appropriate styling and formatting.

This method handles both ordered and unordered list items, with support for nested lists. For ordered lists, it includes the item number prefixed with a period (like “1.”), while unordered lists use a bullet point dash character. The content is rendered with the configured list item style settings from the document style configuration.

The method processes both the direct content of the list item as well as any nested list items recursively. Each nested level increases the indentation by 4 spaces to create a visual hierarchy. The method filters the content to separate inline elements from nested list items, rendering the inline content first before processing any nested items.

After rendering each list item’s content, appropriate spacing is added based on the configured after_spacing value. The method maintains consistent styling throughout the list hierarchy while allowing for proper nesting and indentation of complex list structures.

Source

fn render_table( &self, doc: &mut Document, headers: &Vec<Vec<Token>>, aligns: &Vec<Alignment>, rows: &Vec<Vec<Vec<Token>>>, )

Renders a table with headers, alignment information, and rows.

Each row is a vector of cells.

The table is rendered using genpdfi’s TableLayout with proper column weights and cell borders. Each cell content is processed as inline tokens to handle formatting within table them.

Source

fn render_image(&self, doc: &mut Document, alt: &str, url: &str)

Renders an image token as a block-level element in the document.

Attempts to load the image from the configured ImageLoader and embed it into the PDF. For SVG images, uses native SVG rendering. For raster formats, uses Image::from_reader(). If loading fails or no loader is configured, renders the alt text.

Source

fn render_math_block(&self, doc: &mut Document, latex_content: &str)

Renders a display math block ($$…$$).

This method converts LaTeX mathematical expressions to SVG and embeds them as centered images in the PDF. Display math is rendered as a block-level element with appropriate spacing. The rendering uses dimensional metrics to ensure consistent sizing with the surrounding text.

Source

fn safe_latex_to_svg( &self, content: &str, display: bool, ) -> Result<String, String>

Safely render LaTeX to SVG with error recovery.

This wraps the LaTeX rendering call with error handling to prevent panics from underlying C++ dependencies.

Source

fn safe_latex_to_svg_with_metrics( &self, content: &str, display: bool, target_height: f32, ) -> Result<(String, f32), String>

Safely render LaTeX to SVG with metrics and error recovery.

This wraps the LaTeX rendering call with metrics calculation with error handling to prevent panics from underlying C++ dependencies. Returns both the SVG string and a scale factor computed from the formula’s dimensional metrics.

Source

fn render_inline_math_as_image(&self, doc: &mut Document, latex_content: &str)

Renders inline math ($…$).

This method converts inline LaTeX expressions to SVG and embeds them as inline images in the paragraph. The rendering uses dimensional metrics to ensure consistent sizing with the surrounding text.

Source

fn render_inline_math( &self, para: &mut Paragraph, latex_content: &str, style: Style, )

Auto Trait Implementations§

§

impl !Freeze for Pdf

§

impl !RefUnwindSafe for Pdf

§

impl Send for Pdf

§

impl !Sync for Pdf

§

impl Unpin for Pdf

§

impl UnwindSafe for Pdf

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> Finish for T

§

fn finish(self)

Does nothing but move self, equivalent to drop.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
§

impl<T> Pointable for T

§

const ALIGN: usize

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
§

impl<T> PolicyExt for T
where T: ?Sized,

§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns [Action::Follow] only if self and other return Action::Follow. Read more
§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns [Action::Follow] if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
§

impl<U, T> ToOwnedObj<U> for T
where U: FromObjRef<T>,

§

fn to_owned_obj(&self, data: FontData<'_>) -> U

Convert this type into T, using the provided data to resolve any offsets.
§

impl<U, T> ToOwnedTable<U> for T
where U: FromTableRef<T>,

§

fn to_owned_table(&self) -> U

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more