How to load font from filename (TTF) to use in PDF document generated using Bytescout.PDF library for .NET

Loading fonts from files to use for text in PDF documents

This example demonstrates how to load font from file and how to use this font to add text into PDF document generated using Bytescout.PDF library. You can also use built-in PDF fonts (see sample)

Text in PDF using fonts loaded from files

Download example source code: bytescoutpdf_fonts_from_file_names_ttf.zip (25 KB)

using System;
using System.Collections.Generic;
using System.Text;
using Bytescout.PDF;
using System.Diagnostics;

namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
// Create main PDF Doc Engine
PDFDocEngine engine = new PDFDocEngine("", "");

// Add new document
Document document = engine.AddDocument();

// Append new page to the document
Page page = document.AddPage(PageSizeType.A3, PageOrientationType.LandScape);

// Create new drawing
Drawing drawing = page.AddDrawing();

// font size constant
const int fontSize = 50;

// get path to Windows folder
string WinPath = Environment.GetEnvironmentVariable("SystemRoot");

// Create array with font types
string[] fontFileNames = new string[] {
WinPath + "\\Fonts\\Arial.ttf",
WinPath + "\\Fonts\\Tahomabd.ttf",
WinPath + "\\Fonts\\Timesbi.ttf"
};

// X position of the text to draw
int textX = 10;
// Y position of the text to draw
int textY = 50;

// Draw all font types
foreach (string fontFileName in fontFileNames)
{
// Add standard font
uint font = document.AddFontTrueType(fontFileName);

// Set Active Font
drawing.SetActiveFont(font, fontSize, false, false);

// Draw Text
drawing.PlaceText(textX, textY, 0, fontFileName);

// Increase position of the next text
textY += fontSize + 20;
}


// Save document
document.Save("FontsFromFiles.pdf");

// open generated PDF document in default PDF viewer installed in Windows
Process.Start("FontsFromFiles.pdf");
}
}
}

Download example source code: bytescoutpdf_fonts_from_file_names_ttf.zip (25 KB)

Filed in: PDF SDK for .NET

Tutorials: