Rotate, delete, move and insert pages of an existing PDF in C# with OnePDF; bookmarks and links to deleted pages are repaired.
using OnePdf; using PdfDocument doc = PdfDocument.Open("report.pdf", new PdfOpenOptions { AllowEditing = true }); Console.WriteLine($"before: {doc.PageCount} pages"); doc.RotatePage(0, 90); // clockwise, added to the page's current rotation doc.SetPageRotation(1, 0); // absolute: upright, whatever it was doc.RemovePages([2, 3]); // zero-based; bookmarks and links to them are repaired doc.MovePage(fromIndex: 0, toIndex: 3); // the first page goes to the end doc.InsertBlankPage(0, 612, 792); // a blank US Letter page in front (width, height in points) // Pages taken before an operation are out of date; read doc.Pages again. for (int i = 0; i < doc.PageCount; i++) Console.WriteLine($"page {i + 1}: rotate {doc.Pages[i].Rotate}"); doc.Save("report-edited.pdf");
before: 6 pages page 1: rotate 0 page 2: rotate 0 page 3: rotate 0 page 4: rotate 0 page 5: rotate 90
The new first page is the blank one, and the old first page, now turned 90 degrees, is last.
| Call | What it does |
|---|---|
RotatePage(index, degrees) | Adds to the page’s rotation, clockwise. Multiples of 90. |
SetPageRotation(index, degrees) | Sets the rotation outright. |
RemovePage(index), RemovePages(indexes) | Deletes pages. |
MovePage(from, to) | to is the page’s index afterwards. |
ReorderPages(newOrder) | newOrder[i] is the current index of the page that becomes page i. |
InsertBlankPage(index, width, height) | A blank page, size in points (612 × 792 is US Letter, 595 × 842 is A4). |
DuplicatePage(index) | A copy right after the page. |
Good to know
- The document must be opened with
AllowEditing = true. Page indexes are zero-based. PdfPageobjects, the outline and the form taken before an operation are out of date afterwards. Readdoc.Pagesagain.- Deleting a page drops bookmarks and named destinations that led to it, empties links that pointed at it, removes form fields whose widgets were all on it, and renumbers page labels. The structure tree of a tagged file is dropped on deletion, with a diagnostic, because it would keep the deleted content in the file. Rotating and reordering keep it.
Savewrites only what the remaining pages use, so a deleted page’s content is gone from the file.SaveIncrementalkeeps the old objects, as any incremental update does: don’t use it to get rid of content.
Copying pages between files is in Merge PDFs. Everything else is in Page operations.