惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Martin Fowler
Martin Fowler
Microsoft Security Blog
Microsoft Security Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Vercel News
Vercel News
Y
Y Combinator Blog
D
DataBreaches.Net
IT之家
IT之家
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
博客园_首页
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
H
Hackread – Cybersecurity News, Data Breaches, AI and More
WordPress大学
WordPress大学
H
Help Net Security
GbyAI
GbyAI
C
Check Point Blog
L
LangChain Blog
小众软件
小众软件
T
The Blog of Author Tim Ferriss
MyScale Blog
MyScale Blog
G
Google Developers Blog
月光博客
月光博客
V
V2EX
M
MIT News - Artificial intelligence
博客园 - 叶小钗

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Repairing a Broken PDF in Rust — Rebuilding the XREF Tabl...
hiyoyo · 2026-04-28 · via DEV Community
Cover image for Repairing a Broken PDF in Rust — Rebuilding the XREF Table From Scratch

hiyoyo

All tests run on an 8-year-old MacBook Air.

Some PDFs won't open. Not because the content is gone — because the index that tells readers where to find the content is corrupt.

That index is the XREF table. And it can be rebuilt.


What the XREF table is

Every PDF has a cross-reference table near the end of the file. It's a lookup map: object ID → byte offset in the file.

xref
0 6
0000000000 65535 f
0000000009 00000 n
0000000058 00000 n
0000000115 00000 n
0000000266 00000 n
0000000496 00000 n

Enter fullscreen mode Exit fullscreen mode

When a reader opens the PDF, it reads this table first. If it's missing or corrupt — the PDF "won't open."


Rebuilding it

The content objects are still in the file. We just need to find them and rebuild the index.

pub fn rebuild_xref(data: &[u8]) -> Result {
    // lopdf can attempt recovery on malformed files
    let doc = Document::load_mem(data)
        .or_else(|_| recover_document(data))?;
    Ok(doc)
}

pub fn recover_document(data: &[u8]) -> Result {
    // Scan the raw bytes for object markers
    // Pattern: "N 0 obj" where N is the object number
    let mut offsets: Vec<(u32, u32, usize)> = Vec::new();
    let obj_pattern = b" 0 obj";

    for (i, window) in data.windows(obj_pattern.len()).enumerate() {
        if window == obj_pattern {
            // Walk back to find the object number
            if let Some(num) = extract_obj_num(data, i) {
                offsets.push((num, 0, i - num.to_string().len()));
            }
        }
    }

    // Reconstruct document from found objects
    rebuild_from_offsets(data, offsets)
}

Enter fullscreen mode Exit fullscreen mode


What this fixes

  • PDFs truncated mid-write (power loss during save)
  • PDFs with incremental updates that broke the XREF chain
  • Old files where the XREF was hand-edited incorrectly
  • Scanner output with malformed structure

What it can't fix

If the content streams themselves are corrupt — the actual page data is gone — no amount of XREF rebuilding helps. Structural resurrection only works when the objects are present but the index is broken.


In practice

About 80% of "won't open" PDFs I've tested are XREF problems. The content is fine. They just need a new index.


Hiyoko PDF Vault → https://hiyokoko.gumroad.com/l/HiyokoPDFVault
X → @hiyoyok