Skip to content

Типы и перечисления

Все публичные типы в pdf_oxide, организованные по категориям. Документацию на уровне методов см. в Справочнике Rust API.


Геометрия

Point

pub struct Point {
    pub x: f64,
    pub y: f64,
}

Двумерная точка в координатном пространстве PDF (начало координат — нижний левый угол, Y увеличивается вверх).

Rect

pub struct Rect {
    pub x0: f64,
    pub y0: f64,
    pub x1: f64,
    pub y1: f64,
}

Прямоугольник, выровненный по осям. (x0, y0) — нижний левый угол, (x1, y1) — верхний правый угол. Все координаты в пунктах PDF (1 пункт = 1/72 дюйма).

Python: Доступен как кортеж (x0, y0, x1, y1).

Matrix

pub struct Matrix {
    pub a: f64,
    pub b: f64,
    pub c: f64,
    pub d: f64,
    pub e: f64,
    pub f: f64,
}

Аффинная матрица трансформации 3x3 в формате спецификации PDF:

| a  b  0 |
| c  d  0 |
| e  f  1 |

Используется для позиционирования текста, размещения изображений и трансформаций Form XObject.


Текст

TextSpan

pub struct TextSpan {
    pub text: String,
    pub x: f64,
    pub y: f64,
    pub font_name: String,
    pub font_size: f64,
    pub bbox: Rect,
}

Фрагмент текста с одинаковым стилем. Возвращается extract_spans().

TextChar

pub struct TextChar {
    pub char: char,
    pub x: f64,
    pub y: f64,
    pub font_size: f64,
    pub font_name: String,
    pub bbox: Rect,
}

Одиночный символ с точным позиционированием. Возвращается extract_chars().

Поля Python:

Поле Тип Описание
char str The character
bbox tuple[float, float, float, float] Ограничивающий прямоугольник (x0, y0, x1, y1)
font_name str Имя шрифта
font_size float Размер шрифта в пунктах
origin_x float Начало базовой линии X
origin_y float Начало базовой линии Y
rotation_degrees float Угол поворота (0–360)
advance_width float Расстояние до следующей позиции символа

FontWeight

pub enum FontWeight {
    Thin,       // 100
    ExtraLight, // 200
    Light,      // 300
    Normal,     // 400
    Medium,     // 500
    SemiBold,   // 600
    Bold,       // 700
    ExtraBold,  // 800
    Black,      // 900
}

Color

pub struct Color {
    pub r: f64,
    pub g: f64,
    pub b: f64,
}

Цвет RGB with components in the range 0.0 to 1.0.


Страница

PageSize

pub enum PageSize {
    Letter,         // 612 x 792 pt (8.5 x 11 in)
    A4,             // 595.28 x 841.89 pt (210 x 297 mm)
    Legal,          // 612 x 1008 pt (8.5 x 14 in)
    A3,             // 841.89 x 1190.55 pt
    A5,             // 419.53 x 595.28 pt
    Custom(f32, f32), // Custom width x height in points
}

Методы:

Метод Возвращает Описание
dimensions() (f32, f32) Ширина и высота в пунктах

PageInfo

pub struct PageInfo {
    pub width: f64,
    pub height: f64,
    pub rotation: i32,
    pub media_box: Rect,
    pub crop_box: Option<Rect>,
    pub trim_box: Option<Rect>,
    pub bleed_box: Option<Rect>,
    pub art_box: Option<Rect>,
}

PageLabelStyle

pub enum PageLabelStyle {
    Decimal,        // 1, 2, 3, ...
    UpperRoman,     // I, II, III, ...
    LowerRoman,     // i, ii, iii, ...
    UpperAlpha,     // A, B, C, ...
    LowerAlpha,     // a, b, c, ...
    None,           // No numbering
}

PageLabelRange

pub struct PageLabelRange {
    pub start_page: usize,
    pub style: PageLabelStyle,
    pub prefix: Option<String>,
    pub start_number: Option<usize>,
}

Определяет диапазон меток страниц. Например, диапазон, начинающийся со страницы 0, со стилем LowerRoman и начальным номером 1, помечает страницы как i, ii, iii и т.д.


Изображения

ImageFormat

pub enum ImageFormat {
    Jpeg,
    Png,
    Tiff,
    Bmp,
    Gif,
    Jp2,
    Jbig2,
    Ccitt,
    Raw,
    Unknown,
}

ColorSpace

pub enum ColorSpace {
    DeviceRGB,
    DeviceCMYK,
    DeviceGray,
    ICCBased,
    CalRGB,
    CalGray,
    Lab,
    Indexed,
    Pattern,
    Separation,
    DeviceN,
    Unknown,
}

ImageInfo

pub struct ImageContent {
    pub width: u32,
    pub height: u32,
    pub bits_per_component: u8,
    pub color_space: ColorSpace,
    pub format: ImageFormat,
    pub data: Vec<u8>,
    pub bbox: Rect,
    pub horizontal_dpi: Option<f32>,
    pub vertical_dpi: Option<f32>,
}

Методы:

Метод Возвращает Описание
resolution() Option<(f32, f32)> DPI как (горизонтальное, вертикальное)
is_high_resolution() bool DPI >= 300
is_medium_resolution() bool DPI 150–299
is_low_resolution() bool DPI < 150
calculate_dpi() Option<(f32, f32)> Вычислить из размеров в пикселях и ограничивающего прямоугольника

Пути

PathContent

pub struct PathContent {
    pub operations: Vec<PathOperation>,
    pub stroke_color: Option<Color>,
    pub fill_color: Option<Color>,
    pub stroke_width: f32,
    pub line_cap: LineCap,
    pub line_join: LineJoin,
    pub bbox: Rect,
}

PathOperation

pub enum PathOperation {
    MoveTo { x: f64, y: f64 },
    LineTo { x: f64, y: f64 },
    CurveTo { x1: f64, y1: f64, x2: f64, y2: f64, x3: f64, y3: f64 },
    ClosePath,
    Rect { x: f64, y: f64, width: f64, height: f64 },
}

LineCap

pub enum LineCap {
    Butt,    // Square end at endpoint (default)
    Round,   // Semicircle at endpoint
    Square,  // Square extends half line width past endpoint
}

LineJoin

pub enum LineJoin {
    Miter,   // Sharp corner (default)
    Round,   // Rounded corner
    Bevel,   // Flat corner
}

BlendMode

pub enum BlendMode {
    Normal,
    Multiply,
    Screen,
    Overlay,
    Darken,
    Lighten,
    ColorDodge,
    ColorBurn,
    HardLight,
    SoftLight,
    Difference,
    Exclusion,
}

Используется в графическом состоянии для композитинга с прозрачностью. Устанавливается через ExtGState или графический API.


Элементы содержимого

ContentElement

Объединённый тип для всех элементов содержимого страницы:

pub enum ContentElement {
    Text(TextContent),
    Image(ImageContent),
    Path(PathContent),
    Table(TableContent),
    Structure(StructureElement),
}

TextContent

pub struct TextContent {
    pub text: String,
    pub font_name: String,
    pub font_size: f64,
    pub font_weight: FontWeight,
    pub font_style: FontStyle,
    pub color: Color,
    pub bbox: Rect,
}

FontStyle

pub enum FontStyle {
    Normal,
    Italic,
    Oblique,
}

TextStyle

pub struct TextStyle {
    pub font_name: String,
    pub font_size: f64,
    pub font_weight: FontWeight,
    pub font_style: FontStyle,
    pub color: Color,
}

TableContent

pub struct TableContent {
    pub rows: Vec<TableRowContent>,
    pub column_count: usize,
    pub has_header: bool,
    pub caption: Option<String>,
    pub style: Option<TableContentStyle>,
    pub source: TableSource,
    pub bbox: Rect,
}

TableRowContent

pub struct TableRowContent {
    pub cells: Vec<TableCellContent>,
    pub is_header: bool,
}

TableCellContent

pub struct TableCellContent {
    pub text: String,
    pub row_span: usize,
    pub col_span: usize,
    pub alignment: TableCellAlign,
    pub vertical_alignment: TableCellVAlign,
    pub bbox: Rect,
}

TableCellAlign / TableCellVAlign

pub enum TableCellAlign {
    Left,
    Center,
    Right,
}

pub enum TableCellVAlign {
    Top,
    Middle,
    Bottom,
}

TableSource

pub enum TableSource {
    StructureTree,    // From tagged PDF structure
    Geometric,        // Detected from layout analysis
    Manual,           // User-created
}

StructureElement

pub struct StructureElement {
    pub structure_type: String,
    pub children: Vec<ContentElement>,
    pub alt_text: Option<String>,
    pub actual_text: Option<String>,
    pub language: Option<String>,
}

Аннотации

AnnotationType

pub enum AnnotationSubtype {
    Text,
    Link,
    FreeText,
    Line,
    Square,
    Circle,
    Polygon,
    PolyLine,
    Highlight,
    Underline,
    Squiggly,
    StrikeOut,
    Stamp,
    Caret,
    Ink,
    Popup,
    FileAttachment,
    Sound,
    Movie,
    Screen,
    Widget,
    PrinterMark,
    TrapNet,
    Watermark,
    ThreeD,
    Redact,
    RichMedia,
    Unknown,
}

TextAnnotationIcon

pub enum TextAnnotationIcon {
    Comment,
    Key,
    Note,
    Help,
    NewParagraph,
    Paragraph,
    Insert,
    Check,
    Circle,
    Cross,
    RightArrow,
    RightPointer,
    Star,
    UpArrow,
    UpLeftArrow,
}

StampType

pub enum StampType {
    Approved,
    Experimental,
    NotApproved,
    AsIs,
    Expired,
    NotForPublicRelease,
    Confidential,
    Final,
    Sold,
    Departmental,
    ForComment,
    TopSecret,
    Draft,
    ForPublicRelease,
}

Штрихкоды

BarcodeType

Требуется feature-флаг barcodes.

pub enum BarcodeType {
    QrCode,
    Code128,
    Ean13,
    UpcA,
    Code39,
    Itf,
}

Python: Типы штрихкодов передаются как строки: "code128", "ean13", "upca", "code39", "ean8", "itf".


Формы

FieldType / FormFieldType

pub enum FormFieldType {
    Text,
    Button,
    Choice,
    Signature,
}

FormField

pub struct FormField {
    pub name: String,
    pub field_type: FormFieldType,
    pub value: FormFieldValue,
    pub rect: Option<Rect>,
    pub page_index: Option<usize>,
    pub readonly: bool,
    pub required: bool,
}

FormFieldValue

pub enum FormFieldValue {
    None,
    Text(String),
    Boolean(bool),
    Choice(String),
    MultiChoice(Vec<String>),
}

Методы:

Метод Возвращает Описание
is_none() bool Проверить, является ли значение None
as_text() Option<&str> Получить текстовое значение
as_bool() Option<bool> Получить логическое значение
as_choice() Option<&str> Получить значение выбора
as_multi_choice() Option<&[String]> Получить значения множественного выбора

Поиск

SearchOptions

pub struct SearchOptions {
    pub case_sensitive: bool,
    pub literal: bool,
    pub whole_word: bool,
    pub max_results: Option<usize>,
    pub page_range: Option<(usize, usize)>,
}

SearchResult

pub struct SearchResult {
    pub page_index: usize,
    pub text: String,
    pub bbox: Rect,
    pub context: Option<String>,
}

Возвращается Pdf::search() и PdfDocument::search(). Каждый результат включает страницу совпадения, найденный текст, координаты ограничивающего прямоугольника и необязательный окружающий контекст.


Настройка

ConversionOptions

pub struct ConversionOptions {
    pub preserve_layout: bool,
    pub detect_headings: bool,
    pub extract_tables: bool,
    pub include_images: bool,
    pub image_output_dir: Option<String>,
    pub embed_images: bool,
    // ... additional fields
}

TextConfig

pub struct TextConfig {
    pub detect_headings: bool,
    pub detect_lists: bool,
    pub detect_tables: bool,
    pub merge_spans: bool,
}

RenderOptions

Требуется feature-флаг rendering.

pub struct RenderOptions {
    pub dpi: f32,
    pub background_color: Option<Color>,
    pub format: ImageFormat,
}

EncryptionConfig

pub struct EncryptionConfig {
    pub user_password: String,
    pub owner_password: String,
    pub algorithm: EncryptionAlgorithm,
    pub permissions: Permissions,
}

Конструктор:

EncryptionConfig::new("user_pass", "owner_pass")
    .with_algorithm(EncryptionAlgorithm::Aes256)
    .with_permissions(Permissions::read_only())

EncryptionAlgorithm

pub enum EncryptionAlgorithm {
    Rc4_40,     // V=1, R=2, 40-bit (legacy)
    Rc4_128,    // V=2, R=3, 128-bit (legacy)
    Aes128,     // V=4, R=4, 128-bit
    Aes256,     // V=5, R=6, 256-bit (default, recommended)
}

Разрешения

pub struct Permissions {
    pub print: bool,
    pub copy: bool,
    pub modify: bool,
    pub annotate: bool,
    pub fill_forms: bool,
    pub extract: bool,
}

Фабричные методы:

Метод Описание
Permissions::all() Все разрешения включены
Permissions::read_only() Разрешён только просмотр

PdfConfig

pub struct PdfConfig {
    pub page_size: PageSize,
    pub margins: (f32, f32, f32, f32),  // left, right, top, bottom
    pub font_size: f32,
    pub line_height: f32,
    pub title: Option<String>,
    pub author: Option<String>,
    pub subject: Option<String>,
    pub keywords: Option<String>,
}

Макет текста

TextAlign

pub enum TextAlign {
    Left,
    Center,
    Right,
    Justify,
}

RectFilterMode

Для пространственного извлечения текста:

pub enum RectFilterMode {
    Intersects,             // Любое пересечение (по умолчанию)
    FullyContained,         // Полностью внутри границ
    MinOverlap(f32),        // Минимальная доля пересечения (0.0–1.0)
}

Типы соответствия

См. PDF/A, PDF/UA и PDF/X для полной документации по соответствию стандартам.

PdfALevel

pub enum PdfALevel {
    A1a, A1b,
    A2a, A2b, A2u,
    A3a, A3b, A3u,
}

PdfUaLevel

pub enum PdfUaLevel {
    UA1,
    UA2,
}

PdfXLevel

pub enum PdfXLevel {
    X1a2001, X1a2003,
    X3_2002, X3_2003,
    X4, X4p,
    X5g, X5n, X5pg,
    X6, X6n, X6p,
}

Типы ошибок

PdfError

pub enum PdfError {
    Io(std::io::Error),
    Parse(String),
    Password,
    PageOutOfRange { index: usize, count: usize },
}
Вариант Описание
Io Ошибка файловой системы или ввода-вывода
Parse Повреждённая структура PDF
Password Документ зашифрован и пароль не предоставлен
PageOutOfRange Запрошенный индекс страницы превышает количество страниц

Следующие шаги