2

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.

Luke101
  • 63,072
  • 85
  • 231
  • 359

3 Answers3

10

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.

mkl
  • 90,588
  • 15
  • 125
  • 265
  • And what is the crop box compared to the page size? – ˈvɔlə May 10 '23 at 16:07
  • 1
    @ˈvɔlə *"And what is the crop box compared to the page size?"* - see [this answer](https://stackoverflow.com/a/13240546/1729265) for a characterization of the boxes (media, crop, bleed, trim, art). – mkl May 10 '23 at 16:43
1

how about using this:-

PdfReader reader = new PdfReader(m);
PdfImportedPage page = writer.GetImportedPage(pdfReader, i);
// size information
page.PageSize.Width;
page.PageSize.Height;
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
  • 1
    Importing a page is totally unnecessary, `PdfReader` already offers methods to return the page dimensions. – mkl Sep 19 '13 at 07:14
0

Try this:

using iText.Kernel.Pdf;

PdfReader pdfReader = new PdfReader(yourfile);
PdfDocument pdf = new PdfDocument(pdfReader);

var height = pdf.GetPage(1).GetPageSize().GetHeight();
var width = pdf.GetPage(1).GetPageSize().GetWidth();

Where 1 is the number of the page that you want to extract the dimension. If you want to convert the result to mm, just do that:

var widthMM = width*25,4/72
Darós
  • 158
  • 1
  • 3
  • 9