Converting Word documents to PDF requires parsing OOXML structure and rendering it to a fixed-layout format.
Here's how to build a browser-based Word to PDF converter with Vue 3.
The challenge: Preserving document layout
Word to PDF conversion involves:
- Parsing DOCX (ZIP archive of XML files)
- Extracting text, images, and formatting
- Rendering to a fixed-layout PDF
- Handling tables, lists, and page breaks
The stack
- Vue 3 with Composition API
- docx-parser or mammoth for DOCX parsing
- jsPDF for PDF generation
- Vite for bundling
The core implementation
<script setup lang="ts">
import { ref } from 'vue'
import jsPDF from 'jspdf'
import * as mammoth from 'mammoth'
const file = ref<File | null>(null)
const converting = ref(false)
const result = ref<Uint8Array | null>(null)
async function handleFile(e: Event) {
const input = e.target as HTMLInputElement
if (!input.files?.[0]) return
file.value = input.files[0]
}
async function convertToPdf() {
if (!file.value) return
converting.value = true
// Convert DOCX to HTML using mammoth
const arrayBuffer = await file.value.arrayBuffer()
const { value: html } = await mammoth.convertToHtml({ arrayBuffer })
// Parse HTML and render to PDF
const pdf = new jsPDF({
orientation: 'portrait',
unit: 'mm',
format: 'a4'
})
const lines = html.split('\n').filter(line => line.trim())
let y = 10
for (const line of lines) {
// Simple text rendering
const text = line.replace(/<[^>]*>/g, '').trim()
if (text) {
pdf.text(text, 10, y)
y += 5
}
// Handle page breaks
if (y > 270) {
pdf.addPage()
y = 10
}
}
result.value = await pdf.output('uint8array')
converting.value = false
}
</script>
Key implementation details
1. DOCX parsing
Use mammoth.js to extract text from DOCX files:
const { value: html } = await mammoth.convertToHtml({ arrayBuffer })
2. HTML to PDF rendering
Parse the HTML and render lines to PDF:
const lines = html.split('\n').filter(line => line.trim())
3. Page break handling
Detect page breaks and add new pages:
if (y > 270) {
pdf.addPage()
y = 10
}
Limitations
Complex formatting not preserved
Tables, images, and complex layouts may not render correctly.
Solution: Use desktop software for documents with complex formatting.
No image support in basic implementation
The example only handles text, not images.
Solution: Add image extraction and embedding to the PDF.
Font limitations
Custom fonts may not display correctly.
Solution: Use standard fonts or embed fonts in the PDF.
Summary
Building a browser-based Word to PDF converter involves:
- Using mammoth.js to parse DOCX files
- Extracting text and basic formatting
- Rendering to PDF with jsPDF
- Handling page breaks and layout
Try it at en.sotool.top/word-to-pdf.
Top comments (0)