How do I rotate a PDF page?

399 views
Skip to first unread message

Support

unread,
Mar 20, 2008, 8:13:20 PM3/20/08
to PDFTron PDFNet SDK
Q: We are using the SDK to rotate PDF documents.It works fine with
most PDFs, but it doesn't work with some. The C# code fragment is
listed below:

PDFDoc doc = new PDFDoc(PdfBytes, PdfBytesSize);
Page.Rotate originalRotation = doc.GetPage(0).GetRotation();
Page.Rotate rotation;
switch (originalRotation) {
case Page.Rotate.e_0: rotation = Page.Rotate.e_90; break;
case Page.Rotate.e_90: rotation = Page.Rotate.e_180; break;
case Page.Rotate.e_180: rotation = Page.Rotate.e_270; break;
case Page.Rotate.e_270: rotation = Page.Rotate.e_0; break;
default: rotation = Page.Rotate.e_0; break;
}
doc.GetPage(0).SetRotation(rotation);
string tempFileName = Path.GetTempFileName() + ".pdf";
doc.Save(tempFileName, SDFDoc.SaveOptions.e_hex_strings);

-----
A:

There are couple of problems with your code. First you need to call
doc.InitSecurityHandler() after opening the document (since the file
is encrypted). Second, PDFNet indexes pages starting from 1, so
doc.GetPage(0).GetRotation() will throw an exception. The working code
used to rotate the first page in the document is as follows:

// In C#
PDFNet.Initialize();
try {
PDFDoc doc = new PDFDoc("mydoc.pdf");
doc.InitSecurityHandler(); // <--- !!!
Page.Rotate originalRotation = doc.GetPage(1).GetRotation();
Page.Rotate rotation;
switch (originalRotation) {
case Page.Rotate.e_0: rotation = Page.Rotate.e_90; break;
case Page.Rotate.e_90: rotation = Page.Rotate.e_180; break;
case Page.Rotate.e_180: rotation = Page.Rotate.e_270; break;
case Page.Rotate.e_270: rotation = Page.Rotate.e_0; break;
default: rotation = Page.Rotate.e_0; break; }
doc.GetPage(1).SetRotation(rotation);
doc.Save(output_path + "tiger_shift.pdf", 0); doc.Close();
Console.WriteLine("Done. Result saved in tiger_shift.pdf..."); } catch
(PDFNetException e) {
Console.WriteLine(e.Message);
}

Reply all
Reply to author
Forward
0 new messages