Split PDF by pages in memory using C# and .NET

Splitting PDF documents into separate pages is a common task in software development. In this article, we will look at how you can split PDF documents directly in memory, without saving intermediate files to disk, using the C# programming language and platform .NET with a component SautinSoft.Pdf from SautinSoft.

To complete the task, we will need the following steps:

  1. Add SautinSoft.PDF from NuGet.
  2. Read PDF files into memory.
  3. Split the PDF document using MemoryStream, specifying the page number.
  4. Save the document to show the result.

Output result:

Splitting PDF documents in memory using C# and .NET is an efficient way to process PDF without having to work with the file system. The SautinSoft PDF library .Net provides a simple and powerful API for performing such tasks. Using the above code example, you can easily integrate PDF splitting functionality into your applications.

Полный код

using System;
using System.IO;
using System.Collections.Generic;
using SautinSoft;
using SautinSoft.Pdf;
using SautinSoft.Pdf.Content;
using SautinSoft.Pdf.Facades;

namespace Sample
{
    class Sample
    {
        /// <summary>
        /// Split PDF documents in memory using C# and .NET.
        /// </summary>
        /// <remarks>
        /// Details: https://sautinsoft.com/products/pdf/help/net/developer-guide/merge-pdf-documents-in-memory-using-csharp-and-dotnet.php
        /// </remarks>
        static void Main(string[] args)
        {
            // Before starting this example, please get a free 100-day trial key:
            // https://sautinsoft.com/start-for-free/

            // Apply the key here:
            // PdfDocument.SetLicense("...");

            SplitPdfInMemory();
        }
        static void SplitPdfInMemory()
        {
            int page = 0;
            using var fs = new FileStream(@"..\..\..\005.pdf", FileMode.Open, FileAccess.ReadWrite);
            foreach (var stream in PdfSplitter.Split(fs, PdfLoadOptions.Default, 0, int.MaxValue))
            {
                using var output = new FileStream($"Page {++page}.pdf", FileMode.Create, FileAccess.ReadWrite);
                stream.CopyTo(output);
            }

            // Show the "Page 5.pdf"
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo("Page 5.pdf") { UseShellExecute = true });
        }
    }
}

Download

Imports System
Imports System.IO
Imports System.Collections.Generic
Imports SautinSoft
Imports SautinSoft.Pdf
Imports SautinSoft.Pdf.Content
Imports SautinSoft.Pdf.Facades

Module Sample
    ''' <summary>
    ''' Split PDF documents in memory using VB.NET.
    ''' </summary>
    ''' <remarks>
    ''' Details: https://sautinsoft.com/products/pdf/help/net/developer-guide/merge-pdf-documents-in-memory-using-csharp-and-dotnet.php
    ''' </remarks>
    Sub Main(args As String())
        ' Before starting this example, please get a free 100-day trial key:
        ' https://sautinsoft.com/start-for-free/

        ' Apply the key here:
        ' PdfDocument.SetLicense("...")

        SplitPdfInMemory()
    End Sub

    Sub SplitPdfInMemory()
        Dim page As Integer = 0
        Using fs As New FileStream("..\..\..\005.pdf", FileMode.Open, FileAccess.ReadWrite)
            For Each stream In PdfSplitter.Split(fs, PdfLoadOptions.Default, 0, Integer.MaxValue)
                Using output As New FileStream($"Page {page + 1}.pdf", FileMode.Create, FileAccess.ReadWrite)
                    stream.CopyTo(output)
                End Using
                page += 1
            Next
        End Using

        ' Show the "Page 5.pdf"
        System.Diagnostics.Process.Start(New System.Diagnostics.ProcessStartInfo("Page 5.pdf") With {.UseShellExecute = True})
    End Sub
End Module

Download


Если вам нужен пример кода или у вас есть вопрос: напишите нам по адресу support@sautinsoft.ru или спросите в онлайн-чате (правый нижний угол этой страницы) или используйте форму ниже:



Вопросы и предложения всегда приветствуются!

Мы разрабатываем компоненты .Net с 2002 года. Мы знаем форматы PDF, DOCX, RTF, HTML, XLSX и Images. Если вам нужна помощь в создании, изменении или преобразовании документов в различных форматах, мы можем вам помочь. Мы напишем для вас любой пример кода абсолютно бесплатно.