Split PDF in C# for free with .NET Core and iText.Kernel.Pdf

using iText.Kernel.Pdf;

namespace RvvFacturatie.Services
{
    public class PdfService
    {
        public void Split(string filePath, string outputFolderPath)
        {
            // Make sure the output folder exists and is empty.
            if (Directory.Exists(filePath))
            {
                Directory.Delete(filePath, true);
            }
            Directory.CreateDirectory(outputFolderPath);

            using (var pdfDoc = new PdfDocument(new PdfReader(filePath)))
            {
                // Loop pages in the given document.
                int numberOfPages = pdfDoc.GetNumberOfPages();
                for (int i = 0; i < numberOfPages; i++)
                {
                    // Determine destination file path for current page.
                    int currentPageNumber = i + 1;
                    string fileName = $"Page - {currentPageNumber}.pdf";
                    string pageFilePath = Path.Combine(outputFolderPath, fileName);

                    // Write current page to disk.
                    using (PdfWriter writer = new PdfWriter(pageFilePath))
                    {
                        using (var pdf = new PdfDocument(writer))
                        {
                            pdfDoc.CopyPagesTo(pageFrom: currentPageNumber, pageTo: currentPageNumber, toDocument: pdf, insertBeforePage: 1);
                        }
                    }
                }
            }
        }
    }
}

How to replace any .NET method with your own delegate, including non-virtual / static methods in sealed types.

So if you want to use TDD in .NET and use .NET types from for example mscorlib.dll, then you find your self creating interfaces for things like System.IO.File. System.DateTime etc., this is the way you do things in TDD, so the types can be mocked, but this is time consuming. To the rescue comes Microsoft Research with Moles (http://research.microsoft.com/en-us/projects/moles/).

 

This allows you to replace any .NET method with your own delegate, including non-virtual / static .NET methods in sealed types, in your test. So production code just uses the .NET types, but in your test you can mock these methods by your own implementations.

Watch the video at: http://channel9.msdn.com/blogs/peli/moles-replace-any-net-method-with-a-delegate