今日已更新 133 条资讯 | 累计 37382 条内容
关于我们

How to Convert PDF to Word in the Browser with Vue 3 and pdf-lib

sunshey 2026年08月20日 20:15 2 次阅读 来源:Dev.to

Converting PDF to Word seems straightforward, but the reality is more complex. PDF stores text as character coordinates, while Word uses structured paragraphs. Bridging this gap requires careful text extraction and order reconstruction. Here's how to build a browser-based PDF to Word converter with Vue 3 and pdf-lib . The challenge: PDF vs Word PDF is a presentation format — text is positioned precisely on the page. Word is an editing format — text flows in paragraphs with styles. Converting between them means: Extracting text from PDF coordinates Reconstructing reading order Generating structured DOCX output The stack Vue 3 with Composition API pdf-lib for PDF parsing docx for Word document generation Vite for bundling The core implementation < script setup lang= "ts" > import { ref } from ' vue ' import { PDFDocument } from ' pdf-lib ' import { Document , Paragraph , TextRun } from ' docx ' const file = ref < File | null > ( null ) const processing = ref ( false ) const result = ref < Blob | null > ( null ) async function convertPdfToWord () { if ( ! file . value ) return processing . value = true const arrayBuffer = await file . value . arrayBuffer () const pdf = await PDFDocument . load ( arrayBuffer ) const pages = pdf . getPages () const allChunks : TextChunk [] = [] for ( const page of pages ) { const textContent = await page . getTextContent () for ( const item of textContent . items ) { allChunks . push ({ text : item . text , x : item . transform [ 4 ], y : item . transform [ 5 ], size : item . size }) } } // Sort by reading order const sorted = sortByReadingOrder ( allChunks ) // Generate DOCX const doc = new Document ({ sections : [{ properties : {}, children : sorted . map ( chunk => new Paragraph ({ children : [ new TextRun ( chunk . text )] }) ) }] }) const blob = await doc . pack () result . value = blob processing . value = false } interface TextChunk { text : string x : number y : number size : number } function sortByReadingOrder ( chunks : TextCh

本文内容来源于互联网,版权归原作者所有
查看原文