在之前一篇文章中,已经介绍了如何将多个PDF文件合并为一个PDF。但是,在某些情况下,需要将单个PDF文件拆分为多个文件。可以将PDF的每一页或页面集合拆分为多个PDF。在本文中,将学习如何应对此类情况,以及如何使用C#将PDF文件拆分为多个PDF。
- 按页面分割PDF文件
- 分割PDF文件的选定页面
使用C#分割PDF文件
PDF拆分标准可以根据您的要求而变化。可以按每页或页面集合拆分文档。首先,让我们看一下如何分割PDF文件的每一页。
- 使用Document类加载PDF文档。
- 循环遍历Document.Pages集合,以使用Page类访问每个页面。
- 在每次迭代中,创建一个新Document,将当前页面添加到该文档中,然后使用Document.Save(String)方法将其另存为PDF文件。
以下代码示例显示了如何使用C#拆分PDF文档。
// Open document Document pdfDocument = new Document("merged.pdf"); // For page counter int pageCount = 1; // Loop through all the pages foreach (Aspose.Pdf.Page pdfPage in pdfDocument.Pages) { // Create a new document Document newDocument = new Document(); // Add page to the document newDocument.Pages.Add(pdfPage); // Save as PDF newDocument.Save("page_" + pageCount + "_out" + ".pdf"); pageCount++; }
使用C#分割PDF的选定页面
还可以通过指定页面范围来拆分PDF。例如,您可以分割第N个或最后N个数字页,偶数或奇数页等。为进行演示,以下是从PDF分割偶数和奇数页的步骤。
- 使用Document类加载PDF文档。
- 获取要拆分为Page []数组的页面。
- 创建一个新文档,并使用Document.Pages.Add(Page [])方法向其中添加页面。
- 使用Document.Save(String)方法保存PDF文件。
以下代码示例显示了如何从PDF拆分页面集合。
// Open document Document pdfDocument = new Document("merged.pdf"); // Select even pages only Aspose.Pdf.Page[] evenPages = pdfDocument.Pages.Where(x => x.Number % 2 == 0).ToArray(); // Select odd pages only Aspose.Pdf.Page[] oddPages = pdfDocument.Pages.Where(x => x.Number % 2 != 0).ToArray(); // Save even pages as PDF Document newDocument = new Document(); newDocument.Pages.Add(evenPages); newDocument.Save("split_even_Pages.pdf"); // Save odd pages as PDF newDocument = new Document(); newDocument.Pages.Add(oddPages); newDocument.Save("split_odd_Pages.pdf");