Click here to Skip to main content
5,786,882 members and growing! (22,052 online)
Email Password   helpLost your password?
Web Development » ASP.NET » General     Intermediate

Vertical Text in HTML - Creating dynamic vertical text images in webpages

By MattsterP

Create Cross-Browser Vertical Text in HTML without using IE specific layout-flow or writing-mode
C# 2.0, C#, Windows, .NET, .NET 2.0, GDI+, WebForms, ASP.NET, VS2005, Visual Studio, Dev

Posted: 23 May 2007
Updated: 23 May 2007
Views: 23,094
Bookmarked: 21 times
Note: This is an unedited reader contribution
Announcements
Loading...



Search    
Advanced Search
Sitemap
7 votes for this Article.
Popularity: 3.30 Rating: 3.90 out of 5
1 vote, 14.3%
1
0 votes, 0.0%
2
0 votes, 0.0%
3
2 votes, 28.6%
4
4 votes, 57.1%
5
Note: This is an unedited contribution. If this article is inappropriate, needs attention or copies someone else's work without reference then please Report This Article
Screenshot - vertical_text-firefox_ss.jpg

Introduction

This example code allows you to create rotated vertical text images in an ASP.NET web page using a custom Http Handler and the .NET Graphics libraries - GDI+.

Background

In a recent project I was asked to display a table of data like the one above with rotated vertical text column headings. For a tabular report that may have many columns, vertical text is sometimes the only way a user can view the data. Internet Explorer offers a way to display vertical text using style="writing-mode:tb-rl" but no other browsers support it and I wanted a solution that would work in Firefox and other browsers.

Creating Vertical Text Images

The ImageCreationLibrary.cs file is in charge of creating and saving vertical text images in the format we want using the Microsoft's .NET GDI+ features.

The strategy that worked for me was to use StringFormatFlags.DirectionVertical to draw out the text, the tricky part is that it defaults to write the text reading from top to bottom so you have to rotate the image 180 degrees and translate it appropriately. Most people I think are more comfortable reading vertical text bottom-up because the first letter in each word will be lined up in the same position.

The main code in ImageCreationLibrary.cs is inside the CreateVerticalTextImage method:

public string CreateVerticalTextImage(string stText, Font f)
    {
        string stFileName = Toolbox.GetMD5String(stText);
        string stFullFilePath = this._baseImagePath + stFileName + ".jpg";
        if (!File.Exists(stFullFilePath))
        {
            StringFormat stringFormat = new StringFormat();
            stringFormat.FormatFlags = StringFormatFlags.DirectionVertical;

            SizeF imageSize = _graphics.MeasureString(stText, f, 25, stringFormat);
            System.Drawing.Image i = (Image)new Bitmap((int)imageSize.Width, (int)imageSize.Height);
            Graphics g = Graphics.FromImage(i);
            g.FillRectangle(Brushes.White, 0, 0, i.Width, i.Height);

            //flip the image 180 degrees

            g.TranslateTransform(i.Width, i.Height);
            g.RotateTransform(180.0F);

            g.DrawString(stText, f, Brushes.Black, 0, 0, stringFormat);

            i.Save(stFullFilePath, System.Drawing.Imaging.ImageFormat.Jpeg);
        }
        return stFullFilePath;
    }

CreateVerticalTextImage generates an MD5 hash based on the text passed in; you could do something else, this is just a way to ensure there are no invalid characters in the file path and that the names are somewhat unique. Then it creates a white box large enough to fit the text in. Using the graphics object we then call TranslateTransform to translate our image back to where we want it based on the 180 degree rotation. Then we call RotateTransform, passing 180 degress to actually do the Rotation transformation we want. Finally CreateVerticalTextImage calls DrawString on the graphics object to draw our vertical text, and saves the image.

Using the Code

Well that's all very nice and snazzy, but how do I use this code to actually include a vertical text image in my web page? I've created a custom HttpHandler: ImageViewer.cs, the ImageViewer class extends from IHttpHandler and within the ProcessRequest method calls CreateVerticalTextImage passing it the GET parameter we've called "text".

//get the text passed in

string stText = context.Request.QueryString["text"];
if (stText != null && stText != "")
{
    string stFileName = this.imageLib.CreateVerticalTextImage(stText, new System.Drawing.Font(System.Drawing.FontFamily.GenericSerif, 12));
    this.WriteImageFile(context, stFileName);
}

The WriteImageFile method inside ImageViewer.cs simply sets the content type based on the image file extension and calls Response.WriteFile(stFilePath) on our HttpContext object.

Make sure to register the custom HttpHandler in the Web.Config file so we ensure requests to get_image.aspx get processed by ImageViewer.cs.

<system.web>
    <httphandlers>
        "VerticalTextExample.ImageViewer" path="get_image.aspx" verb="*">
    
    ...
</httphandlers></system.web>

Finally, to include our image in a web page we need to UrlEncode the text we want on our image and pass it in the querystring to get_image.aspx like so:

string stGET = System.Web.HttpUtility.UrlEncode(stText);

string stImageTag = "<img src=\"get_image.aspx?text=" + stGET + "\"/>";

Points of Interest

When working with the GDI+ and matrix transformations you learn (or remember) much from Linear Algebra, it helps to use that F1 key within Visual Studio on methods your using such as TranslateTransform and RotateTransform and read the docs and examples and experiment with it. One thing to keep in mind: According to the docs these methods work by prepending the specified translation or rotation to the transformation matrix, so in my example the rotation is actually done first and then the translation is performed.

References

I was assited by the many great references I found (some from CodeProject) when trying to solve this problem: Many thanks to Horia Tudosie's Vertical Labels in Web Pages article which is very complete and helped me figure out some of the GDI+ code for rendering the text properly, I decided to share my code because I wanted a simple example from a slightly different perspective that also saved the created files so that it only has to generate the images once. Another good vertical text GDI+ article I found on codeproject (VB): Vertical Label Control in VB.NET

History

05/23/2007 - Created Article

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

MattsterP


Matt Palmerlee is a Software Engineer that has been working in the Microsoft.NET environment developing C# WebServices, Windows Applications, Web Applications, and Windows Services since 2003.
Occupation: Web Developer
Location: United States United States

Other popular ASP.NET articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 9 of 9 (Total in Forum: 9) (Refresh)FirstPrevNext
GeneralGood job!memberEtIeNn38:59 30 Dec '08  
QuestionExceptionmembersehajpal2:04 23 Jul '07  
AnswerRe: ExceptionmemberMattsterP7:59 23 Jul '07  
GeneralRe: Exceptionmembersehajpal19:28 23 Jul '07  
GeneralCachingmemberSean Feldman5:00 30 May '07  
GeneralRe: CachingmemberMattsterP9:20 4 Jun '07  
GeneralVery cool...memberDale Lundgren7:58 23 May '07  
GeneralRe: Very cool...member/randz23:51 13 Aug '07  
GeneralHandymemberSteven Berkovitz7:07 23 May '07  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 23 May 2007
Editor:
Copyright 2007 by MattsterP
Everything else Copyright © CodeProject, 1999-2009
Web10 | Advertise on the Code Project