DotNetT2 Light_1200x303

Learn how to use the new text-measuring functionality in SpreadProcessing and SpreadStreamProcessing.

Measuring text is usually a tough task when it comes to documents, especially in .NET Standard projects where the platform doesn’t provide any API to achieve that. The text is a core building piece of the documents, and, if not properly measured, it can destroy the look and sometimes even the meaning of the data it represents.

👉 With the two document processing libraries for working with spreadsheet documents, SpreadProcessing and SpreadStreamProcessing, this is not an issue anymore.

In the latest R2 2021 release, we introduced extension points that allow you to measure the content you need using the precision of the .NET Framework or, for .NET Standard projects, of PdfProcessing. PdfProcessing is designed to work with PDF documents where everything should be measured and positioned with great accuracy. So, the new extensions help you use that precision in your spreadsheets as well. In this post, I will show you the new API of the two libraries.

SpreadProcessing for .NET Standard

The .NET Framework version of SpreadProcessing has a built-in capability of measuring the content when needed. As I mentioned in the beginning of this post, such a capability is not available in .NET Standard due to platform limitations.

To overcome the aforementioned limitations, we have introduced an extension point for defining a text measurer along with a simple implementation of such. This simple text measurer tries to predict the width of a string using a predefined set of character widths in specific fonts.

This prediction turned out to be inaccurate for many cases, and the other possible approach was to define a custom measurer that could calculate a more accurate result. We have noticed that it takes our customers a lot of time and effort to implement this, and we decided to improve it by using the already existing measuring logic of PdfProcessing.

All you need to do to enable the new measuring mechanism is set the TextMeasurer property of SpreadExtensibilityManager to an instance of SpreadFixedTextMeasurer:

SpreadTextMeasurerBase fixedTextMeasurer = new SpreadFixedTextMeasurer();
SpreadExtensibilityManager.TextMeasurer = fixedTextMeasurer;

Do not forget that the SpreadFixedTextMeasurer uses PdfProcessing and needs a reference to the Telerik.Documents.Fixed.dll.

If you are eager to learn more details about this functionality, go straight to the Text Measuring help topic to find all the needed information.

SpreadStreamProcessing

The streaming library is built with .NET Standard compatibility and great performance in mind, thus it doesn’t support any measuring at all. With the new CellContentSizeHelper class, you can now obtain the size that a specific piece of content would need to render, so you can set it to the row or column that contains it. This way, you can achieve a functionality pretty close to auto-fitting the contents of a row or column.

Important Details

The CellContentSizeHelper class uses SpreadProcessing’s measuring logic. That is why you should add a reference to Telerik.Windows.Documents.Spreadsheet.dll for .NET Framework projects or Telerik.Documents.Spreadsheet.dll for .NET Standard projects.

In .NET Standard, you can control the measuring logic through the SpreadExtensibilityManager.TextMeasurer as described in the previous section of this post.

Example

The CellContentSizeHelper class exposes different overloads of the GetCellContentSize method that enable you to specify the formatting applied to the text content. Measuring text is now as simple as passing the string and the styling properties you need to apply on it to a single method. The following example shows how you can create a spreadsheet document that has columns as wide as the content needs them to be.

public static void ExportSpreadsheet(SpreadDocumentFormat documentFormat, string fileName)
{
    SpreadCellFormat format = new SpreadCellFormat()
    {
        NumberFormat = "@",
        IsBold = true,
        IsItalic = true
    };
  
    string[] vegetablesToExport = new string[] { "carrot", "broccoli", "cucumber", "eggplant", "lettuce", "cabbage", "tomato" };
  
    double vegetablesColumnWidth;
    CalculateColumnWidth(format, vegetablesToExport, out vegetablesColumnWidth);
  
    using (FileStream stream = File.Open(fileName, FileMode.OpenOrCreate))
    {
        using (IWorkbookExporter workbook = SpreadExporter.CreateWorkbookExporter(documentFormat, stream))
        {
            using (IWorksheetExporter worksheet = workbook.CreateWorksheetExporter("Vegetables List"))
            {
                using (IColumnExporter column = worksheet.CreateColumnExporter())
                {
                    column.SetWidthInPixels(vegetablesColumnWidth);
                }
  
                for (int rowIndex = 1; rowIndex < vegetablesToExport.Length + 1; rowIndex++)
                {
                    using (IRowExporter row = worksheet.CreateRowExporter())
                    {
                        string vegetable = vegetablesToExport[rowIndex - 1];
  
                        using (ICellExporter cell = row.CreateCellExporter())
                        {
                            cell.SetValue(vegetable);
                            cell.SetFormat(format);
                        }
                    }
                }
            }
        }
    }
}
  
private static void CalculateColumnWidth(SpreadCellFormat format, string[] values, out double columnWidth)
{
    columnWidth = 0;
  
    for (int i = 0; i < values.Length; i++)
    {
        double contentWidth = CellContentSizeHelper.GetCellContentSize(values[i], format).Width;
        columnWidth = Math.Max(columnWidth, contentWidth);
    }
}

As you can see, the CalculateColumnWidth method is the one that invokes GetCellContentSize and obtains the width of the string that would need the biggest area to be rendered. Once you have the result from that calculation, you can set it to the column that will host the values. If you are interested in learning more details on how to use that functionality, head over to our documentation page that describes it: Get Cell Content Size.

Try It and Share Your Feedback

In case you still haven’t tried Telerik Document Processing, use the button below to obtain a trial version and explore all the features and possibilities of the libraries.

Download a Free Trial

If you are already familiar with the package, don’t forget that we are eager to hear your feedback. Feel free to drop us a comment below sharing your thoughts. Or visit our Document Processing Libraries Feedback Portal to let us know if you have any suggestions or if you need any particular features.


Tanya-Dimitrova
About the Author

Tanya Dimitrova

Tanya Dimitrova is a Tech Support Engineer in the Telerik XAML Team. In her work her main responsibility is to assist clients to implement different scenarios using the document processing libraries and editors. She is passionate in finding new adventures and in her free time enjoys travelling, reading, swimming, dancing or just spending time with friends.

Related Posts

Comments

Comments are disabled in preview mode.