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

推荐订阅源

Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Vercel News
Vercel News
Microsoft Azure Blog
Microsoft Azure Blog
Stack Overflow Blog
Stack Overflow Blog
Martin Fowler
Martin Fowler
Hacker News - Newest:
Hacker News - Newest: "LLM"
Cyberwarzone
Cyberwarzone
Recorded Future
Recorded Future
H
Hackread – Cybersecurity News, Data Breaches, AI and More
T
Threat Research - Cisco Blogs
Know Your Adversary
Know Your Adversary
Recent Announcements
Recent Announcements
L
LINUX DO - 热门话题
D
DataBreaches.Net
K
Kaspersky official blog
T
Threatpost
F
Full Disclosure
T
The Exploit Database - CXSecurity.com
C
CERT Recently Published Vulnerability Notes
S
Securelist
I
Intezer
有赞技术团队
有赞技术团队
罗磊的独立博客
爱范儿
爱范儿
S
Schneier on Security
P
Privacy & Cybersecurity Law Blog
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Cisco Talos Blog
Cisco Talos Blog
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
L
LangChain Blog
美团技术团队
G
Google Developers Blog
T
Tor Project blog
Project Zero
Project Zero
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
The Hacker News
The Hacker News
W
WeLiveSecurity
Engineering at Meta
Engineering at Meta
Apple Machine Learning Research
Apple Machine Learning Research
aimingoo的专栏
aimingoo的专栏
PCI Perspectives
PCI Perspectives
L
LINUX DO - 最新话题
MyScale Blog
MyScale Blog
阮一峰的网络日志
阮一峰的网络日志
酷 壳 – CoolShell
酷 壳 – CoolShell
V
V2EX
Hugging Face - Blog
Hugging Face - Blog
P
Proofpoint News Feed
Webroot Blog
Webroot Blog
T
Troy Hunt's Blog

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 Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
How I built a PDF Word converter that runs 100% in the browser (no server)"
Doctor PDF · 2026-06-24 · via DEV Community

"Extracting text with coordinates from pdf.js, rebuilding paragraphs and tables, fixing Arabic right-to-left order, and generating a real .docx — all client-side, no upload."
tags: javascript, webdev, pdf, opensource
canonical_url: https://doctor-pdf.com/pdf-to-word.html

cover_image:

TL;DR — I built a PDF → Word (.docx) converter that does everything in the browser: no file ever leaves the user's device. The hard parts weren't the file formats — they were reconstructing layout (paragraphs, tables, headings) from a flat stream of positioned glyphs, and getting Arabic / right-to-left text to come out in logical order. Here's how it works, with the gotchas I hit along the way. Live tool: doctor-pdf.com/pdf-to-word.html.

Why client-side?

Almost every "free" PDF tool uploads your file to a server. For contracts, IDs, and confidential documents that's a non-starter for a lot of people. Browsers are now powerful enough that the entire pipeline — parsing the PDF, reconstructing the document, and writing a Word file — can run in JavaScript on the user's machine. Nothing is uploaded. That constraint shaped every decision below.

The stack is intentionally boring and CDN-only:

  • pdf.js — read text, positions, fonts, colours, and the operator list.
  • docx — generate a real .docx (lazy-loaded ~740 KB, only when the user clicks Download).
  • <canvas> — the browser's own text shaper, which turns out to be the secret weapon for Arabic.

Step 1 — PDF text isn't text, it's positioned glyphs

The first surprise for anyone new to PDFs: there are no paragraphs, no lines, often no spaces. pdf.js hands you textContent.items, each roughly:

{ str: "Invoice", transform: [fs,0,0,fs, x, y], width, fontName }

That's a glyph run with a position. A "line" of text might arrive as ten fragments; a visual space between two columns might be no character at all, just a horizontal gap. So step one is to rebuild lines and spaces from geometry:

// group items into lines by their y coordinate
lines.sort((a, b) => b.y - a.y); // top-to-bottom

// within a line, rebuild missing spaces from the x-gap
for (const cur of chunks) {
  const gap = cur.x - (prev.x + prev.w);
  if (gap > cur.fs * 0.18) text += " ";      // a normal word space
  if (gap > cur.fs * 4)    text += "   ";     // a column gap → several spaces
  text += cur.str;
}

That fs * 0.18 threshold (a fraction of the font size) is the single most-tuned number in the whole project. Too low and words run together; too high and you get H e l l o.

Step 2 — From lines to paragraphs, headings, and lists

Once you have lines, you infer structure from typography and whitespace — the same cues a human reads:

  • New paragraph when the vertical gap between lines jumps, when alignment changes, or when a line stops well short of the right margin (a "short last line").
  • Heading when a line's font size is meaningfully larger than the body — or it's short, bold, and standalone. Important caveat I learned the hard way: in a document where everything is bold (lots of legal letters are), "bold" carries no signal. So I compute a document-wide boldFraction and only treat bold as a heading hint when bold is uncommon (< 40%).
  • List item when a line starts with a bullet/number glyph.

A fun bug: bullet characters (U+2022) are often drawn in a SymbolMT font. Carry that font name into Word and the bullet renders as a □ tofu box. The fix is to drop the font for known symbol fonts so the bullet falls back to a Unicode-capable default.

Step 3 — The hard one: Arabic and right-to-left

This is where most converters fall over. Legacy PDFs frequently emit Arabic glyphs in visual order — i.e. already laid out left-to-right on the page — instead of logical order. Concatenate the fragments naively and you get Arabic that's reversed and, worse, mixed Arabic/Latin lines like QUOTATION / عرض أسعار that come out scrambled.

The reconstruction is a small bidi pass per line:

// line contains Arabic drawn in visual (LTR) order →
// 1) reverse all runs to base right-to-left logical order
runs.reverse();
// 2) re-flip maximal runs of Latin / digits so they read left-to-right again
flipLatinRunsBackToLTR(runs);

Pure-Latin lines short-circuit out (so English documents are untouched), and the same routine runs inside table cells. The payoff: الإمارات العربية المتحدة / Sharjah - United Arab Emirates comes out correct in both scripts, and the Word runs get bidirectional: true + rightToLeft: true.

One more Arabic-specific gotcha: italic / sheared text. A naive "skip rotated text" watermark filter (checking the transform matrix) also kills faux-italic text, because the shear shows up in the same matrix entries. The fix is to normalise by scale and separate rotation from shear before deciding to drop a run.

Step 4 — Reconstructing tables geometrically

Tables are the other place server engines usually win, because a PDF table is just… lines of text that happen to align into columns, often with rows that wrap across several text-lines. My first attempt (split each line at big x-gaps) produced fragmented messes on real multi-column tables.

The approach that actually worked is a small geometric reconstructor:

  1. Find a region — consecutive lines that each have ≥ 2 well-separated fragment groups ("anchors").
  2. Rows — group fragment y-positions; a gap bigger than fontSize * 1.5 starts a new row, so wrapped multi-line rows merge correctly.
  3. Columns — cluster fragment x-positions (tolerance ~25pt) and keep clusters that appear in at least half the rows.
  4. Assign each fragment to its nearest column centre.

The make-or-break part is the precision guards — what separates a real data table from a page that merely looks columnar (like a two-column CV):

cols >= 3 && rows >= 3 &&
fillRatio >= 0.7 &&
fullRowFraction >= 0.7 &&   // most rows fill EVERY column
headerRowFullyFilled        // kills "contact block" false positives

fullRowFraction is the key signal: a genuine table has rows that fill every column (≈1.0); a sidebar layout doesn't (≈0.67). With those guards the tool reconstructs reflowed/wrapped tables that match what the commercial converters produce — while a CV's two-column layout correctly stays as prose. Borderless label/value info-grids (the Client | …, Project | … block at the top of invoices) get their own lighter detector and render without grid lines.

Step 5 — Carrying images

To match diagrams in English docs and stamps/signatures in Arabic ones, I walk pdf.js's operator list, track the current transformation matrix through save/restore/transform, and on each paintImageXObject pull the bitmap from page.objs, draw it to a canvas at ~2× for sharpness, and emit a PNG. Images that overlap vertically get grouped into a single side-by-side row so figures that sit next to each other in the PDF stay next to each other in Word.

⚠️ Hang warning worth its own paragraph: page.objs.get(id, callback) will wait forever if an image object never becomes ready — on some files that froze the whole conversion. The fix was to make the lookup synchronous and skippable: objs.has(id) ? objs.get(id) : null. A skipped image is infinitely better than a frozen tab.

Step 6 — Writing the .docx

With an ordered list of blocks (paragraph / table / image), the docx library does the heavy lifting. The thing to get right is fidelity of the runs: explicit font size (real points), colour (only when it's not near-black, so dark-mode Word doesn't get weird), bold/italic, alignment, and — a detail that bit me — set the heading run's size and colour explicitly instead of relying on Word's Heading2 style, which otherwise renders everything the same size and blue.

new TextRun({
  text: run.text,
  font: cleanFontName(run.fontName),   // strip "ABCDEF+" subset prefix, map Helvetica→Arial
  size: Math.round(run.fs) * 2,        // docx uses half-points
  bold: run.bold, italics: run.ital,
  color: nearBlack ? undefined : run.hex,
  rightToLeft: isArabic, // ...
})

Packer.toBlob() produces the file, and a classic appendChild → click → remove anchor triggers the download. No server round-trip.

Things I'd tell my past self

  • PDF is a presentation format, not a content format. You're not parsing a document; you're reverse-engineering one from ink positions.
  • Tune thresholds against real files, not synthetic ones. Every magic number here (0.18, 1.5, 0.7) was calibrated on actual contracts, CVs, and invoices — and re-checked for regressions on every change.
  • The browser is a great text shaper. For anything involving Arabic shaping or RTL, rendering to <canvas> and embedding the result sidesteps a whole category of font-embedding pain.
  • Never ship a feature that can hang. A wrong-but-fast result beats a correct-but-frozen tab every time. Guard every async decode with a synchronous fallback or a timeout.
  • Know your limits. Damaged ToUnicode maps (the PDF's own defect) extract as , and Arabic OCR isn't good enough to silently recover small/decorative text. When that happens the tool shows an honest quality banner instead of pretending.

Try it / read the code

The tool is live and free, no signup, nothing uploaded: doctor-pdf.com/pdf-to-word.html. It's part of a suite of 15 browser-only PDF tools I'm building — Arabic-first, since 400M+ Arabic speakers had no real privacy-respecting option.

If you're building something similar, happy to compare notes in the comments. 🔒