Drawing Text

This example demonstrates how to draw text .

When creating a pdf doucment we often have content is form of text file .Which can be read and displayed in pdf

Stamp - Checking a textbox with put the watermark with text "Demo"

Clicking generate button will lauch a pdf with content from text file and stamp according to user choice

using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Text;
using OfficeComponent.Pdf;
using OfficeComponent.Pdf.Graphics;

namespace OfficeComponent.Samples
{
    class DrawingTextExample : ExampleBase
    {
        public bool Stamp
        {
            get;
            set;
        }

        public DrawingTextExample(string commonDataPath, string outputDir)
            : base(commonDataPath, outputDir)
        {
        }

        public DrawingTextExample(string commonDataPath, string outputDir, string xmlFile) : base(commonDataPath, outputDir, xmlFile)
        {
        }

        public override string Execute()
        {
            // Create a new instance of PdfDocument class.
            PdfDocument doc = new PdfDocument();

            doc.CompressionLevel = PdfCompressionLevel.NoCompression;

            // Add a page to the document.
            PdfPage page = doc.Pages.Add();

            // Read the text from the text file
            string expath = CommonDataPath + "\\EULA.txt";
            StreamReader reader = new StreamReader(expath, Encoding.ASCII);
            string text = reader.ReadToEnd();
            reader.Close();

            // Set the font
            Font f = new Font("Arial", 12);
            PdfTrueTypeFont font = new PdfTrueTypeFont(f, false);

            // Set the formats for the text
            PdfStringFormat format = new PdfStringFormat();
            format.Alignment = PdfTextAlignment.Justify;
            format.LineAlignment = PdfVerticalAlignment.Top;
            format.ParagraphIndent = 15f;

            // Create a text element 
            PdfTextElement element = new PdfTextElement(text, font);
            element.Brush = new PdfSolidBrush(Color.Black);
            element.StringFormat = format;
            element.Font = new PdfStandardFont(PdfFontFamily.Helvetica, 12);

            // Set the properties to paginate the text.
            PdfLayoutSettings layoutFormat = new PdfLayoutSettings();
            layoutFormat.Break = PdfLayoutBreakType.FitPage;
            layoutFormat.Layout = PdfLayoutType.Paginate;

            RectangleF bounds = new RectangleF(new PointF(10, 10), new SizeF(page.Graphics.ClientSize.Width - 20, page.Graphics.ClientSize.Height - 10));
            
            if (Stamp)
            {
                element.AfterPageLayout += EndPageLayout;

                // Draw the text element with the properties and formats set.
                element.Draw(page, bounds, layoutFormat);
                // Set the font
                PdfFont stampFont = new PdfStandardFont(PdfFontFamily.Helvetica, 60, PdfFontStyle.Bold);
                PdfPageTemplateElement stamp = new PdfPageTemplateElement(new SizeF(500, 500));
                stamp.Background = true;
                stamp.Graphics.SetTransparency(0.25f);
                stamp.Graphics.RotateTransform(-45);
                stamp.Graphics.DrawString("DEMO", stampFont, PdfBrushes.Blue, new PointF(-150, 400), format);
                doc.Template.Stamps.Add(stamp);

            }
            else
            {
                // Raise the events to draw the graphic elements for each page.
                element.BeforePageLayout += BeginPageLayout;
                element.AfterPageLayout += EndPageLayout;

                // Draw the text element with the properties and formats set.
                element.Draw(page, bounds, layoutFormat);
            }

            // Save and close the document.
            var outputPath = Path.Combine(OutputDir, this.GetType().Name + "_" + Guid.NewGuid().ToString() + ".pdf");
            doc.Save(outputPath);
            doc.Close(true);

            return outputPath;
        }
        private static void BeginPageLayout(object sender, BeforePageLayoutEventArgs e)
        {
            int index = e.Page.Section.Pages.IndexOf(e.Page);
            const float offset = 50;
            PdfSolidBrush brush = new PdfSolidBrush(Color.LightBlue);

            if (index % 3 == 0)
            {
                RectangleF bounds = e.Bounds;
                e.Page.Graphics.DrawPie(brush, offset + 10, offset + 10, 2 * offset, 2 * offset, 0, 270);
            }
            else
            {
                RectangleF bounds = e.Bounds;
                e.Page.Graphics.DrawRectangle(brush, offset + 10, offset + 10, 2 * offset, 2 * offset);
            }
        }

        private static void EndPageLayout(object sender, AfterPageLayoutEventArgs e)
        {
            AfterTextPageLayoutEventArgs args = (AfterTextPageLayoutEventArgs)e;
            PdfPage page = args.Result.Page;
            PdfPen pen = PdfPens.Cyan;
            page.Graphics.DrawRectangle(pen, new RectangleF(Point.Empty, page.Graphics.ClientSize));
        }
    }
}
Imports System.IO
Imports System.Text
Imports OfficeComponent.Pdf
Imports OfficeComponent.Pdf.Graphics

Namespace OfficeComponent.Samples
	Friend Class DrawingTextExample
		Inherits ExampleBase
		Private privateStamp As Boolean
		Public Property Stamp() As Boolean
			Get
				Return privateStamp
			End Get
			Set(ByVal value As Boolean)
				privateStamp = value
			End Set
		End Property

		Public Sub New(ByVal commonDataPath As String, ByVal outputDir As String)
			MyBase.New(commonDataPath, outputDir)
		End Sub

		Public Sub New(ByVal commonDataPath As String, ByVal outputDir As String, ByVal xmlFile As String)
			MyBase.New(commonDataPath, outputDir, xmlFile)
		End Sub

		Public Overrides Function Execute() As String
			' Create a new instance of PdfDocument class.
			Dim doc As New PdfDocument()

			doc.CompressionLevel = PdfCompressionLevel.NoCompression

			' Add a page to the document.
			Dim page As PdfPage = doc.Pages.Add()

			' Read the text from the text file
			Dim expath As String = CommonDataPath & "\EULA.txt"
			Dim reader As New StreamReader(expath, Encoding.ASCII)
			Dim text As String = reader.ReadToEnd()
			reader.Close()

			' Set the font
			Dim f As New Font("Arial", 12)
			Dim font As New PdfTrueTypeFont(f, False)

			' Set the formats for the text
			Dim format As New PdfStringFormat()
			format.Alignment = PdfTextAlignment.Justify
			format.LineAlignment = PdfVerticalAlignment.Top
			format.ParagraphIndent = 15F

			' Create a text element 
			Dim element As New PdfTextElement(text, font)
			element.Brush = New PdfSolidBrush(Color.Black)
			element.StringFormat = format
			element.Font = New PdfStandardFont(PdfFontFamily.Helvetica, 12)

			' Set the properties to paginate the text.
			Dim layoutFormat As New PdfLayoutSettings()
			layoutFormat.Break = PdfLayoutBreakType.FitPage
			layoutFormat.Layout = PdfLayoutType.Paginate

			Dim bounds As New RectangleF(New PointF(10, 10), New SizeF(page.Graphics.ClientSize.Width - 20, page.Graphics.ClientSize.Height - 10))

			If Stamp Then
				AddHandler element.AfterPageLayout, AddressOf EndPageLayout

				' Draw the text element with the properties and formats set.
				element.Draw(page, bounds, layoutFormat)
				' Set the font
				Dim stampFont As PdfFont = New PdfStandardFont(PdfFontFamily.Helvetica, 60, PdfFontStyle.Bold)
'INSTANT VB NOTE: The variable stamp was renamed since Visual Basic does not handle local variables named the same as class members well:
				Dim stamp_Renamed As New PdfPageTemplateElement(New SizeF(500, 500))
				stamp_Renamed.Background = True
				stamp_Renamed.Graphics.SetTransparency(0.25F)
				stamp_Renamed.Graphics.RotateTransform(-45)
				stamp_Renamed.Graphics.DrawString("DEMO", stampFont, PdfBrushes.Blue, New PointF(-150, 400), format)
				doc.Template.Stamps.Add(stamp_Renamed)

			Else
				' Raise the events to draw the graphic elements for each page.
				AddHandler element.BeforePageLayout, AddressOf BeginPageLayout
				AddHandler element.AfterPageLayout, AddressOf EndPageLayout

				' Draw the text element with the properties and formats set.
				element.Draw(page, bounds, layoutFormat)
			End If

			' Save and close the document.
			Dim outputPath = Path.Combine(OutputDir, Me.GetType().Name & "_" & Guid.NewGuid().ToString() & ".pdf")
			doc.Save(outputPath)
			doc.Close(True)

			Return outputPath
		End Function
		Private Shared Sub BeginPageLayout(ByVal sender As Object, ByVal e As BeforePageLayoutEventArgs)
			Dim index As Integer = e.Page.Section.Pages.IndexOf(e.Page)
			Const offset As Single = 50
			Dim brush As New PdfSolidBrush(Color.LightBlue)

			If index Mod 3 = 0 Then
				Dim bounds As RectangleF = e.Bounds
				e.Page.Graphics.DrawPie(brush, offset + 10, offset + 10, 2 * offset, 2 * offset, 0, 270)
			Else
				Dim bounds As RectangleF = e.Bounds
				e.Page.Graphics.DrawRectangle(brush, offset + 10, offset + 10, 2 * offset, 2 * offset)
			End If
		End Sub

		Private Shared Sub EndPageLayout(ByVal sender As Object, ByVal e As AfterPageLayoutEventArgs)
			Dim args As AfterTextPageLayoutEventArgs = CType(e, AfterTextPageLayoutEventArgs)
			Dim page As PdfPage = args.Result.Page
			Dim pen As PdfPen = PdfPens.Cyan
			page.Graphics.DrawRectangle(pen, New RectangleF(Point.Empty, page.Graphics.ClientSize))
		End Sub
	End Class
End Namespace