Markdown変換
PDF OxideはPDFページをクリーンで読みやすいMarkdownに変換します。変換パイプラインはテキストスパンを抽出し、行にクラスタリングし、タグ付きPDFでは見出しやリストの役割を/StructTreeRootから参照し、複数段組のガターや逆方向x読み取り順の折り返しを検出し、段落をグループ化してMarkdown構文を出力します。
v0.3.36以降、タグ付きPDFでは、フォントサイズから見出しレベルを再導出する代わりに、StructRole(Heading(1..6) | ListItem | ListItemLabel | ListItemBody)を/StructTreeRootから直接読み込みます。ロール情報はネストされたMCR(H1 → Span → MCR、LI → LBody → Span → MCR)を通じて伝播されます。タグなしドキュメントでは、ジオメトリックフォールバックが引き続き適用されます:太字 + 5%サイズアップでH4に昇格し、is_ordered_list_markerが1. / 12. / a) / iv. / A.を認識しながら、図のキャプションや年号を除外します。
複数段組の処理: > max(3 × font_size, 30 pt)で分離された同一ベースラインのスパンは、列をまたぐものとして扱われます。逆方向x読み取り順の折り返し(列優先の末尾→先頭スパン)は、意味不明なトークンに連結される代わりに段落を分割します。
RTL: bidi並び替えはデフォルトでオフです。以前の無条件な視覚的→論理的並び替えは、論理順のPDF(ヘブライ語בנימיןが逆順になっていた)を破壊していました。アラビア語の文脈グリフ周辺の誤った**bold**マーカーは除去されます。入力が視覚順の場合、呼び出し元はtext::bidi::reorder_visual_to_logicalを手動で呼び出せます(Rust)。
インライン画像は200 KBのbase64ペイロード上限に制限されています(v0.3.36追加)。上限を超えた画像は元のサイズを示すHTMLコメントを出力します。ディスクに書き出すにはimage_output_dirを使用してください。
クイックサンプル
Python
from pdf_oxide import PdfDocument
doc = PdfDocument("paper.pdf")
md = doc.to_markdown(0, detect_headings=True)
print(md)
Node.js
const { PdfDocument } = require("pdf-oxide");
const doc = new PdfDocument("paper.pdf");
const md = doc.toMarkdown(0, { detectHeadings: true });
console.log(md);
doc.close();
Go
import pdfoxide "github.com/yfedoseev/pdf_oxide/go"
doc, _ := pdfoxide.Open("paper.pdf")
defer doc.Close()
md, _ := doc.ToMarkdown(0)
fmt.Println(md)
C#
using PdfOxide.Core;
using var doc = PdfDocument.Open("paper.pdf");
var md = doc.ToMarkdown(0);
Console.WriteLine(md);
WASM
const doc = new WasmPdfDocument(bytes);
const md = doc.toMarkdown(0, true);
console.log(md);
Rust
use pdf_oxide::PdfDocument;
use pdf_oxide::converters::ConversionOptions;
let mut doc = PdfDocument::open("paper.pdf")?;
let options = ConversionOptions { detect_headings: true, ..Default::default() };
let md = doc.to_markdown(0, &options)?;
println!("{}", md);
Java
import fyi.oxide.pdf.PdfDocument;
try (PdfDocument doc = PdfDocument.open(java.nio.file.Path.of("paper.pdf"))) {
String md = doc.toMarkdown(0);
System.out.println(md);
}
Kotlin
import fyi.oxide.pdf.PdfDocument
PdfDocument.open(java.nio.file.Path.of("paper.pdf")).use { doc ->
val md = doc.toMarkdown(0)
println(md)
}
Scala
import fyi.oxide.pdf.PdfDocument
import scala.util.Using
Using.resource(PdfDocument.open("paper.pdf")) { doc =>
val md = doc.toMarkdown(0)
println(md)
}
Clojure
(require '[pdf-oxide.core :as pdf])
(with-open [doc (pdf/open "paper.pdf")]
(println (pdf/to-markdown doc 0)))
PHP
use PdfOxide\PdfDocument;
$doc = PdfDocument::open('paper.pdf');
echo $doc->toMarkdown(0);
$doc->close();
Ruby
require 'pdf_oxide'
PdfOxide::PdfDocument.open('paper.pdf') do |doc|
puts doc.to_markdown(0)
end
C++
#include <pdf_oxide/pdf_oxide.hpp>
auto doc = pdf_oxide::Document::open("paper.pdf");
auto md = doc.to_markdown(0);
std::cout << md << std::endl;
Swift
import PdfOxide
let doc = try Document.open("paper.pdf")
let md = try doc.toMarkdown(0)
print(md)
Dart
import 'package:pdf_oxide/pdf_oxide.dart';
final doc = PdfDocument.open('paper.pdf');
final md = doc.toMarkdown(0);
print(md);
R
library(pdfoxide)
doc <- pdf_open("paper.pdf")
md <- pdf_to_markdown(doc, 0)
cat(md)
Julia
using PdfOxide
doc = open_document("paper.pdf")
md = to_markdown(doc, 0)
println(md)
Zig
const pdf_oxide = @import("pdf_oxide");
const a = std.heap.page_allocator;
var doc = try pdf_oxide.Document.open("paper.pdf");
const md = try doc.toMarkdown(a, 0);
std.debug.print("{s}\n", .{md});
Objective-C
#import "POXPdfOxide.h"
NSError *err = nil;
POXDocument *doc = [POXDocument openPath:@"paper.pdf" error:&err];
NSString *md = [doc toMarkdown:0 error:&err];
NSLog(@"%@", md);
Elixir
{:ok, doc} = PdfOxide.open("paper.pdf")
{:ok, md} = PdfOxide.to_markdown(doc, 0)
IO.puts(md)
APIリファレンス
to_markdown(page_index, ...) -> str
単一ページをMarkdownに変換します。
Python Signature
doc.to_markdown(
page: int,
preserve_layout: bool = False,
detect_headings: bool = True,
include_images: bool = True,
image_output_dir: str | None = None,
embed_images: bool = True,
) -> str
JavaScript Signature
doc.toMarkdown(pageIndex, detectHeadings?, includeImages?, includeFormFields?) -> string
Rust Signature
pub fn to_markdown(
&mut self,
page_index: usize,
options: &ConversionOptions,
) -> Result<String>
Java Signature
String toMarkdown(int pageIndex)
Kotlin Signature
fun toMarkdown(pageIndex: Int): String
Scala Signature
def toMarkdown(pageIndex: Int): String
Clojure Signature
(pdf/to-markdown doc page-index) ; => String
PHP Signature
public function toMarkdown(int $pageIndex): string
Ruby Signature
doc.to_markdown(page_index) # => String
C++ Signature
std::string to_markdown(int page_index) const;
Swift Signature
func toMarkdown(_ pageIndex: Int) throws -> String
Dart Signature
String toMarkdown(int pageIndex)
R Signature
pdf_to_markdown(doc, page_index) # character
Julia Signature
to_markdown(doc, page_index)::String
Zig Signature
pub fn toMarkdown(self: *Document, allocator: std.mem.Allocator, page_index: usize) ![]u8
Objective-C Signature
- (NSString *)toMarkdown:(NSInteger)pageIndex error:(NSError **)error;
Elixir Signature
PdfOxide.to_markdown(doc, page_index) :: {:ok, String.t()} | {:error, term()}
| パラメータ | 型 | デフォルト | 説明 |
|---|---|---|---|
page_index |
int / usize / number |
– | 0始まりのページインデックス |
preserve_layout |
bool |
false |
視覚的レイアウトの配置を保持 |
detect_headings |
bool |
true |
フォントサイズと太さに基づいて見出しを検出 |
include_images |
bool |
true |
出力に画像を含める |
image_output_dir |
str / None |
None |
抽出した画像の保存先ディレクトリ(Python/Rustのみ)。200 KBインライン上限の影響を受けない。 |
embed_images |
bool |
true |
画像をbase64データURIとして埋め込む(Python/Rustのみ)。200 KBを超えるペイロードは元のサイズを示すプレースホルダーHTMLコメントを出力(v0.3.36)。 |
include_form_fields |
bool |
true |
フォームフィールドの値を含める(Python/JS) |
返り値: ページのMarkdown文字列。
to_markdown_all(...) -> str
全ページをMarkdownに変換し、水平線(---)で区切って結合します。
Python Signature
doc.to_markdown_all(
preserve_layout: bool = False,
detect_headings: bool = True,
include_images: bool = True,
image_output_dir: str | None = None,
embed_images: bool = True,
) -> str
JavaScript Signature
doc.toMarkdownAll(detectHeadings?, includeImages?, includeFormFields?) -> string
Rust Signature
pub fn to_markdown_all(
&mut self,
options: &ConversionOptions,
) -> Result<String>
Java Signature
String toMarkdown() // no-arg overload = whole document
Kotlin Signature
fun toMarkdown(): String // no-arg = whole document
Scala Signature
def toMarkdown(): String // no-arg = whole document
Clojure Signature
(pdf/to-markdown doc) ; no page index = whole document => String
PHP Signature
public function toMarkdownAll(): string
Ruby Signature
doc.to_markdown # nil page index = whole document => String
C++ Signature
std::string to_markdown_all() const;
Swift Signature
func toMarkdownAll() throws -> String
Dart Signature
String toMarkdownAll()
R Signature
pdf_to_markdown_all(doc) # character
Julia Signature
to_markdown_all(doc)::String
Zig Signature
pub fn toMarkdownAll(self: *Document, allocator: std.mem.Allocator) ![]u8
Objective-C Signature
- (NSString *)toMarkdownAllWithError:(NSError **)error;
Elixir Signature
PdfOxide.to_markdown_all(doc) :: {:ok, String.t()} | {:error, term()}
| パラメータ | 型 | デフォルト | 説明 |
|---|---|---|---|
preserve_layout |
bool |
false |
視覚的レイアウトを保持 |
detect_headings |
bool |
true |
見出しを検出 |
include_images |
bool |
true |
画像を含める |
image_output_dir |
str / None |
None |
画像の出力ディレクトリ |
embed_images |
bool |
true |
画像をbase64として埋め込む |
返り値: 全ページを---セパレータで結合したMarkdown文字列。
to_markdown_with_ocr(page_index, model_path, options) -> str
スキャン済みページへのOCRフォールバック付きでMarkdownに変換します。ページから抽出できるテキストが少ないか皆無の場合、レンダリング済みページ画像からテキストを認識するためにOCRが使用されます。ocrフィーチャーが必要です。
| パラメータ | 型 | 説明 |
|---|---|---|
page_index |
usize |
0始まりのページインデックス |
model_path |
&str |
OCRモデルファイルへのパス |
options |
&ConversionOptions |
変換オプション |
Rust
let mut doc = PdfDocument::open("scanned.pdf")?;
let options = ConversionOptions { detect_headings: true, ..Default::default() };
let md = doc.to_markdown_with_ocr(0, "/path/to/models", &options)?;
println!("{}", md);
ConversionOptions
ConversionOptions構造体はすべての変換動作を制御します。
| フィールド | 型 | デフォルト | 説明 |
|---|---|---|---|
preserve_layout |
bool |
false |
配置付きで視覚的レイアウトを保持 |
detect_headings |
bool |
true |
フォントサイズクラスターから見出しを自動検出 |
extract_tables |
bool |
false |
表を抽出(試験的) |
include_images |
bool |
true |
出力に画像を含める |
image_output_dir |
Option<String> |
None |
このディレクトリに画像を保存 |
embed_images |
bool |
true |
画像をbase64データURIとして埋め込む |
reading_order_mode |
ReadingOrderMode |
Auto |
読み取り順の決定方法 |
bold_marker_behavior |
BoldMarkerBehavior |
Conservative |
太字マーカーの適用戦略 |
動作原理
Markdown変換パイプラインは複数の段階で動作します:
-
テキスト抽出 – ページコンテンツストリームから
TextSpanオブジェクトを抽出し、テキスト、位置、フォント、サイズ、ウェイト、色を取得します。 -
文字クラスタリング – 文字間のギャップに基づいて文字を単語にグループ化し、次に垂直方向の近接性に基づいて単語を行にグループ化します。
-
読み取り順 – タグ付きPDF構造ツリー(優先)またはテキストブロック位置のグラフベース空間解析を使用して読み取り順を決定します。
-
見出し検出 –
detect_headingsが有効な場合、ページ全体のフォントサイズをクラスタリングして見出しレベルを特定します。より大きく太いテキストは#、##、###見出しにマッピングされます。 -
フォーマット – フォントウェイトとスタイルメタデータに基づいて太字(
**text**)と斜体(*text*)マーカーを適用します。 -
表の検出 – 整列したテキストブロックの空間解析を使用して表形式レイアウトを識別し、GFMスタイルのMarkdown表を出力します。
-
空白の整理 – 間隔を正規化し、冗長な空白行を削除し、段落区切りの一貫性を確保します。
応用例
PDF全体をMarkdownファイルに変換
Python
from pdf_oxide import PdfDocument
doc = PdfDocument("book.pdf")
md = doc.to_markdown_all(detect_headings=True)
with open("book.md", "w", encoding="utf-8") as f:
f.write(md)
Node.js
const fs = require("node:fs");
const doc = new PdfDocument("book.pdf");
const md = doc.toMarkdownAll();
fs.writeFileSync("book.md", md);
doc.close();
Go
doc, _ := pdfoxide.Open("book.pdf")
defer doc.Close()
md, _ := doc.ToMarkdownAll()
os.WriteFile("book.md", []byte(md), 0644)
C#
using var doc = PdfDocument.Open("book.pdf");
var md = doc.ToMarkdownAll();
File.WriteAllText("book.md", md);
WASM
const doc = new WasmPdfDocument(bytes);
const md = doc.toMarkdownAll(true);
writeFileSync("book.md", md);
doc.free();
Java
import fyi.oxide.pdf.PdfDocument;
import java.nio.file.*;
try (PdfDocument doc = PdfDocument.open(Path.of("book.pdf"))) {
String md = doc.toMarkdown();
Files.writeString(Path.of("book.md"), md);
}
Kotlin
import fyi.oxide.pdf.PdfDocument
import java.nio.file.*
PdfDocument.open(Path.of("book.pdf")).use { doc ->
Files.writeString(Path.of("book.md"), doc.toMarkdown())
}
Scala
import fyi.oxide.pdf.PdfDocument
import java.nio.file.{Files, Path}
import scala.util.Using
Using.resource(PdfDocument.open("book.pdf")) { doc =>
Files.writeString(Path.of("book.md"), doc.toMarkdown())
}
Clojure
(require '[pdf-oxide.core :as pdf]
'[clojure.java.io :as io])
(with-open [doc (pdf/open "book.pdf")]
(spit "book.md" (pdf/to-markdown doc)))
PHP
use PdfOxide\PdfDocument;
$doc = PdfDocument::open('book.pdf');
file_put_contents('book.md', $doc->toMarkdownAll());
$doc->close();
Ruby
require 'pdf_oxide'
PdfOxide::PdfDocument.open('book.pdf') do |doc|
File.write('book.md', doc.to_markdown)
end
C++
#include <pdf_oxide/pdf_oxide.hpp>
#include <fstream>
auto doc = pdf_oxide::Document::open("book.pdf");
auto md = doc.to_markdown_all();
std::ofstream("book.md") << md;
Swift
import PdfOxide
let doc = try Document.open("book.pdf")
let md = try doc.toMarkdownAll()
try md.write(toFile: "book.md", atomically: true, encoding: .utf8)
Dart
import 'dart:io';
import 'package:pdf_oxide/pdf_oxide.dart';
final doc = PdfDocument.open('book.pdf');
final md = doc.toMarkdownAll();
File('book.md').writeAsStringSync(md);
R
library(pdfoxide)
doc <- pdf_open("book.pdf")
md <- pdf_to_markdown_all(doc)
writeLines(md, "book.md")
Julia
using PdfOxide
doc = open_document("book.pdf")
md = to_markdown_all(doc)
write("book.md", md)
Zig
const pdf_oxide = @import("pdf_oxide");
const a = std.heap.page_allocator;
var doc = try pdf_oxide.Document.open("book.pdf");
const md = try doc.toMarkdownAll(a);
try std.fs.cwd().writeFile(.{ .sub_path = "book.md", .data = md });
Objective-C
#import "POXPdfOxide.h"
NSError *err = nil;
POXDocument *doc = [POXDocument openPath:@"book.pdf" error:&err];
NSString *md = [doc toMarkdownAllWithError:&err];
[md writeToFile:@"book.md" atomically:YES encoding:NSUTF8StringEncoding error:&err];
Elixir
{:ok, doc} = PdfOxide.open("book.pdf")
{:ok, md} = PdfOxide.to_markdown_all(doc)
File.write!("book.md", md)
画像をディレクトリに保存して変換
use pdf_oxide::PdfDocument;
use pdf_oxide::converters::ConversionOptions;
let mut doc = PdfDocument::open("report.pdf")?;
let options = ConversionOptions {
detect_headings: true,
include_images: true,
embed_images: false,
image_output_dir: Some("output/images".to_string()),
..Default::default()
};
let md = doc.to_markdown_all(&options)?;
std::fs::write("output/report.md", &md)?;
進捗表示付きページごとの変換
from pdf_oxide import PdfDocument
doc = PdfDocument("report.pdf")
pages = doc.page_count()
parts = []
for i in range(pages):
md = doc.to_markdown(i, detect_headings=True)
parts.append(md)
print(f"Converted page {i + 1}/{pages}")
full_md = "\n\n---\n\n".join(parts)
with open("report.md", "w") as f:
f.write(full_md)
フラットテキスト向けに見出し検出を無効化
doc = PdfDocument("form.pdf")
md = doc.to_markdown(0, detect_headings=False)
# All text rendered as paragraphs, no # headings