TX Text Control .NET for Windows Forms

Images

Topic

Logos, photos, scanned signatures and diagrams become part of a document as images. Users of a Windows Forms TextControl insert them from the ribbon, drag them into place, resize them with the mouse and choose how the text flows around them; your code inserts images from files, anchors them to paragraphs, reacts when the user clicks them and opens the built-in dialog box.

The examples are methods of Form1.cs in the application of Create Your First Windows Forms Application, with a TextControl named textControl1. Call them from the Click handler of a button, and copy an image named logo.png into the output folder of the project. Inserting and extracting images without a user interface, with ServerTextControl, is covered in Images, Text Frames, and Shapes.

How Images Are Placed

An Image is one of the frames of a document, together with text frames, charts, barcodes and drawings, and shares their base class FrameBase with its name, ID, size, location and text distances. TextControl.Images returns the ImageCollection of the text part with the input focus: the main text, or the header, footer or text frame the user is editing.

Class diagram of the image classes: TextControl, WPF.TextControl and ServerTextControl with their Images property and image events, ImageCollection with its Add, GetItem and Remove methods, and the Image class with its properties.

An image is placed inline, like a single character of the text, anchored to a paragraph, with which it moves, or at a fixed position on a page. How Frames Are Placed describes the three placements, the Add overload of each and the text flow values for all kinds of frames. When the user drags an anchored image, its anchor moves to the paragraph nearest to its new top-left corner. Locations and sizes are measured in twips, 1/1440 inch.

Insert and Arrange Images in the Ribbon

On the Insert tab, Image in the Illustrations group inserts an image at the input position. Its Image... item opens a file dialog box with the image formats TX Text Control reads; Image Placeholder is for templates, as Images and Barcodes in Mail Merge describes.

The Insert tab of the ribbon with the groups Pages, Tables and Illustrations, where the mouse points at the Image button next to Chart, Shape and Barcode.

A click on an image selects it and shows its sizing handles. Users drag the image to move it and drag a handle to resize it. The Frame Formatting tab, a RibbonFrameLayoutTab, changes the selected image:

  • Arrange: Wrap Text sets the text flow with In Line with Text, Top and Bottom, Square, In Front of Text and Behind Text, and More Layout Options... opens the dialog box. Bring to Front and Send to Back change the order of overlapping objects, and Position aligns the image.
  • Size: Height and Width.
  • Properties: the Name, ID and Descriptive Text of the image.

TX Text Control Words with a selected logo in the header of an invoice and the Frame Formatting tab of the Frame Tools group, with the groups Arrange, Size and Properties.

TX Text Control Words shows this tab in a contextual Frame Tools group while a frame is selected, which Built-in Ribbon Tabs describes. The same tab formats text frames, drawings and barcodes, with a group of its own for each kind.

Insert an Image From Code

The following methods open the file dialog box and insert a logo from a file, anchored at the right edge of the paragraph with the input position:

using System;
using System.Windows.Forms;
using TXTextControl;

public partial class Form1 : Form
{
    private void InsertImageWithDialog()
    {
        // Opens a file dialog box and inserts the image inline at the input position
        textControl1.Images.Add();
    }

    private void InsertLogo()
    {
        // 4 is the import filter for PNG
        TXTextControl.Image logo = new TXTextControl.Image("logo.png", 4);

        // Anchored to the paragraph at the input position, the text flows around it
        textControl1.Images.Add(logo, TXTextControl.HorizontalAlignment.Right, -1,
            ImageInsertionMode.DisplaceText);

        logo.Name = "logo";
        logo.DescriptiveText = "Company logo";
    }
}

The code works as follows:

  • ImageCollection.Add without parameters opens a file dialog box and inserts the chosen image inline at the input position. Every other overload opens the dialog box as well when the Image has neither a file name nor a filter index.
  • The Image constructor takes the file name and the number of the import filter; 4 is PNG. Other constructors take a System.Drawing.Image or a MemoryStream.
  • Add(image, alignment, textPosition, insertionMode) anchors the image to the paragraph that contains the text position; -1 is the input position. The alignment is Left, Right or Center, and ImageInsertionMode sets the text flow.
  • FrameBase.Name is the name your code finds the image by later, and DescriptiveText its alternative text for screen readers and tagged PDF files.

In a form, the names Image and HorizontalAlignment exist in System.Drawing and System.Windows.Forms as well, so the code writes TXTextControl.Image and TXTextControl.HorizontalAlignment.

The two remaining overloads place an image at a fixed position: Add(image, page, location, insertionMode) relative to the top-left corner of a page, numbered from 1, and Add(image, location, insertionMode) relative to the whole document, including the gaps between the pages.

What the position properties return depends on the placement:

  • FrameBase.Location of an image at a fixed position is relative to the whole document, whichever of the two overloads inserted it. For an anchored image it is relative to the paragraph, whose position and width are given by its left and right indents. It returns zero for an inline image and for an image with a horizontal alignment.
  • FrameBase.Alignment is defined only for images anchored to a paragraph. Inline images and images at a fixed position have no horizontal alignment.

Image Formats

The import filters are numbered in the order of ImageCollection.ImportFilters, a filter string you can assign to the Filter property of an OpenFileDialog of your own. Its FilterIndex then serves as the filter number of the image:

Filter indexFormat
1Windows Bitmap (BMP)
2Tagged Image Format (TIF)
3Windows Metafile (WMF)
4Portable Network Graphics (PNG)
5JPEG (JPG, JPEG)
6Graphics Interchange Format (GIF)
7Windows Enhanced Metafile (EMF)
8Scalable Vector Graphics (SVG)

The blog article Various Ways of Inserting Images into TX Text Control inserts images from memory streams, byte arrays and URLs.

React to the Selected Image

Your code finds the image the user has selected and can open the dialog box for it. The following methods open the dialog box on a double-click and halve the size of the selected image:

using System;
using System.Windows.Forms;
using TXTextControl;

public partial class Form1 : Form
{
    private void ConnectImageEvents()
    {
        textControl1.ImageDoubleClicked += TextControl1_ImageDoubleClicked;
    }

    private void TextControl1_ImageDoubleClicked(object sender, ImageEventArgs e)
    {
        // A double-click selects the image, so the dialog box opens for it
        textControl1.ImageAttributesDialog();
    }

    private void HalveSelectedImage()
    {
        // The image the user has selected, or null
        TXTextControl.Image image = textControl1.Images.GetItem();

        if (image != null)
        {
            // Scaling factors in percent
            image.HorizontalScaling = 50;
            image.VerticalScaling = 50;
        }
    }
}

The code works as follows:

  • ImageDoubleClicked passes an ImageEventArgs whose Image is the image. Call ConnectImageEvents once, for example in the constructor of the form.
  • ImageAttributesDialog opens the dialog box of the selected image, with tabs for text wrapping and layout, size and distances, and saving options. It's shown only when an image is selected.
  • ImageCollection.GetItem without a parameter returns the selected image, or null. With a name or an ID, it returns that image.
  • HorizontalScaling and VerticalScaling scale the image in percent. The size of an image, FrameBase.Size, can only be read.

Other events report what users do with images: ImageClicked, ImageMoved, ImageSized and ImageDeleted. ImageCreated occurs for images that are pasted or loaded with a document, but not for images your code adds. For all kinds of frames at once, TextControl.Frames and the FrameSelected event report the selected image, text frame, chart, barcode or drawing. Events lists them all.

Control How Images Are Saved

An image inserted from a file is saved as a reference to that file, with its absolute path, while pasted images are saved with their data in their original format. When a document is opened on another computer, a file reference may point nowhere, and the image is shown as a rectangle with its file name. To keep the images in the document, save them as data:

Users set the same options on the saving tab of the image dialog box. Loading and Saving Documents describes SaveSettings and LoadSettings.

Image Formats of Each Document Format

Each document format stores only some image formats. When an image's format, or the export format you set, isn't one of them, the image is saved in the default format of the document format, the first in its row:

Document formatImage formats, default first
RTFPNG, BMP, WMF, JPG, EMF
DOCWMF, BMP, PNG, JPG, EMF, TIF
DOCXPNG, BMP, WMF, JPG, EMF, TIF, GIF, SVG
HTMLPNG, BMP, JPG, GIF
PDFBMP, JPG; the vector formats EMF, WMF and SVG are converted to PostScript
TX Text Control formatWMF, BMP, PNG, JPG, EMF, TIF, GIF, SVG

Where Image Files Are Saved

When images are saved as file references, for example in an HTML document, TX Text Control writes the image files by these rules:

  1. Folder. SaveSettings.ImageSavePath sets the folder, which is created if it doesn't exist. Without it, the files go into a subfolder next to the document, named after the document with _Images appended: for C:\temp\sample.rtf, that is C:\temp\sample_Images\.
  2. File name. Image.ExportFileName sets the name of an image's file; users set it in the image dialog box.
  3. Without an export file name, the original file name is used, with the extension of the export format.
  4. Without any file name, the name of the document followed by a number is used, such as sample_1.bmp and sample_2.bmp for images exported as BMP.

Next Steps