Merging multiple PDF files requires careful handling of PDF structure and page ordering.
Here's how to build a browser-based PDF merge tool with Vue 3 and pdf-lib.
The challenge: Combining PDF structures
PDF merging involves:
- Loading multiple PDF documents
- Extracting pages from each document
- Combining pages into a new PDF
- Preserving page order and metadata
The stack
- Vue 3 with Composition API
- pdf-lib for PDF manipulation
- Vite for bundling
The core implementation
<script setup lang="ts">
import { ref } from 'vue'
import { PDFDocument } from 'pdf-lib'
const files = ref<File[]>([])
const merging = ref(false)
const result = ref<Uint8Array | null>(null)
async function handleFileChange(e: Event) {
const input = e.target as HTMLInputElement
if (input.files) {
files.value = Array.from(input.files)
}
}
async function mergePdfs() {
if (files.value.length === 0) return
merging.value = true
const mergedPdf = await PDFDocument.create()
for (const file of files.value) {
const arrayBuffer = await file.arrayBuffer()
const pdfDoc = await PDFDocument.load(arrayBuffer)
const pageIndices = Array.from({ length: pdfDoc.getPageCount() }, (_, i) => i)
const pages = await mergedPdf.copyPages(pdfDoc, pageIndices)
pages.forEach(page => mergedPdf.addPage(page))
}
result.value = await mergedPdf.save()
merging.value = false
}
function downloadResult() {
if (!result.value) return
const blob = new Blob([result.value], { type: 'application/pdf' })
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = 'merged.pdf'
a.click()
}
</script>
Key implementation details
1. Copying pages between PDFs
pdf-lib uses copyPages to transfer pages:
const pages = await mergedPdf.copyPages(pdfDoc, pageIndices)
pages.forEach(page => mergedPdf.addPage(page))
2. Preserving page order
Pages are added in the order they're processed. For multi-file merges:
for (const file of files.value) {
// process each file in order
}
3. Handling empty PDFs
Some PDFs may have zero pages. Add safety checks:
if (pdfDoc.getPageCount() === 0) continue
Limitations
No page reordering within files
pdf-lib copies entire files sequentially.
Solution: Implement a custom page reordering UI.
Memory constraints
Many large PDFs can exhaust browser memory.
Solution: Process files in batches and show progress.
Metadata loss
Copied pages may lose some source metadata.
Solution: For metadata-critical documents, use desktop software.
Summary
Building a browser-based PDF merge tool involves:
- Using pdf-lib to load and combine PDFs
- Copying pages from each source document
- Preserving order through sequential processing
- Providing download functionality
Try it at en.sotool.top/merge.
Top comments (0)