Skip to content

编辑概述

PDF Oxide 为编辑现有 PDF 提供了两个层次的 API:推荐使用的高层 Pdf 类,以及底层 DocumentEditor。两者均可打开 PDF、修改内容和元数据、追踪变更并保存结果。

各语言绑定的编辑功能覆盖情况。 编辑功能最完整的是 PythonRustWASM,涵盖页面操作、文本/图像编辑、注释处理、加密和遮蔽。Go 提供了丰富的编辑器 API(元数据、页面旋转/移动/删除、区域擦除、表单填写/扁平化、裁剪、合并、加密保存)。C# 目前支持元数据编辑(Title/Author/Subject)、表单填写(SetFormFieldValue)、FlattenForms,以及 DocumentEditor 上的 Save/SaveAsync;页面级操作、加密、遮蔽和文本/图像编辑尚未在 C# 公共 API 中开放——对于这些功能,请使用 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

使用统一的 Pdf API:

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 Trait

EditableDocument trait 定义了核心编辑契约:

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 完整方法列表

下表列出了 Rust 中 DocumentEditor / Pdf 编辑器的全部公共方法。每行在适用时链接到对应的深度指南,并注明了各语言绑定的支持情况。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 便捷方法)

在 Go 中以 DocumentEditor 方法形式暴露,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")?;

相关页面