Compartir a través de


So wish GDI+ in .NET had a way to write EPS files.

Yay, a technical post. It's been a while since I wrote one of those. Been working on EasyBarcode 2.0 and working on the export functionality. One important part of generating barcodes is the ability to export to vector based files so the barcodes can be exported at the best possible resolution. I am writing my code using C# and GDI+. You can export to EMF/WMF files using GDI+ but there is a twist. If you use the Image.Save functionality specifying a vector format, you'll still get a PNG raster output. But however, if you create your Metafile using a stream, once the Metafile item is disposed, the GDI+ engine will write back the EMF file content to the stream. Here is the main function I use to write EMF files.

public Metafile CreateIndependentEMF(Stream outputStream)

{

Graphics emfGrfx = null;

try

{

emfGrfx =

this.CreateGraphics();

}

catch (System.Exception e)

{

return null;

}

emfGrfx.PageUnit =

GraphicsUnit.Point;

emfGrfx.PageScale = 1;

//Create and retrieve a handle to the device context

IntPtr ipHdc = emfGrfx.GetHdc();

//Create a new empty metafile from the memory stream

Metafile MetafileToDisplay = new Metafile(outputStream, ipHdc, EmfType.EmfOnly);

//Now that we have a loaded metafile, we get rid of that Graphics object

emfGrfx.ReleaseHdc(ipHdc);

emfGrfx.Dispose();

//Reload the graphics object with the newly created metafile.

emfGrfx =

Graphics.FromImage(MetafileToDisplay);

emfGrfx.PageUnit =

GraphicsUnit.Point;

emfGrfx.PageScale = 1;

if (this.BackColor != Color.Transparent)

emfGrfx.Clear(

this.BackColor);

PrintCanvas(emfGrfx);

//Get rid of the graphics object that we created

emfGrfx.Dispose();

//Set the Picture property of the control to the metafile

return MetafileToDisplay;

}

//End CreateIndetEMF()

This part, although convoluted, works great... What is more difficult, is generating a more platform neutral vector format such as an EPS file. Of course, there is no built-in support within .NET and GDI+. And I have yet to find a .NET compatible library that is either free (or reasinably priced) or that doesn't involve some convoluted use of Ghostscript or a PostScript printer driver.

Call me lazy, but I sure don't want to go through the 900 page PostScript language specification to generate my own EPS files. Any suggestions?

Comments