简体   繁体   中英

How can i identify pdf orientation whether landscape or portrait using itextsharp library in C#

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!

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM