Skip to content

Огляд редагування

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

Підтримка редагування у різних прив’язках. Найбагатша поверхня редагування — у Python, Rust та WASM: вони підтримують операції зі сторінками, редагування тексту/зображень, роботу з анотаціями, шифрування і замазування. Go надає повноцінний API редактора (метадані, поворот/переміщення/видалення сторінок, стирання областей, заповнення/вирівнювання форм, обрізання, злиття, збереження з шифруванням). C# наразі підтримує редагування метаданих (Title/Author/Subject), заповнення форм (SetFormFieldValue), FlattenForms і Save/SaveAsync через DocumentEditor; операції на рівні сторінок, шифрування, замазування та редагування тексту/зображень ще не відкриті в публічному API C# — для цього використовуйте CLI, Go, Python або Rust.

Відкриття PDF для редагування

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")?;

Go

package main

import (
    "log"
    pdfoxide "github.com/yfedoseev/pdf_oxide/go"
)

func main() {
    editor, err := pdfoxide.OpenEditor("input.pdf")
    if err != nil { log.Fatal(err) }
    defer editor.Close()
}

C#

using PdfOxide;

using var editor = DocumentEditor.Open("input.pdf");

Java

import fyi.oxide.pdf.DocumentEditor;
import java.nio.file.Path;

try (DocumentEditor editor = DocumentEditor.open(Path.of("input.pdf"))) {
    // ...
}

Kotlin

import fyi.oxide.pdf.DocumentEditor
import java.nio.file.Path

DocumentEditor.open(Path.of("input.pdf")).use { editor ->
    // ...
}

Scala

import fyi.oxide.pdf.DocumentEditor
import scala.util.Using

Using.resource(DocumentEditor.open("input.pdf")) { editor =>
  // ...
}

Clojure

(require '[pdf-oxide.core :as pdf])

(with-open [editor (pdf/editor "input.pdf")]
  ;; ...
  )

Ruby

require 'pdf_oxide'

PdfOxide::DocumentEditor.open('input.pdf') do |editor|
  # ...
end

PHP

use PdfOxide\DocumentEditor;

$editor = DocumentEditor::open('input.pdf');

C++

#include <pdf_oxide/pdf_oxide.hpp>

auto editor = pdf_oxide::DocumentEditor::open("input.pdf");

Swift

import PdfOxide

let editor = try DocumentEditor.open("input.pdf")

Dart

import 'package:pdf_oxide/pdf_oxide.dart';

final editor = DocumentEditor.open('input.pdf');

R

library(pdfoxide)

editor <- pdf_editor_open("input.pdf")

Julia

using PdfOxide

editor = open_editor("input.pdf")

Zig

const pdf_oxide = @import("pdf_oxide");

var editor = try pdf_oxide.DocumentEditor.open("input.pdf");
defer editor.deinit();

Objective-C

#import "POXPdfOxide.h"

NSError *err = nil;
POXDocumentEditor *editor = [POXDocumentEditor openEditor:@"input.pdf" error:&err];

Elixir

{:ok, editor} = PdfOxide.open_editor("input.pdf")

Перевірка наявності змін

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

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());

Go

editor, _ := pdfoxide.OpenEditor("input.pdf")
defer editor.Close()

modified, _ := editor.IsModified()
fmt.Println(modified) // false

_ = editor.SetTitle("Updated Title")
modified, _ = editor.IsModified()
fmt.Println(modified) // true

C#

using var editor = DocumentEditor.Open("input.pdf");
Console.WriteLine(editor.IsModified); // false

editor.Title = "Updated Title";
Console.WriteLine(editor.IsModified); // true

PHP

$editor = DocumentEditor::open('input.pdf');
var_dump($editor->isModified()); // false

$editor->setProducer('pdf_oxide');
var_dump($editor->isModified()); // true

C++

auto editor = pdf_oxide::DocumentEditor::open("input.pdf");
bool before = editor.is_modified(); // false

editor.set_producer("pdf_oxide");
bool after = editor.is_modified(); // true

Swift

let editor = try DocumentEditor.open("input.pdf")
try editor.isModified() // false

try editor.setProducer("pdf_oxide")
try editor.isModified() // true

Dart

final editor = DocumentEditor.open('input.pdf');
editor.isModified(); // false

editor.setProducer('pdf_oxide');
editor.isModified(); // true

R

editor <- pdf_editor_open("input.pdf")
pdf_editor_is_modified(editor) # FALSE

pdf_editor_set_producer(editor, "pdf_oxide")
pdf_editor_is_modified(editor) # TRUE

Julia

editor = open_editor("input.pdf")
is_modified(editor) # false

set_producer(editor, "pdf_oxide")
is_modified(editor) # true

Zig

var editor = try pdf_oxide.DocumentEditor.open("input.pdf");
defer editor.deinit();
_ = editor.isModified(); // false

try editor.setProducer("pdf_oxide");
_ = editor.isModified(); // true

Objective-C

NSError *err = nil;
POXDocumentEditor *editor = [POXDocumentEditor openEditor:@"input.pdf" error:&err];
[editor isModified]; // NO

[editor setProducer:@"pdf_oxide" error:&err];
[editor isModified]; // YES

Elixir

{:ok, editor} = PdfOxide.open_editor("input.pdf")
PdfOxide.editor_modified?(editor) # false

PdfOxide.set_producer(editor, "pdf_oxide")
PdfOxide.editor_modified?(editor) # true

Збереження

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")?;

Go

editor, _ := pdfoxide.OpenEditor("input.pdf")
defer editor.Close()

_ = editor.SetTitle("New Title")
_ = editor.Save("output.pdf")

C#

using var editor = DocumentEditor.Open("input.pdf");
editor.Title = "New Title";
editor.Save("output.pdf");

PHP

$editor = DocumentEditor::open('input.pdf');
$editor->setProducer('pdf_oxide');
$editor->saveTo('output.pdf');

C++

auto editor = pdf_oxide::DocumentEditor::open("input.pdf");
editor.set_producer("pdf_oxide");
editor.save("output.pdf");

Swift

let editor = try DocumentEditor.open("input.pdf")
try editor.setProducer("pdf_oxide")
try editor.save("output.pdf")

Dart

final editor = DocumentEditor.open('input.pdf');
editor.setProducer('pdf_oxide');
editor.save('output.pdf');

R

editor <- pdf_editor_open("input.pdf")
pdf_editor_set_producer(editor, "pdf_oxide")
pdf_editor_save(editor, "output.pdf")

Julia

editor = open_editor("input.pdf")
set_producer(editor, "pdf_oxide")
save(editor, "output.pdf")

Zig

var editor = try pdf_oxide.DocumentEditor.open("input.pdf");
defer editor.deinit();
try editor.setProducer("pdf_oxide");
try editor.save("output.pdf");

Objective-C

NSError *err = nil;
POXDocumentEditor *editor = [POXDocumentEditor openEditor:@"input.pdf" error:&err];
[editor setProducer:@"pdf_oxide" error:&err];
[editor saveToPath:@"output.pdf" error:&err];

Elixir

{:ok, editor} = PdfOxide.open_editor("input.pdf")
PdfOxide.set_producer(editor, "pdf_oxide")
PdfOxide.editor_save(editor, "output.pdf")

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

Метадані документа

Читання та запис стандартних полів метаданих PDF: заголовок, автор, тема й ключові слова.

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")?;

Go

editor, _ := pdfoxide.OpenEditor("input.pdf")
defer editor.Close()

if t, err := editor.Title(); err == nil { fmt.Println("Current title:", t) }
if a, err := editor.Author(); err == nil { fmt.Println("Current author:", a) }

_ = editor.SetTitle("Quarterly Report")
_ = editor.SetAuthor("Jane Smith")
_ = editor.SetSubject("Q4 2025 Financial Results")

_ = editor.Save("output.pdf")

C#

using var editor = DocumentEditor.Open("input.pdf");

if (editor.Title is { } t) Console.WriteLine($"Current title: {t}");
if (editor.Author is { } a) Console.WriteLine($"Current author: {a}");
if (editor.Subject is { } s) Console.WriteLine($"Current subject: {s}");

editor.Title = "Quarterly Report";
editor.Author = "Jane Smith";
editor.Subject = "Q4 2025 Financial Results";

editor.Save("output.pdf");

Інформація про документ

Шлях до джерела та версія

use pdf_oxide::editor::DocumentEditor;

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

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

// PDF version as (major, minor)
let (major, minor) = editor.version();
println!("PDF version: {}.{}", major, minor);

// Number of pages
println!("Pages: {}", editor.current_page_count());

Повний довідник API

DocumentEditor

Метод Повертає Опис
open(path) Result<DocumentEditor> Відкрити PDF для редагування
is_modified() bool Перевірити наявність змін
source_path() &str Шлях до вихідного PDF
source() &PdfDocument Доступ до вихідного документа лише для читання
version() (u8, u8) Версія PDF (мажорна, мінорна)
current_page_count() usize Кількість сторінок у документі
title() Result<Option<String>> Отримати заголовок документа
set_title(title) () Задати заголовок документа
author() Result<Option<String>> Отримати автора документа
set_author(author) () Задати автора документа
subject() Result<Option<String>> Отримати тему документа
set_subject(subject) () Задати тему документа
keywords() Result<Option<String>> Отримати ключові слова документа
set_keywords(keywords) () Задати ключові слова документа
save(path) Result<()> Зберегти з повним перезаписуванням
save_with_options(path, options) Result<()> Зберегти з користувацькими параметрами

Pdf (уніфікований API)

Метод Повертає Опис
Pdf::open(path) Result<Pdf> Відкрити PDF для редагування
Pdf::open_editor(path) Result<DocumentEditor> Відкрити напряму як DocumentEditor
is_modified() bool Перевірити наявність змін
save(path) Result<()> Зберегти документ
save_as(path) Result<()> Зберегти за новим шляхом
page(index) Result<PdfPage> Отримати сторінку для DOM-редагування
save_page(page) Result<()> Записати змінену сторінку назад
editor() Option<&mut DocumentEditor> Отримати доступ до внутрішнього редактора

Трейт EditableDocument

Трейт 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<()>;
}

Повний перелік методів DocumentEditor

Таблиці нижче перелічують усі публічні методи DocumentEditor / Pdf-редактора в Rust. Кожен рядок посилається на детальний посібник, де це можливо. Зазначена підтримка у різних прив’язках; приклади для Go / C# дивіться на відповідних сторінках.

Метадані

Метод Rust Python WASM Go C# Сторінка
title / set_title Огляд
author / set_author Огляд
subject / set_subject Огляд
keywords / set_keywords Огляд
producer / set_producer Огляд
creation_date / set_creation_date Огляд
apply_metadata(info) Огляд

Операції зі сторінками

Метод Rust Python WASM Go C# Сторінка
remove_page / delete_page Сторінки
move_page(from, to) Сторінки
duplicate_page(i) Сторінки
get_page_rotation / set_page_rotation Сторінки
rotate_page_by(i, deg) Сторінки
rotate_all_pages(deg) Сторінки
get_page_media_box / set_page_media_box Сторінки
get_page_crop_box / set_page_crop_box Сторінки
crop_margins(l, r, t, b) Сторінки
erase_region(page, rect) Сторінки
erase_regions(page, rects) Сторінки
clear_erase_regions(page) Сторінки

Об’єднання / розділення

Метод Rust Python WASM Go C# Сторінка
merge_from(path) Об’єднання та розділення
merge_pages_from(path, pages) Об’єднання та розділення
extract_pages(pages, output) Об’єднання та розділення
Merge([]paths) верхній рівень Об’єднання та розділення

Форми

Метод Rust Python WASM Go C# Сторінка
get_form_fields() Форми
get_form_field_value(name) Форми
has_form_field(name) Форми
set_form_field_value(name, value) Форми
add_form_field(widget, page) Створення форм
add_parent_field / add_child_field Створення форм
remove_form_field(name) Форми
set_form_field_* (readonly, required, tooltip, rect, max_length, alignment, colors, flags) Форми
flatten_forms_on_page(page) Форми
flatten_forms() Форми
export_form_data_fdf(path) Форми
export_form_data_xfdf(path) Форми

Анотації

Метод Rust Python WASM Go C# Сторінка
flatten_page_annotations(page) Анотації
flatten_all_annotations() Анотації
is_page_marked_for_annotation_flatten(page) Анотації
unmark_page_for_annotation_flatten(page) Анотації

Замазування

Метод Rust Python WASM Go C# Сторінка
apply_page_redactions(page) Замазування
apply_all_redactions() Замазування
is_page_marked_for_redaction(page) Замазування
unmark_page_for_redaction(page) Замазування

XFA

Метод Rust Python WASM Go C# Сторінка
has_xfa() XFA-форми
analyze_xfa() XFA-форми
convert_xfa_to_acroform(opts) XFA-форми

Збереження

Метод Rust Python WASM Go C# Сторінка
save(path) Огляд
save_with_options(path, opts) Шифрування
save_encrypted(path, user, owner) Шифрування
save_with_encryption(path, cfg) Шифрування
save_async / SaveAsync Асинхронність

Допоміжні методи (зручності Go)

Методи, доступні як методи DocumentEditor у Go; у Rust — через editor.source():

Метод Rust Python WASM Go C#
IsModified is_modified() is_modified IsModified() IsModified
SourcePath source_path() source_path SourcePath() SourcePath
Version version() version() Version()
PageCount current_page_count() page_count() pageCount() PageCount() PageCount
RemoveHeaders / RemoveFooters / RemoveArtifacts
Close / Dispose Drop context manager free() Close() Dispose()

Повний робочий процес редагування

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

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")?;

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