Monday, September 22, 2008

Export GeoMedia Layout Window to PDF Example Code

There is a great open source C# library that you can use to build GeoMedia custom programs to create PDF files. It is called iText# or iTextSharp - a port of the iText open source java library written entirely in C# for the .NET platform. It can be downloaded here.

I have combined this library with GeoMedia's RenderToRasterFileService to export out the Layout Window's active sheet contents as PDF files. Below is a simple example that locates the Layout Window and exports its active sheet to an A0 sized, landscape PDF file via an intermediate PNG raster file. This example will work with a running instance of GeoMedia, which has data loaded in the Layout Window.



GeoMedia.LayoutWindow layoutWnd = null;
RenderToRasterFile.RenderToRasterFileService renderer = null;
GMLayout.Application layoutVw = null;
GMLayout.Sheet sheet = null;

//Get the GeoMedia framework's windows collection
GeoMedia.Windows wnds = (GeoMedia.Windows)this._application.Windows;

//Loop through all the GeoMedia windows to find the layout window
for (int i = 1; i <= wnds.Count; i++)
{
if (wnds.Item(i) is GeoMedia.LayoutWindow)
{
layoutWnd = (GeoMedia.LayoutWindow)wnds.Item(i);
break;
}
}

if (layoutWnd == null)
throw new Exception("Unable to find the Layout Window");

//Get the layout window's active sheet
layoutVw = (GMLayout.Application) layoutWnd.LayoutView;
sheet = layoutVw.ActiveSheet;

//Create the RenderToRasterFile service and set the output raster file properties
renderer = (RenderToRasterFile.RenderToRasterFileService) this._application.CreateService("GeoMedia.RenderToRasterFileService");
renderer.InputDisplay = sheet;
renderer.OutputFileName = @"C:\temp\test.png";
renderer.OutputFileResolution = 300;
renderer.OutputFileType = RenderToRasterFile.FileFormatConstants.gmRenderToRasterFilePNG;

//Render the sheet into a PNG file
renderer.Execute();

if (File.Exists(@"C:\temp\test.png") == false)
throw new Exception("Test.png not created successfully");

iTextSharp.text.Document doc = null;
iTextSharp.text.Image img = null;
iTextSharp.text.Rectangle pageRect = null;

//Define a PDF page as A0 size with landscape orientation
pageRect = PageSize.A0.Rotate();

//Create a new PDF document with A0 sized, landscape pages
doc = new iTextSharp.text.Document(pageRect);
PdfWriter.GetInstance(doc, new FileStream(@"C:\temp\test.pdf", FileMode.Create));
doc.Open();

//Read the PNG raster file
img = Image.GetInstance(@"C:\temp\test.png");

//Adjust the PNG raster file to fit the PDF page
img.Alignment = Image.ALIGN_CENTER;
img.SetAbsolutePosition(0, 0);
img.ScaleToFit(pageRect.Width, pageRect.Height);

//Add the PNG file to the PDF document
doc.Add(img);
doc.Close();

No comments: