Intelligent page breaks (C# / netframework)
Note
This demo is available in your FlexCel installation at <FlexCel Install Folder>\samples\csharp\VS2022\netframework\10.API\72.Intelligent Page Breaks and also at https://github.com/tmssoftware/TMS-FlexCel.NET-demos/tree/master/csharp/VS2022/netframework/Modules/10.API/72.Intelligent Page Breaks
Overview
While there is no direct support in Excel for Widow/Orphan control, FlexCel has the capacity to add page breaks to your file, so you can keep interesting sections together.
Make sure to read the conceptual documentation about Intelligent Page Breaks to better understand what we are doing here.
Concepts
How to add automatic page breaks to a sheet. In this case, we are dumping a C# file to PDF, and we want to keep procedures in the same page is possible.
How to deal with different levels of "keep together". FlexCel allows you to make some rows more "keep together" than others, if it can't fit everything in the same page, it will try to keep the rows of higher "keep together". We use this here to try to keep full classes first, if it is not possible full procedures, if not full for/while loops, etc.\ Each "{" sign in the source file means higher level of "keep together", and each "}" decreases the level.
The method ExcelFile.AutoPageBreaks must be called after everything is done, so the sheet is in a final state when applying the page breaks.
Files
AssemblyInfo.cs
using System.Reflection;
using System.Runtime.CompilerServices;
//
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
//
[assembly: AssemblyTitle("")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("(c) 2002 - 2025 TMS Software")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
//
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("7.24.0.0")]
//
// In order to sign your assembly you must specify a key to use. Refer to the
// Microsoft .NET Framework documentation for more information on assembly signing.
//
// Use the attributes below to control which key is used for signing.
//
// Notes:
// (*) If no key is specified, the assembly is not signed.
// (*) KeyName refers to a key that has been installed in the Crypto Service
// Provider (CSP) on your machine. KeyFile refers to a file which contains
// a key.
// (*) If the KeyFile and the KeyName values are both specified, the
// following processing occurs:
// (1) If the KeyName can be found in the CSP, that key is used.
// (2) If the KeyName does not exist and the KeyFile does exist, the key
// in the KeyFile is installed into the CSP and used.
// (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility.
// When specifying the KeyFile, the location of the KeyFile should be
// relative to the project output directory which is
// %Project Directory%\obj\<configuration>. For example, if your KeyFile is
// located in the project directory, you would specify the AssemblyKeyFile
// attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")]
// (*) Delay Signing is an advanced option - see the Microsoft .NET Framework
// documentation for more information on this.
//
[assembly: AssemblyDelaySign(false)]
[assembly: AssemblyKeyFile("")]
[assembly: AssemblyKeyName("")]
Form1.cs
using System;
using System.Drawing;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using FlexCel.Core;
using FlexCel.XlsAdapter;
using System.IO;
using System.Diagnostics;
using System.Reflection;
using System.Text;
using FlexCel.Render;
namespace IntelligentPageBreaks
{
/// <summary>
/// Demo showing how to create intelligent page breaks with the API.
/// </summary>
public partial class mainForm: System.Windows.Forms.Form
{
public mainForm()
{
InitializeComponent();
}
private Dictionary<string, string> Keywords = CreateKeywords();
private static Dictionary<string, string> CreateKeywords()
{
// A very silly syntax highlighter. We don't have any context here, so for example "get" will be highlighted when it is a property or when it is not, but it is ok for this demo.
Dictionary<string, string> Result = new Dictionary<string, string>();
Result.Add("private", null);
Result.Add("public", null);
Result.Add("protected", null);
Result.Add("internal", null);
Result.Add("static", null);
Result.Add("void", null);
Result.Add("get", null);
Result.Add("set", null);
Result.Add("return", null);
Result.Add("while", null);
Result.Add("for", null);
Result.Add("foreach", null);
Result.Add("using", null);
Result.Add("true", null);
Result.Add("false", null);
return Result;
}
private string PathToExe
{
get
{
return Path.Combine(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), ".."), "..") + Path.DirectorySeparatorChar;
}
}
private TRichString SyntaxColor(ExcelFile Xls, int NormalFont, int CommentFont, int HighlightFont, string line)
{
List<TRTFRun> RTFRunList = new List<TRTFRun>();
int i = 0;
while (i < line.Length)
{
if (i > 0 && line[i - 1] == '/' && line[i] == '/')
{
TRTFRun rtf;
rtf.FirstChar = i - 1;
rtf.FontIndex = CommentFont;
RTFRunList.Add(rtf);
return new TRichString(line, RTFRunList.ToArray(), Xls);
}
int start = i;
while (i < line.Length && char.IsLetterOrDigit(line[i]))
{
i++;
}
if (i > start && Keywords.ContainsKey(line.Substring(start, i - start)))
{
TRTFRun rtf;
rtf.FirstChar = start;
rtf.FontIndex = HighlightFont;
RTFRunList.Add(rtf);
rtf.FirstChar = i;
rtf.FontIndex = NormalFont;
RTFRunList.Add(rtf);
}
i++;
}
return new TRichString(line, RTFRunList.ToArray(), Xls);
}
private void DumpFile(ExcelFile Xls, ref int Row)
{
TFlxFont fnt = Xls.GetDefaultFont;
fnt.Color = Color.Blue;
int HighlightFont = Xls.AddFont(fnt);
fnt.Color = Color.Green;
int CommentFont = Xls.AddFont(fnt);
int Level = 0;
Stack<int> LevelStart = new Stack<int>();
LevelStart.Push(Row);
using (StreamReader sr = new StreamReader(Path.Combine(PathToExe, "Form1.cs")))
{
string line;
while ((line = sr.ReadLine()) != null)
{
//Find the level of "keep together" for the row. We will use #region and "{" delimiters
//to increase the level. If possible, we would want those blocks together in one page.
string s = line.Trim();
if (s.StartsWith("#region")) { Level++; LevelStart.Push(Row); }
if (s == "{")
{
Level++;
LevelStart.Push(Row - 1);//On {} blocks, we want to keep lines together starting with the previous statement.
}
if (s == "#endregion" || s == "}")
{
Level--;
Xls.KeepRowsTogether(LevelStart.Pop(), Row, Level + 1, false);
}
Xls.KeepRowsTogether(Row, Row, Level, true);
Xls.SetCellValue(Row, 1, SyntaxColor(Xls, 0, CommentFont, HighlightFont, line.Replace("\t", " ")));
Row++;
}
}
}
private void AddData(ExcelFile Xls)
{
//Fill the file with the contents of this c# file, many times so we can see many page breaks.
int Row = 3;
DumpFile(Xls, ref Row);
Xls.AutofitRowsOnWorkbook(false, true, 1);
Xls.AutoPageBreaks(50, 100); // we will use a 100% of page scale since we are printing to pdf.
//If this was to create an Excel file, pagescale should be lower to
//compensate the differences between page sizes in diiferent printers in Excel
//Export the file to PDF so we can see the page breaks.
using (FlexCelPdfExport pdf = new FlexCelPdfExport(Xls, true))
{
pdf.Export(saveFileDialog1.FileName);
}
}
private void button1_Click(object sender, System.EventArgs e)
{
AutoRun();
}
public void AutoRun()
{
if (saveFileDialog1.ShowDialog() != DialogResult.OK) return;
ExcelFile Xls = new XlsFile(true);
Xls.NewFile(1, TExcelFileFormat.v2019);
Xls.SetColWidth(1, 78 * 256); //;make longer lines wrap in the cell.
TFlxFormat fmt = Xls.GetFormat(Xls.GetColFormat(1));
fmt.WrapText = true;
Xls.SetColFormat(1, Xls.AddFormat(fmt));
AddData(Xls);
if (MessageBox.Show("Do you want to open the generated file?", "Confirm", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
using (Process p = new Process())
{
p.StartInfo.FileName = saveFileDialog1.FileName;
p.StartInfo.UseShellExecute = true;
p.Start();
}
}
}
}
}
Form1.Designer.cs
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using FlexCel.Core;
using FlexCel.XlsAdapter;
using System.IO;
using System.Diagnostics;
using System.Reflection;
using System.Text;
using FlexCel.Render;
namespace IntelligentPageBreaks
{
public partial class mainForm: System.Windows.Forms.Form
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.saveFileDialog1 = new System.Windows.Forms.SaveFileDialog();
this.label1 = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// button1
//
this.button1.Anchor = System.Windows.Forms.AnchorStyles.Bottom;
this.button1.Location = new System.Drawing.Point(132, 73);
this.button1.Name = "button1";
this.button1.TabIndex = 0;
this.button1.Text = "GO!";
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// saveFileDialog1
//
this.saveFileDialog1.Filter = "Pdf Files|*.pdf";
this.saveFileDialog1.RestoreDirectory = true;
this.saveFileDialog1.Title = "Select PDF file to save";
//
// label1
//
this.label1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.label1.BackColor = System.Drawing.Color.FromArgb(((System.Byte)(255)), ((System.Byte)(255)), ((System.Byte)(192)));
this.label1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.label1.Location = new System.Drawing.Point(16, 16);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(312, 32);
this.label1.TabIndex = 1;
this.label1.Text = "A demo on how to have FlexCel paginate your documents so they keep their section" +
"s together.";
//
// mainForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(336, 110);
this.Controls.Add(this.label1);
this.Controls.Add(this.button1);
this.Name = "mainForm";
this.Text = "Intelligent Page Breaks";
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Button button1;
private System.Windows.Forms.SaveFileDialog saveFileDialog1;
private System.Windows.Forms.Label label1;
}
}
Program.cs
using System;
using System.Windows.Forms;
namespace IntelligentPageBreaks
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new mainForm());
}
}
}