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
impl Pdf
Sourcepub fn new(
input: Vec<Token>,
style: StyleMatch,
font_config: Option<&FontConfig>,
) -> Self
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 convertstyle- Style configuration for the documentfont_config- Optional font configuration with custom paths and font overridesdocument_path- Optional path to the markdown document (for resolving relative image paths)
Sourcepub fn with_document_path(
input: Vec<Token>,
style: StyleMatch,
font_config: Option<&FontConfig>,
document_path: Option<&Path>,
) -> Self
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 convertstyle- Style configuration for the documentfont_config- Optional font configuration with custom paths and font overridesdocument_path- Path to the markdown document (for resolving relative image paths)
Sourcepub fn render(document: Document, path: &str) -> Option<String>
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.
Sourcepub fn render_to_bytes(document: Document) -> Result<Vec<u8>, String>
pub fn render_to_bytes(document: Document) -> Result<Vec<u8>, String>
Renders the processed document to bytes and returns the PDF data as a Vecrender 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 renderingErr(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());Sourcepub fn render_into_document(&self) -> Document
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
Sourcefn process_tokens(&self, doc: &mut Document)
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.
Sourcefn flush_paragraph(&self, doc: &mut Document, tokens: &[Token])
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.
Sourcefn render_heading(&self, doc: &mut Document, content: &[Token], level: usize)
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.
Sourcefn render_inline_content_with_style(
&self,
para: &mut Paragraph,
tokens: &[Token],
style: Style,
doc: &mut Document,
)
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.
Sourcefn render_inline_content_with_style_simple(
&self,
para: &mut Paragraph,
tokens: &[Token],
style: Style,
)
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
fn render_inline_content( &self, para: &mut Paragraph, tokens: &[Token], doc: &mut Document, )
Sourcefn render_code_block(&self, doc: &mut Document, lang: &str, content: &str)
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.
Sourcefn render_highlighted_line(
&self,
doc: &mut Document,
indent: &str,
tokens: &[(String, HighlightColor, bool, bool)],
)
fn render_highlighted_line( &self, doc: &mut Document, indent: &str, tokens: &[(String, HighlightColor, bool, bool)], )
Renders a single line of highlighted code
Sourcefn render_list_item(
&self,
doc: &mut Document,
content: &[Token],
ordered: bool,
number: Option<usize>,
nesting_level: usize,
)
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.
Sourcefn render_table(
&self,
doc: &mut Document,
headers: &Vec<Vec<Token>>,
aligns: &Vec<Alignment>,
rows: &Vec<Vec<Vec<Token>>>,
)
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.
Sourcefn render_image(&self, doc: &mut Document, alt: &str, url: &str)
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.
Sourcefn render_math_block(&self, doc: &mut Document, latex_content: &str)
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.
Sourcefn safe_latex_to_svg(
&self,
content: &str,
display: bool,
) -> Result<String, String>
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.
Sourcefn safe_latex_to_svg_with_metrics(
&self,
content: &str,
display: bool,
target_height: f32,
) -> Result<(String, f32), String>
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.
Sourcefn render_inline_math_as_image(&self, doc: &mut Document, latex_content: &str)
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.
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> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
§impl<T> Instrument for T
impl<T> Instrument for T
§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self>
fn into_either(self, into_left: bool) -> Either<Self, Self>
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 moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
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
impl<T> Pointable for T
§impl<T> PolicyExt for Twhere
T: ?Sized,
impl<T> PolicyExt for Twhere
T: ?Sized,
§impl<U, T> ToOwnedObj<U> for Twhere
U: FromObjRef<T>,
impl<U, T> ToOwnedObj<U> for Twhere
U: FromObjRef<T>,
§fn to_owned_obj(&self, data: FontData<'_>) -> U
fn to_owned_obj(&self, data: FontData<'_>) -> U
T, using the provided data to resolve any offsets.