Skip to content

Объединение и разделение PDF — Python / Rust / Go

Доступность по биндингам. Объединение PDF доступно в Python, Rust и Go. Разделение через extract_pages пока есть только в Python и Rust. Биндинги C# и WASM этих операций редактора ещё не раскрывают — в качестве обходного пути используйте Rust CLI (pdf-oxide merge, pdf-oxide split) или вызывайте функциональность через один из поддерживаемых биндингов.

Объедините два PDF в один:

Python

from pdf_oxide import PdfDocument

doc = PdfDocument("main.pdf")
doc.merge_from("appendix.pdf")
doc.save("combined.pdf")

WASM

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

// Загрузите оба PDF как Uint8Array
const mainDoc = new WasmPdfDocument(mainBytes);
const appendixDoc = new WasmPdfDocument(appendixBytes);
// Извлеките текст из обоих документов и обработайте как нужно
const allText = mainDoc.extractAllText() + "\n" + appendixDoc.extractAllText();
mainDoc.free();
appendixDoc.free();

Rust

use pdf_oxide::editor::DocumentEditor;

let mut editor = DocumentEditor::open("main.pdf")?;
editor.merge_from("appendix.pdf")?;
editor.save("combined.pdf")?;

Go

package main

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

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

    if _, err := editor.MergeFrom("appendix.pdf"); err != nil { log.Fatal(err) }
    if err := editor.Save("combined.pdf"); err != nil { log.Fatal(err) }
}

PDF Oxide объединяет страницы на уровне PDF-объектов — шрифты, изображения и аннотации корректно переносятся между документами.

Установка

pip install pdf_oxide

Объединение PDF

Добавить все страницы

Добавьте каждую страницу из второго PDF в конец первого:

Python

from pdf_oxide import PdfDocument

doc = PdfDocument("report.pdf")
doc.merge_from("charts.pdf")
doc.save("full-report.pdf")

WASM

// WASM API: загрузка и обработка нескольких документов
const report = new WasmPdfDocument(reportBytes);
const charts = new WasmPdfDocument(chartsBytes);
// Обработать оба документа вместе
const fullText = report.extractAllText() + "\n" + charts.extractAllText();
report.free();
charts.free();

Rust

let mut editor = DocumentEditor::open("report.pdf")?;
let pages_added = editor.merge_from("charts.pdf")?;
println!("Добавлено страниц: {}", pages_added);
editor.save("full-report.pdf")?;

Go

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

added, _ := editor.MergeFrom("charts.pdf")
fmt.Printf("Добавлено страниц: %d\n", added)
_ = editor.Save("full-report.pdf")

Объединить несколько файлов

Статический метод Pdf.merge() собирает несколько PDF в один вызов:

Python

from pdf_oxide import Pdf

pdf = Pdf.merge(["intro.pdf", "chapter1.pdf", "chapter2.pdf", "appendix.pdf"])
pdf.save("book.pdf")

То же самое можно сделать цепочкой merge_from() поверх существующего документа:

from pdf_oxide import PdfDocument

doc = PdfDocument("intro.pdf")
for f in ["chapter1.pdf", "chapter2.pdf", "appendix.pdf"]:
    doc.merge_from(f)
doc.save("book.pdf")

WASM

// Последовательно загрузите и обработайте несколько PDF
const files = [introBytes, ch1Bytes, ch2Bytes, appendixBytes];
const allText = [];
for (const bytes of files) {
    const doc = new WasmPdfDocument(bytes);
    allText.push(doc.extractAllText());
    doc.free();
}
console.log(allText.join("\n"));

Rust

let files = ["intro.pdf", "chapter1.pdf", "chapter2.pdf", "appendix.pdf"];
let mut editor = DocumentEditor::open(files[0])?;
for f in &files[1..] {
    editor.merge_from(f)?;
}
editor.save("book.pdf")?;

Go

// Merge верхнего уровня возвращает байты итогового PDF одним вызовом
bytes, err := pdfoxide.Merge([]string{
    "intro.pdf", "chapter1.pdf", "chapter2.pdf", "appendix.pdf",
})
if err != nil { log.Fatal(err) }
_ = os.WriteFile("book.pdf", bytes, 0644)

Объединить выбранные страницы

Выберите, какие страницы брать из исходного документа:

Python

from pdf_oxide import PdfDocument

doc = PdfDocument("main.pdf")
# Взять только страницы 0, 2 и 4 из источника
doc.merge_pages_from("source.pdf", [0, 2, 4])
doc.save("selected.pdf")

Rust

let mut editor = DocumentEditor::open("main.pdf")?;
editor.merge_pages_from("source.pdf", &[0, 2, 4])?;
editor.save("selected.pdf")?;

Разделение PDF

Извлечь страницы в новый файл

Выньте нужные страницы из большого документа:

Python

from pdf_oxide import PdfDocument

doc = PdfDocument("book.pdf")
doc.extract_pages([0, 1, 2, 3, 4], "chapter1.pdf")

WASM

// Извлеките текст с конкретных страниц
const doc = new WasmPdfDocument(bytes);
const pages = [0, 1, 2, 3, 4];
for (const i of pages) {
    const text = doc.extractText(i);
    console.log(`Страница ${i + 1}: ${text.slice(0, 80)}...`);
}
doc.free();

Rust

let mut editor = DocumentEditor::open("book.pdf")?;
editor.extract_pages(&[0, 1, 2, 3, 4], "chapter1.pdf")?;

Разделить постранично

Сохраните каждую страницу в отдельный файл:

Python

from pdf_oxide import PdfDocument

doc = PdfDocument("document.pdf")
for i in range(doc.page_count()):
    doc.extract_pages([i], f"page_{i + 1}.pdf")

Rust

let mut editor = DocumentEditor::open("document.pdf")?;
let page_count = editor.page_count()?;
for i in 0..page_count {
    editor.extract_pages(&[i], &format!("page_{}.pdf", i + 1))?;
}

Разбить на части по N страниц

Разделите большой PDF на файлы по N страниц:

Python

from pdf_oxide import PdfDocument

doc = PdfDocument("large.pdf")
chunk_size = 10

for start in range(0, doc.page_count(), chunk_size):
    end = min(start + chunk_size, doc.page_count())
    pages = list(range(start, end))
    doc.extract_pages(pages, f"chunk_{start // chunk_size + 1}.pdf")

Rust

let mut editor = DocumentEditor::open("large.pdf")?;
let page_count = editor.page_count()?;
let chunk_size = 10;

for start in (0..page_count).step_by(chunk_size) {
    let end = (start + chunk_size).min(page_count);
    let pages: Vec<usize> = (start..end).collect();
    editor.extract_pages(&pages, &format!("chunk_{}.pdf", start / chunk_size + 1))?;
}

Связанные страницы