Calculate the height of a paragraph in PDF

Calculate the height of a paragraph in PDF

This code sample demonstrates how to use the event mechanism to calculate the height of a paragraph in a PDF. The program writes the height of the paragraph to the console.

using System;
using System.IO;

using TallComponents.PDF;
using TallComponents.PDF.Layout;
using TallComponents.PDF.Layout.Paragraphs;

namespace CalculateParagraphHeight
{
   class Program
   {
      static double startY;
      static double endY;

      static void Main(string[] args)
      {
         Document document = new Document();
         Section section = document.Sections.Add();

         section.Paragraphs.PrintParagraph += 
            new PrintParagraphEventHandler(section_PrintParagraph);

         using (FileStream file = 
            new FileStream(@"..\..\out.pdf", FileMode.Create, FileAccess.Write))
         {
            document.Write(file);
         }

         Console.WriteLine("Height: {0:f1} points", startY - endY);
      }

      static void section_PrintParagraph(
         ParagraphCollection sender, PrintParagraphEventArgs e)
      {
         RtfParagraph rtf = new RtfParagraph();
         rtf.Text = File.ReadAllText(@"..\..\sample.rtf");
         rtf.EndParagraph += new EndParagraphEventHandler(rtf_EndParagraph);
         e.Paragraph = rtf;
         startY = e.Top;
      }

      static void rtf_EndParagraph(Paragraph sender, EndParagraphEventArgs e)
      {
         endY = e.Bottom;
      }
   }
}