Create PDF Template Document by Using C#

Sometimes, we need to create several PDF documents or each pages in a PDF document with the same format, for example, add some labels at the edge of pages. In this post, I will show how to set PDF template by using C#.

In my example, there are two template settings, document template and section template. Document template includes pages size and margin settings, while for section template, label will be added at edge of pages.

The following steps show details.

  1. Create a PDF document and set margin for it.
  2. Set document template. There parameters should be passed to SetDocumentTemplate method, document, page size and margin. Then, set template elements, including left space, top space, right space and bottom space.
  3. Add section and set section template. In SetSectionTemplate method, I pass four parameters, section, page size, margin and label string. Besides, template format should be set. Firstly, set odd pages template. Put label on left of odd pages. Then, after setting location of label, drawing label string, including text font style, color and alignment. Secondly, set even pages template. Put label on the right of even pages. Then, set location and draw label string with format.
  4. Add page and draw. When drawing page, draw title firstly, including title string, format and location. Then, draw icon and content. Icon and content are from files I prepare. Load them and then set format, location for them. Finally, add background image to make appearance be more beautiful.
  5. Save and launch file.

Note: I use a C# .NET PDF component, Spire.PDF for .NET in this example, so I have added its dll file in project at the beginning.

Main Coding:

using System;
using System.Drawing;
using Spire.Pdf;
using Spire.Pdf.Graphics;
using Spire.Pdf.AutomaticFields;

namespace PDFTemplate
    class Template
        static void Main(string[] args)
            //Create PDF
            PdfDocument doc = new PdfDocument();
            doc.ViewerPreferences.PageLayout = PdfPageLayout.TwoColumnLeft;

            PdfUnitConvertor unitCvtr = new PdfUnitConvertor();
            PdfMargins margin = new PdfMargins();
            margin.Top = unitCvtr.ConvertUnits(2.54f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point);
            margin.Bottom = margin.Top;
            margin.Left = unitCvtr.ConvertUnits(3.17f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point);
            margin.Right = margin.Left;

            //Set Document Template
            SetDocumentTemplate(doc, PdfPageSize.A4, margin);

            //Add Section and Set Section Template
            PdfSection section = doc.Sections.Add();
            section.PageSettings.Size = PdfPageSize.A4;
            section.PageSettings.Margins = new PdfMargins(0);
            SetSectionTemplate(section, PdfPageSize.A4, margin, “Example Label”);

            //Add and Draw Page
            PdfNewPage page = section.Pages.Add();
            page = section.Pages.Add();
            page = section.Pages.Add();

            //Save and Launch

        static void SetSectionTemplate(PdfSection section, SizeF pageSize, PdfMargins margin, String label)
            PdfPageTemplateElement leftSpace
                = new PdfPageTemplateElement(margin.Left, pageSize.Height);
            leftSpace.Foreground = true;
            section.Template.OddLeft = leftSpace;
            PdfTrueTypeFont font = new PdfTrueTypeFont(new Font(“Calibri”, 11f, FontStyle.Regular));
            PdfStringFormat format = new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle);
            float y = (pageSize.Height – margin.Top – margin.Bottom) * (1 – 0.618f);
            RectangleF bounds
                = new RectangleF(10, y, margin.Left – 20, font.Height + 6);
            leftSpace.Graphics.DrawRectangle(PdfBrushes.WhiteSmoke, bounds);
            leftSpace.Graphics.DrawString(label, font, PdfBrushes.LimeGreen, bounds, format);
            PdfPageTemplateElement rightSpace
                = new PdfPageTemplateElement(margin.Right, pageSize.Height);
            rightSpace.Foreground = true;
            section.Template.EvenRight = rightSpace;
                = new RectangleF(10, y, margin.Right – 20, font.Height + 6);
            rightSpace.Graphics.DrawRectangle(PdfBrushes.LimeGreen, bounds);
            rightSpace.Graphics.DrawString(label, font, PdfBrushes.White, bounds, format);

        static void SetDocumentTemplate(PdfDocument doc, SizeF pageSize, PdfMargins margin)
            PdfPageTemplateElement leftSpace
                = new PdfPageTemplateElement(margin.Left, pageSize.Height);
            doc.Template.Left = leftSpace;
            PdfPageTemplateElement topSpace
                = new PdfPageTemplateElement(pageSize.Width, margin.Top);
            topSpace.Foreground = true;
            doc.Template.Top = topSpace;
            PdfPageTemplateElement rightSpace
                = new PdfPageTemplateElement(margin.Right, pageSize.Height);
            doc.Template.Right = rightSpace;
            PdfPageTemplateElement bottomSpace
                = new PdfPageTemplateElement(pageSize.Width, margin.Bottom);
            bottomSpace.Foreground = true;
            doc.Template.Bottom = bottomSpace;

        static void DrawPage(PdfPageBase page)
            float pageWidth = page.Canvas.ClientSize.Width;
            float y = 0;

            y = y + 25;
            PdfBrush brush1 = new PdfSolidBrush(Color.Red);
            PdfBrush brush2 = new PdfSolidBrush(Color.DarkOrange);
            PdfTrueTypeFont font1 = new PdfTrueTypeFont(new Font(“Calibri”, 14f, FontStyle.Regular));
            PdfStringFormat format1 = new PdfStringFormat(PdfTextAlignment.Center);
            format1.CharacterSpacing = 1f;
            String text = “Cold Joke”;
            page.Canvas.DrawString(text, font1, brush1, pageWidth / 2, y, format1);
            SizeF size = font1.MeasureString(text, format1);
            y = y + size.Height + 6;

            PdfImage image = PdfImage.FromFile(@”D:\work\My Documents\cold joke.jpg”);
            page.Canvas.DrawImage(image, new PointF(pageWidth – image.PhysicalDimension.Width, y));
            float imageLeftSpace = pageWidth – image.PhysicalDimension.Width – 2;
            float imageBottom = image.PhysicalDimension.Height + y;

            PdfStringFormat format2 = new PdfStringFormat();
            text = System.IO.File.ReadAllText(@”D:\work\My Documents\cold joke.txt”);
            PdfTrueTypeFont font2 = new PdfTrueTypeFont(new Font(“Calibri”, 12f));
            format2.LineSpacing = font2.Size * 1.5f;
            PdfStringLayouter textLayouter = new PdfStringLayouter();
            float imageLeftBlockHeight = imageBottom – y;
            PdfStringLayoutResult result
                = textLayouter.Layout(text, font2, format2, new SizeF(imageLeftSpace, imageLeftBlockHeight));

            if (result.ActualSize.Height < imageBottom – y)
                imageLeftBlockHeight = imageLeftBlockHeight + result.LineHeight;
                result = textLayouter.Layout(text, font2, format2, new SizeF(imageLeftSpace, imageLeftBlockHeight));

            foreach (LineInfo line in result.Lines)
                page.Canvas.DrawString(line.Text, font2, brush2, 0, y, format2);
                y = y + result.LineHeight;

            PdfTextWidget textWidget = new PdfTextWidget(result.Remainder, font2, brush2);
            PdfTextLayout textLayout = new PdfTextLayout();
            textLayout.Break = PdfLayoutBreakType.FitPage;
            textLayout.Layout = PdfLayoutType.Paginate;
            RectangleF bounds = new RectangleF(new PointF(0, y), page.Canvas.ClientSize);
            textWidget.StringFormat = format2;
            textWidget.Draw(page, bounds, textLayout);

            //Background Image
            Image img = Image.FromFile(@”D:\work\My Documents\bi.png”);
            page.BackgroundImage = img;

Result Shown by Following:

Download Spire.PDF for .NET Here


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s