Reputation: 220
Can any one know how can I identify pdf orientation whether landscape or portrait using itextsharp library in C#
.
Here is my code below, It is retrieving PDF
stream and rotating the image, but my problem is that how can we identify orientation?
public static string ReadPdfFile(string fileName)
{
StringBuilder text = new StringBuilder();
if (File.Exists(fileName))
{
byte[] bytes = System.IO.File.ReadAllBytes(fileName);
using (MemoryStream ms = new MemoryStream())
{
Document doc = new Document();
PdfWriter writer = PdfWriter.GetInstance(doc, ms);
doc.Open();
PdfContentByte cb = writer.DirectContent;
PdfImportedPage page;
PdfReader reader;
reader = new PdfReader(bytes);
int pages = reader.NumberOfPages;
// loop over document pages
for (int i = 1; i <= pages; i++)
{
page = writer.GetImportedPage(reader, i);
//Rectangle pagesize = reader.GetPageSizeWithRotation(0);
AffineTransform scale = new AffineTransform(0, 1.0F, -1.0F, 0, 500, 500);
cb.AddTemplate(page,scale);
}
doc.Close();
var rotatedFile = ms.GetBuffer();
ms.Flush();
ms.Dispose();
string filepath = @"D:\test2.pdf";
File.Delete(filepath);
using (FileStream Writer = new System.IO.FileStream(filepath, FileMode.Create, FileAccess.Write))
{
Writer.Write(rotatedFile, 0, rotatedFile.Length);
string actualFilePath = "test2.pdf";
filepath = actualFilePath;
}
}
Please help me, Thanks in advance!
Upvotes: 4
Views: 5853
Reputation: 2317
I evaluate the rectangle size of a page to find that out. Something to keep in mind... you can have multiple orientations within the same file, so you can't decide a file is landscape based on solely the first page. A file is landscape if all the pages are landscape, otherwise it's a mixed orientation file.
Rectangle currentPageRectangle = pdfReader.GetPageSizeWithRotation(<PageNumberHere>);
if (currentPageRectangle.Width > currentPageRectangle.Height)
{
//page is landscape
}
else
{
//page is portrait
}
Upvotes: 6