Separate PDF by pages in memory 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

Option Infer On

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

Namespace Sample
	Friend 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>
		Shared Sub Main(ByVal args() As String)
			' Before starting this example, please get a free lisense:
			' https://sautinsoft.com/start-for-free/

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

			SplitPdfInMemory()
		End Sub
		Private Shared Sub SplitPdfInMemory()
			Dim page As Integer = 0
			Using fs = New FileStream("..\..\..\005.pdf", FileMode.Open, FileAccess.ReadWrite)
				For Each stream In PdfSplitter.Split(fs, PdfLoadOptions.Default, 0, Integer.MaxValue)
' INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
' ORIGINAL LINE: using var output = new FileStream(string.Format("Page {0}.pdf", ++page), FileMode.Create, FileAccess.ReadWrite);
					Using page += 1
Dim output = New FileStream($"Page {page}.pdf", FileMode.Create, FileAccess.ReadWrite)
						stream.CopyTo(output)
					End Using
				Next stream
	
				' Show the "Page 5.pdf"
				System.Diagnostics.Process.Start(New System.Diagnostics.ProcessStartInfo("Page 5.pdf") With {.UseShellExecute = True})
			End Using
		End Sub
	End Class
End Namespace

Download


Если вам нужен пример кода или у вас есть вопрос: напишите нам по адресу [email protected] или спросите в онлайн-чате (правый нижний угол этой страницы) или используйте форму ниже:



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

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