GxPDF v0.1.0:纯 Go 实现 100% 表格提取准确率

发布: (2026年1月7日 GMT+8 11:03)
7 min read
原文: Dev.to

Source: Dev.to

GxPDF v0.1.0 封面图:纯 Go 实现 100% 表格提取准确率

Andrey Kolkov

PDF 库的问题

每个使用过 PDF 的 Go 开发者都深有体会:

LibraryIssue
UniPDF强大,但起价为 $299/月
pdfcpu操作功能强大,不支持表格提取
gofpdf仅支持创建,自 2019 年起已被弃用

我需要从银行对账单中提取表格——共 740 笔交易,跨多页。商业库可以工作,但费用对开源项目来说太高。

Solution: 我构建了 GxPDF

什么是 GxPDF?

GxPDF 是一个 纯 Go 的 PDF 库,能够处理 读取创建

  • 无 CGO
  • 无外部依赖
  • MIT 许可证
# Install CLI
go install github.com/coregx/gxpdf/cmd/gxpdf@v0.1.0

# Or use as a library
go get github.com/coregx/gxpdf@v0.1.0

关键创新 – 四阶段混合检测

表格抽取非常困难。PDF 并不包含“表格”,而是包含散布在坐标上的定位文本元素。大多数算法在以下情况下会失效:

  • 多行单元格(换行的描述)
  • 缺失边框(现代设计)
  • 合并单元格
  • 表头与数据的区分

GxPDF 使用 四阶段混合检测 算法:

阶段描述
Pass 1间隙检测(自适应阈值)
Pass 2重叠检测(受 Tabula 启发)
Pass 3对齐检测(几何聚类)
Pass 4多行单元格合并(基于金额的区分)

Pass 4 见解: 交易行包含金额;续行不包含金额。

// Works on ALL banks without configuration
isTransactionRow := hasAmount(row)   // Has amount = new transaction
isContinuation   := !hasAmount(row)   // No amount = continuation of previous

这种通用判别器能够跨不同的 PDF 生成器、布局以及银行格式工作。

Results – 100 % Accuracy

Tested on real bank statements:

银行交易数准确率
Sberbank242100 %
Alfa‑Bank281100 %
VTB217100 %
总计740100 %

每笔交易都被正确提取,且每个多行描述都得以保留。

代码示例

从 PDF 中提取表格

package main

import (
    "fmt"
    "log"

    "github.com/coregx/gxpdf"
)

func main() {
    // Open PDF
    doc, err := gxpdf.Open("bank_statement.pdf")
    if err != nil {
        log.Fatal(err)
    }
    defer doc.Close()

    // Extract all tables
    tables := doc.ExtractTables()

    for _, t := range tables {
        fmt.Printf("Table: %d rows x %d cols\n",
            t.RowCount(), t.ColumnCount())

        // Access rows
        for _, row := range t.Rows() {
            fmt.Println(row)
        }
    }
}

导出为 CSV / JSON

// Export to CSV
csv, _ := table.ToCSV()
fmt.Println(csv)

// Export to JSON
json, _ := table.ToJSON()
fmt.Println(json)

// Write to file
file, _ := os.Create("output.csv")
table.ExportCSV(file)

创建 PDF

package main

import (
    "log"

    "github.com/coregx/gxpdf/creator"
)

func main() {
    c := creator.New()
    c.SetTitle("Invoice")
    c.SetAuthor("GxPDF")

    page, _ := c.NewPage()

    // Add text with Standard 14 fonts
    page.AddText("Invoice #12345", 100, 750, creator.HelveticaBold, 24)
    page.AddText("Amount: $1,234.56", 100, 700, creator.Helvetica, 14)

    // Draw graphics
    opts := &creator.RectOptions{
        StrokeColor: &creator.Black,
        FillColor:   &creator.LightGray,
        StrokeWidth: 1.0,
    }
    page.DrawRect(100, 600, 400, 50, opts)

    // Save
    if err := c.WriteToFile("invoice.pdf"); err != nil {
        log.Fatal(err)
    }
}

CLI 工具

GxPDF 包含一个用于快速操作的 CLI:

# Extract tables
gxpdf tables invoice.pdf
gxpdf tables bank.pdf --format csv > transactions.csv
gxpdf tables report.pdf --format json

# Get PDF info
gxpdf info document.pdf

# Extract text
gxpdf text document.pdf

# Merge PDFs
gxpdf merge part1.pdf part2.pdf -o combined.pdf

# Split PDF
gxpdf split document.pdf --pages 1-5 -o first_five.pdf

功能矩阵

FeatureStatus
表格提取100 % accuracy
文本提取Supported
图像提取Supported
PDF 创建Supported
标准 14 种字体All 14
嵌入式字体TTF/OTF
图形Lines, Rectangles, Circles, Bezier
加密RC4 + AES‑128/256
导出格式CSV, JSON, Excel

架构

internal/
├── document/       # Document model
├── encoding/       # FlateDecode, DCTDecode
├── extractor/      # Text, image, graphics
├── fonts/          # Standard 14 + embedding
├── models/         # Data structures
├── parser/         # PDF parsing
├── reader/         # PDF reader
├── security/       # RC4/AES encryption
├── tabledetect/    # 4‑Pass Hybrid algorithm
└── writer/         # PDF generation

清晰的分层。无 CGO。从头到尾纯 Go。

性能

15‑页 银行对账单上的表格提取:

指标
时间~200 ms
内存~15 MB 峰值
分配最小(请参见仓库中的基准测试)

基准测试

使用 sync.Pool 优化

PDF 创建基准:

BenchmarkNewPage-8        50000    28.4 µs/op
BenchmarkAddText-8       100000    11.2 µs/op
BenchmarkWriteToFile-8    5000   312.5 µs/op

接下来

v0.1.0 版本涵盖核心功能。计划在后续版本中实现:

  • 表单填写 – 填写现有的 PDF 表单
  • 数字签名 – 对 PDF 进行加密签名
  • SVG 导入 – 矢量图形支持
  • PDF 渲染 – 将页面转换为图像

我们需要您的 PDF

这是 v0.1.0 — 我们的首次公开发布。我们已经在银行对账单、发票和报告上进行了测试,但 PDF 的形式千变万化。

我们需要使用真实文档的测试者:

  • 包含复杂表格的企业报告
  • 来自不同国家和不同格式的发票
  • 带有 OCR 层的扫描文档
  • 多语言 PDF(中日韩、阿拉伯语、希伯来语)
  • 老旧生成器产生的遗留 PDF
  • 会导致其他库出错的极端案例

如果 GxPDF 在您的文档上失败,这也是有价值的数据。请提交 issue,附上 PDF(或已脱敏的版本),我们会进行修复。

我们的目标是企业级质量。不是“仅够业余项目使用”——我们希望 GxPDF 能在大规模生产环境中运行。对银行对账单 740/740 的准确率是我们的基准,而非上限。

试一试

go install github.com/coregx/gxpdf/cmd/gxpdf@v0.1.0
gxpdf version

仓库:

文档和示例位于仓库中。欢迎提交 Issue 和 PR。

GxPDF 使用 MIT 许可证。为需要真实 PDF 库且不受商业限制的 Go 社区而构建。

Back to Blog

相关文章

阅读更多 »