Introduction
While working on applications requiring PDF processing
you very often encounter a task of splitting a single PDF document to multiple
pages. Our well-known library, Apitron PDF Kit makes you able to achieve this goal in clean and
reliable manner.
We’ll keep the demonstration simple as code speaks for
itself better than a thousand words, see the complete listing with comments
below.
The code
void SplitPDFDocument()
{
//
open main PDF file
using (Stream file = File.OpenRead("fileToSplit.pdf"))
{
FixedDocument pdfDocument = new FixedDocument(file);
//
enumerate pages and save each page as separate PDF file
for (int i = 0; i < pdfDocument.Pages.Count; i++)
{
FixedDocument pagePdfDocument = new FixedDocument();
//
Export page before inserting it into the new document,
//
it preserves resources used by this page.
pagePdfDocument.Pages.Add(Page.Export(pagePdfDocument,pdfDocument.Pages[i]));
//
save page document
using (Stream outputStream = File.Create(string.Format("page{0}.pdf",i)))
{
pagePdfDocument.Save(outputStream);
}
}
}
}
The code above enumerates
document pages and saves each page as separate PDF file, it’s important to note
that each page should be “exported” prior to saving. Exporting will preserve
resources used by page content and make sure it’s viewable. The complete book,
describing PDF internals and processing techniques made possible with Apitron
PDF Kit, is available by the following link.
Downloadable version of this article can be found by the following link [PDF].
No comments:
Post a Comment