C#中将大型PDF拆分为多个文件的免费可行实现方案问询
C# 免费实现PDF拆分/分块上传方案
方案1:拆分单个PDF为多个独立PDF(无付费依赖)
推荐使用iTextSharp.LGPLv2.Core,这是旧版iTextSharp的社区维护分支,适配.NET Core/.NET 5+全版本,基于LGPL协议完全开源免费,无商用限制,功能和原iTextSharp完全兼容,不存在停止维护的问题。
按页拆分代码示例:
using iTextSharp.text.pdf; using System.IO; // pagesPerFile可自定义每个拆分文件包含的页数,也可按文件大小阈值动态判断 public void SplitPdfByPage(string sourcePdfPath, string outputFolderPath, int pagesPerFile = 10) { if (!Directory.Exists(outputFolderPath)) Directory.CreateDirectory(outputFolderPath); using (var reader = new PdfReader(sourcePdfPath)) { int totalPages = reader.NumberOfPages; int fileCount = (int)Math.Ceiling((double)totalPages / pagesPerFile); for (int i = 0; i < fileCount; i++) { int startPage = i * pagesPerFile + 1; int endPage = Math.Min((i + 1) * pagesPerFile, totalPages); string outputPath = Path.Combine(outputFolderPath, $"split_part_{i+1}.pdf"); using (var fs = new FileStream(outputPath, FileMode.Create)) using (var doc = new iTextSharp.text.Document()) using (var copy = new PdfCopy(doc, fs)) { doc.Open(); for (int pageNum = startPage; pageNum <= endPage; pageNum++) { var importedPage = copy.GetImportedPage(reader, pageNum); copy.AddPage(importedPage); } doc.Close(); } } } }
如果需要按2MB大小拆分,只需每次写入页面后判断当前输出文件大小,超过阈值就关闭当前文件、新建下一个文件即可。
方案2:直接拆分二进制分块(无需PDF处理库)
如果WCF服务端支持分块接收后合并,不需要拆分后的文件单独可预览,推荐直接做二进制分块,无任何第三方依赖,性能更高。
分块代码示例:
// 默认每块大小2MB,可自定义调整 public List<byte[]> SplitFileToChunks(string filePath, int chunkSize = 2 * 1024 * 1024) { var chunks = new List<byte[]>(); using (var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read)) { byte[] buffer = new byte[chunkSize]; int bytesRead; while ((bytesRead = fs.Read(buffer, 0, buffer.Length)) > 0) { if (bytesRead < chunkSize) { byte[] lastChunk = new byte[bytesRead]; Array.Copy(buffer, lastChunk, bytesRead); chunks.Add(lastChunk); } else { chunks.Add(buffer); } buffer = new byte[chunkSize]; } } return chunks; }
注意:该方案服务端只需按顺序接收所有分块后直接拼接写入新文件,即可还原完整PDF,无需额外PDF处理逻辑,实现成本更低,仅用于解决上传大小限制的场景优先选这个方案。
其他可选开源库
如果不想用iText相关依赖,也可以选MIT协议的PdfSharp或者QuestPDF,都是完全免费的开源库,也支持PDF拆分操作。
内容的提问来源于stack exchange,提问作者mohan
相关产品推荐
相关产品推荐

