Split PDF files in C++
Contents
[
Hide
]
Export each page of a PDF to its own file for review or further processing.
Split a PDF into single-page files
- Open the input PDF as a Document.
- Iterate through the PageCollection, starting at index 1.
- Create an empty Document for each page.
- Copy the source page into the new document with CopyPage().
- Save each document with Document::Save() using a unique name such as page_1.pdf.
- 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();
}
}