Split PDF files in C++

Export each page of a PDF to its own file for review or further processing.

Split a PDF into single-page files

  1. Open the input PDF as a Document.
  2. Iterate through the PageCollection, starting at index 1.
  3. Create an empty Document for each page.
  4. Copy the source page into the new document with CopyPage().
  5. Save each document with Document::Save() using a unique name such as page_1.pdf.
  6. Report any page processing errors and continue with the remaining pages.
#include <exception>
#include <iostream>

#include <system/io/path.h>

#include <Aspose.PDF.Cpp/Document.h>
#include <Aspose.PDF.Cpp/Page.h>
#include <Aspose.PDF.Cpp/PageCollection.h>

using namespace System;
using namespace Aspose::Pdf;

void SplitDocument(String inputFile, String outputDir) {
    auto document = MakeObject<Document>(inputFile);
    try {
        
        for (int pageNumber = 1; pageNumber <= document->get_Pages()->get_Count(); pageNumber++) {
            auto newDocument = MakeObject<Document>();
            try {
                auto page = document->get_Pages()->idx_get(pageNumber);
                newDocument->get_Pages()->CopyPage(page);
                auto outputFile = System::IO::Path::Combine(outputDir, System::String::Format(u"page_{0}.pdf", pageNumber));
                newDocument->Save(outputFile);
            }
            catch (std::exception& e) {
                std::cerr << e.what();
            }            
        }
    }
    catch (std::exception& e) {
        std::cerr << e.what();
    }
}