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

How to Split PDF by File Size in the Browser with Vue 3 and pdf-lib

sunshey 2026年08月10日 21:00 0 次阅读 来源:Dev.to

Splitting a PDF by file size is one of the most practical but technically tricky operations. Unlike splitting by page count (simple math) or bookmarks (tree traversal), size-based splitting requires estimating and controlling the output size of each chunk — and PDFs don't have a simple "size per page" property. Here's how to build a browser-based PDF splitter that respects file size constraints. The challenge PDFs are notoriously unpredictable in terms of size. Two PDFs with the same number of pages can differ by 10x in file size depending on: Image resolution and compression Font embedding Color space (RGB vs. CMYK) Content complexity (vector graphics vs. scanned images) This means you can't calculate split points with simple arithmetic. You need to estimate, test, and adjust . The stack Vue 3 with Composition API pdf-lib for PDF manipulation Vite for bundling The core implementation The approach is greedy accumulation with size estimation : < script setup lang= "ts" > import { ref } from ' vue ' import { PDFDocument } from ' pdf-lib ' const file = ref < File | null > ( null ) const targetSizeMB = ref < number > ( 10 ) const compression = ref < ' none ' | ' low ' | ' high ' > ( ' low ' ) const splitting = ref ( false ) const progress = ref ( 0 ) const progressTotal = ref ( 0 ) const results = ref < Record < string , Uint8Array >> ({}) async function splitBySize () { if ( ! file . value ) return splitting . value = true const arrayBuffer = await file . value . arrayBuffer () const pdf = await PDFDocument . load ( arrayBuffer ) const totalPages = pdf . getPageCount () const targetBytes = targetSizeMB . value * 1024 * 1024 const outputFiles : Array < { name : string ; data : Uint8Array } > = [] let currentPdf = await PDFDocument . create () let currentSize = 0 let pageNum = 0 for ( let i = 0 ; i < totalPages ; i ++ ) { progressTotal . value = totalPages progress . value = i + 1 // Try adding this page try { const [ copiedPage ] = await currentPdf . copyPages ( pdf , [

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