Saturday, May 28, 2005

Playing with Text and GDI+ in VB.Net - System.Drawing.Fun

VB Helper: HowTo: Print a long series of paragraphs in different fonts, breaking across pages in VB .NET

"This example shows how to print a long series of paragraphs in different fonts, breaking across pages in VB .NET. It shows measure text to see where it needs to brake across pages, and how to tell VB not to draw partial words or lines."

Oh my... This is fun.

Just recently I started working with creating bitmaps/images and text via GDI+ in VB.Net.

I had to create an image with dynamic length text (which needs to be wrapped) that needs to be in simple table like layout. Different fonts/styles for different parts, etc, etc.

In VB6 I was using the richtext control and then "printing" to tiff/jpg/etc (via third party print driver). While this worked, it has too many moving parts and prerequisites (i.e. the correct Printer driver installed, etc, etc). Since other processes in the app suite used this same image creation approach, it made sense at the time to continue using it.

Moving to VB.Net through the app was going to be used by more people, in different environments and the moving parts issue was just going to get worse. I really didn't want to play that game...

So I decided it was time to rethink the approach. Having read about GDI+ & System.Drawing I figured it was time to play in that space. Of course there's the initial learning curve which is both fun and irritating.

At first I was a little dismayed that I was going to have to do my own text wrapping calculations. I was ready to do this, but wasn't looking forward to it. BUT then I came across the above How To...

With some more work, I had auto wrapping text, in the layout and format I needed. Rock on... Man I love Google and the .Net framework.

Now I needed to take the in memory 24bpp image and save it as a Tiff G4 file... sigh. You know there's no easy way to do this (that I could find at least)? One suggestion was to loop through each pixel in the image and based on the luminosity, set it to Black or White. Right... There's no way in hell I was going to do that.

Luckily I already had a license for Lead14.Net. So with a little more work I had a component where I could feed it some strings and get out B&W Tiff's, JPG's or PDF (we have the PDF Plug in license already too). Having Lead in place ended up being a good thing in that I was able to apply special effects to the image based on the output format (Antialias if going to JPG/PDF, halftone & smooth if going to TIF, etc)

Here are some other posts that helped;
Print Simple Reports With GDI+ (Free Registration Required)
Convert e.Graphics to an image or bitmap


In the end I'm a happy VB.Net guy. Man, I dig programming... :)

No comments: