Skip to content

Редагування PDF — Огляд

PDF Oxide надає два рівні API для редагування існуючих PDF: високорівневий клас Pdf (рекомендований) та низькорівневий DocumentEditor. Обидва дозволяють відкрити PDF, змінити його вміст та метадані, відстежувати зміни та зберегти результат.

Opening a PDF for Editing

Python

from pdf_oxide import PdfDocument

doc = PdfDocument("input.pdf")

Редактор ініціалізується ліниво при першій модифікації. Ви можете почати читання одразу, а редактор активується при виклику будь-якого мутуючого методу, такого як set_title() або page().

WASM

import { WasmPdfDocument } from "pdf-oxide-wasm";

const bytes = new Uint8Array(/* file bytes */);
const doc = new WasmPdfDocument(bytes);

Rust

Використовуйте уніфікований API Pdf:

use pdf_oxide::api::Pdf;

let mut doc = Pdf::open("input.pdf")?;

Або використовуйте DocumentEditor безпосередньо для низькорівневого контролю:

use pdf_oxide::editor::DocumentEditor;

let mut editor = DocumentEditor::open("input.pdf")?;

Checking for Modifications

Перед збереженням ви можете перевірити, чи були зроблені які-небудь зміни:

Python

doc = PdfDocument("input.pdf")
print(doc.is_modified)  # False -- no changes yet

doc.set_title("Updated Title")
print(doc.is_modified)  # True

Rust

let mut doc = Pdf::open("input.pdf")?;
assert!(!doc.is_modified());

doc.editor().unwrap().set_title("Updated Title");
assert!(doc.is_modified());

Saving

Python

doc = PdfDocument("input.pdf")
doc.set_title("New Title")
doc.save("output.pdf")

WASM

import { WasmPdfDocument } from "pdf-oxide-wasm";

const bytes = new Uint8Array(/* file bytes */);
const doc = new WasmPdfDocument(bytes);
doc.setTitle("New Title");
const output = doc.save();
doc.free();

Rust

let mut doc = Pdf::open("input.pdf")?;
doc.editor().unwrap().set_title("New Title");
doc.save("output.pdf")?;

// Or save to a new path
doc.save_as("copy.pdf")?;

Метод save() за замовчуванням виконує повне перезаписування PDF. Для розширених опцій збереження (інкрементальні оновлення, шифрування) дивіться Шифрування та безпека.

Document Metadata

Read and write the standard PDF metadata fields: title, author, subject, and keywords.

Python

from pdf_oxide import PdfDocument

doc = PdfDocument("input.pdf")

# Set metadata
doc.set_title("Quarterly Report")
doc.set_author("Jane Smith")
doc.set_subject("Q4 2025 Financial Results")
doc.set_keywords("finance, quarterly, 2025")

doc.save("output.pdf")

WASM

import { WasmPdfDocument } from "pdf-oxide-wasm";

const bytes = new Uint8Array(/* file bytes */);
const doc = new WasmPdfDocument(bytes);

// Set metadata
doc.setTitle("Quarterly Report");
doc.setAuthor("Jane Smith");
doc.setSubject("Q4 2025 Financial Results");
doc.setKeywords("finance, quarterly, 2025");

const output = doc.save();
doc.free();

Rust

use pdf_oxide::editor::DocumentEditor;

let mut editor = DocumentEditor::open("input.pdf")?;

// Read metadata
if let Some(title) = editor.title()? {
    println!("Current title: {}", title);
}
if let Some(author) = editor.author()? {
    println!("Current author: {}", author);
}
if let Some(subject) = editor.subject()? {
    println!("Current subject: {}", subject);
}
if let Some(keywords) = editor.keywords()? {
    println!("Current keywords: {}", keywords);
}

// Set metadata
editor.set_title("Quarterly Report");
editor.set_author("Jane Smith");
editor.set_subject("Q4 2025 Financial Results");
editor.set_keywords("finance, quarterly, 2025");

editor.save("output.pdf")?;

Document Information

Source Path and Version

use pdf_oxide::editor::DocumentEditor;

let editor = DocumentEditor::open("input.pdf")?;

// Path to the original file
println!("Source: {}", editor.source_path());

// Версія PDF as (major, minor)
let (major, minor) = editor.version();
println!("Версія PDF: {}.{}", major, minor);

// Кількість сторінок
println!("Pages: {}", editor.current_page_count());

Full API Reference

DocumentEditor

Метод Повертає Опис
open(path) Result<DocumentEditor> Open a PDF for editing
is_modified() bool Check if any changes have been made
source_path() &str Path to the source PDF
source() &PdfDocument Read-only access to the source document
version() (u8, u8) Версія PDF (major, minor)
current_page_count() usize Кількість сторінок у документі
title() Result<Option<String>> Get document title
set_title(title) () Встановити назву документа
author() Result<Option<String>> Get document author
set_author(author) () Встановити автора документа
subject() Result<Option<String>> Get document subject
set_subject(subject) () Встановити тему документа
keywords() Result<Option<String>> Get document keywords
set_keywords(keywords) () Встановити ключові слова документа
save(path) Result<()> Save with full rewrite
save_with_options(path, options) Result<()> Save with custom options

Pdf (Unified API)

Метод Повертає Опис
Pdf::open(path) Result<Pdf> Open a PDF for editing
Pdf::open_editor(path) Result<DocumentEditor> Open directly as DocumentEditor
is_modified() bool Check if changes exist
save(path) Result<()> Зберегти документ
save_as(path) Result<()> Save to a new path
page(index) Result<PdfPage> Get a page for DOM editing
save_page(page) Result<()> Save a modified page back
editor() Option<&mut DocumentEditor> Доступ до базового редактора

EditableDocument Trait

Трейт EditableDocument визначає основний контракт редагування:

pub trait EditableDocument {
    fn get_info(&mut self) -> Result<DocumentInfo>;
    fn set_info(&mut self, info: DocumentInfo) -> Result<()>;
    fn page_count(&mut self) -> Result<usize>;
    fn get_page_info(&mut self, index: usize) -> Result<PageInfo>;
    fn remove_page(&mut self, index: usize) -> Result<()>;
    fn move_page(&mut self, from: usize, to: usize) -> Result<()>;
    fn duplicate_page(&mut self, index: usize) -> Result<usize>;
    fn save(&mut self, path: impl AsRef<Path>) -> Result<()>;
    fn save_with_options(&mut self, path: impl AsRef<Path>, options: SaveOptions) -> Result<()>;
}

Complete Edit Workflow

Цей приклад демонструє повну сесію редагування: відкрити, перевірити, змінити метадані, відредагувати вміст і зберегти.

Python

from pdf_oxide import PdfDocument

# Open the document
doc = PdfDocument("report.pdf")
print(f"Pages: {doc.page_count()}")

# Update metadata
doc.set_title("Annual Report 2025")
doc.set_author("Finance Team")

# Edit text on page 0
page = doc.page(0)
for text in page.find_text_containing("DRAFT"):
    page.set_text(text.id, "FINAL")
doc.save_page(page)

# Save
doc.save("report-final.pdf")

Rust

use pdf_oxide::api::Pdf;

let mut doc = Pdf::open("report.pdf")?;
println!("Pages: {}", doc.page_count()?);

// Update metadata
{
    let editor = doc.editor().unwrap();
    editor.set_title("Annual Report 2025");
    editor.set_author("Finance Team");
}

// Edit text on page 0
let mut page = doc.page(0)?;
let drafts = page.find_text_containing("DRAFT");
for t in &drafts {
    page.set_text(t.id(), "FINAL")?;
}
doc.save_page(page)?;

// Save
doc.save("report-final.pdf")?;

Пов’язані сторінки