Move PDF Pages programmatically C#
Contents
[
Hide
]
Moving a Page from one PDF Document to Another
This topic explains how to move page from one PDF document to the end of another document using C#.
The following code snippet also work with Aspose.PDF.Drawing library.
To move an page we should:
- Create a Document class object with the source PDF file.
- Create a Document class object with the destination PDF file.
- Get Page from the the PageCollection collection’s.
- Add page to the destination document.
- Save the output PDF using the Save method.
- Delete page in source document.
- Save the source PDF using the Save method.
The following code snippet shows you how to move one page.
var srcFileName = "<enter file name>";
var dstFileName = "<enter file name>";
var srcDocument = new Document(srcFileName);
var dstDocument = new Document();
var page = srcDocument.Pages[2];
dstDocument.Pages.Add(page);
// Save output file
dstDocument.Save(srcFileName);
srcDocument.Pages.Delete(2);
srcDocument.Save(dstFileName);
Moving bunch of Pages from one PDF Document to Another
- Create a Document class object with the source PDF file.
- Create a Document class object with the destination PDF file.
- Define an array with page numbers to be moved.
- Run loop through array:
- Get Page from the the PageCollection collection’s.
- Add page to the destination document.
- Save the output PDF using the Save method.
- Delete page in source document using array.
- Save the source PDF using the Save method.
The following code snippet shows you how to move a bunch of pages from one PDF document to another.
var srcFileName = "<enter file name>";
var dstFileName = "<enter file name>";
var srcDocument = new Document(srcFileName);
var dstDocument = new Document();
var pages = new []{ 1, 3 };
foreach (var pageIndex in pages)
{
var page = srcDocument.Pages[pageIndex];
dstDocument.Pages.Add(page);
}
// Save output files
dstDocument.Save(dstFileName);
srcDocument.Pages.Delete(pages);
srcDocument.Save(srcFileName);
Moving a Page in new location in the current PDF Document
- Create a Document class object with the source PDF file.
- Get Page from the the PageCollection collection’s.
- Add page to the new location (for example to end).
- Delete page in previous location.
- Save the output PDF using the Save method.
var srcFileName = "<enter file name>";
var dstFileName = "<enter file name>";
var srcDocument = new Document(srcFileName);
var page = srcDocument.Pages[2];
srcDocument.Pages.Add(page);
srcDocument.Pages.Delete(2);
// Save output file
srcDocument.Save(dstFileName);