Skip to main content Skip to footer

How to Rotate a Page Without Changing Content

By swapping the page height and width, we can rotate the page while preserving the contents of the PDF. For example, you might have a PDF with text that is in portrait orientation, and you may want to change it to landscape orientation without shifting the text.

First, we can initialize GcPDF and open our document similar to the following:

GcPdfDocument doc = new GcPdfDocument();
FileStream fs = new FileStream("test.pdf", FileMode.Open);
doc.Load(fs);

Then, we can use the following code to edit the document, swap the height and width, and save the resulting document:

GcPdfDocument newDoc = new GcPdfDocument();
for (var i = 0; i < doc.Pages.Count; i++)
{
    var newPage = newDoc.NewPage();
    newPage.Size = new SizeF(newPage.Size.Height, newPage.Size.Width);  //Swap height and width dimensions
    var newGraphics = newPage.Graphics;
    var formXObject = new FormXObject(newDoc, doc.Pages[i]);
    newGraphics.DrawForm(formXObject, doc.Pages[i].Bounds, null, ImageAlign.CenterImage);
}
newDoc.Save("rotated.pdf");

You can download a sample project with the above code (thanks to Nitin Sharma): PdfRotate.zip

Tags:

Tye Glenz