Example_32

Drawing source code with highlighted keywords using the TextLine component.

Example_32.pdf — the PDF this example creates.

/*
 * Example_32.cs
 *
 * Copyright (c) 2026 PDFjet Software
 * Licensed under the MIT License. See LICENSE file in the project root.
 */
using System;
using System.IO;
using System.Diagnostics;
using System.Collections.Generic;

using PDFjet.NET;

/**
 * Example_32.cs
 */
public class Example_32 {
    public Example_32() {
        PDF pdf = new PDF(new BufferedStream(
                new FileStream("Example_32.pdf", FileMode.Create)));

        Font font = new Font(pdf, JetBrainsMono.Regular);
        font.SetSize(10f);

        Dictionary<String, Int32> colors = new Dictionary<String, Int32>();
        colors["new"] = Color.red;
        colors["class"] = Color.blue;
        colors["void"] = Color.green;
        float[] grayColor = new float[] {0.2f, 0.2f, 0.2f};

        Page page = new Page(pdf, Letter.PORTRAIT);
        float x = 50f;
        float y = 50f;
        float leading = font.GetBodyHeight();
        List<String> lines = Content.LinesOfTextFile("examples/Example_02.java");
        foreach (String line in lines) {
            new TextLine(font, line).SetTextColor(grayColor).SetHighlightColors(colors).SetLocation(x, y).DrawOn(page);
            y += leading;
            if (y > (page.GetHeight() - 20f)) {
                page = new Page(pdf, Letter.PORTRAIT);
                y = 50f;
            }
        }

        pdf.Complete();
    }

    public static void Main(String[] args) {
        Stopwatch sw = Stopwatch.StartNew();
        long time0 = sw.ElapsedMilliseconds;
        new Example_32();
        long time1 = sw.ElapsedMilliseconds;
        sw.Stop();
        Console.WriteLine($"Example_32 => {time1 - time0,4} ms");
    }
}   // End of Example_32.cs

©2026 PDFjet Software.