Search code examples
c#pdfitext

How to get PDF page dimensions


I have an existing pdf and extracting text from the pdf. Here is the code I have already

using iTextSharp.text.pdf;
using iTextSharp.text.pdf.parser;
using System.IO;

public string ReadPdfFile(string fileName)
{
    StringBuilder text = new StringBuilder();

    if (File.Exists(fileName))
    {
        PdfReader pdfReader = new PdfReader(fileName);

        for (int page = 1; page <= pdfReader.NumberOfPages; page++)
        {
            ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();
            string currentText = PdfTextExtractor.GetTextFromPage(pdfReader, page, strategy);

            currentText = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(currentText)));
            text.Append(currentText);
        }
        pdfReader.Close();
    }
    return text.ToString();
}

I would like to get the dimensions of the pdf page. I need the dimensions so I can create a wrapper class that contains this information. Then the class can determine if rectangles are out of bounds.


Solution

  • I would like to get the dimensions of the pdf page.

    The PdfReader class supplies methods to retrieve them:

    PdfReader pdfReader = new PdfReader(fileName);
    
    Rectangle mediabox = pdfReader.GetPageSize(pageNr);
    Rectangle cropbox = pdfReader.GetCropBox(pageNr);
    

    Depending on which dimensions you actually need, use either of those.