0 Comments

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);
                        }
                    }
                }
            }
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Posts