Sometimes you want to display thumbnail images beside a list of
PDF files on your website. It's possible to create thumbnails
automatically from PDFs using the GhostscriptSharp tool. I'll
show you how to get this to happen automatically in Umbraco.
To have something happen automatically in Umbraco, you can hook
into an event. For my purposes, I used the Media.AfterSave event.
This way any time a pdf document is uploaded or updated in the
media section, I create a thumbnail file based on the first page of
that document and store it on the file server. If you name it
correctly, it will even appear next to your pdf in the Umbraco
media section.
To use the GhostscriptSharp tool, just copy the
GhostscriptSharp.dll and gsdll32.dll files from the
GhostscriptSharp project (which you can download as a zip) into the
bin directory of your Umbraco site. Then add references to both of
those dlls to your UserControls project. Now add your event handler
to your UserControls project, so that it will be compiled into your
UserControls.dll file and copied into your Umbraco site. Umbraco is
smart enough to find any event handlers that implement the correct
interfaces in your compiled code - you don't need to do anything
else. The code for my event handler is shown below.
Please note! This has only been tested in Umbraco 4.9.x and
4.11.x.
I also had to do two other things. Firstly, make sure that the
application pool for your website is set to enable 32-bit
applications (you can find that setting in the Advanced Settings in
IIS7). I also had to remove the System.Data.SQLite.dll from the bin
folder of my Umbraco site when I made the change to the application
pool. I haven't noticed any side-effects.
And so, here is the code for the event handler. Enjoy!
public class CreatePdfThumbnail : IApplicationStartupHandler
{
public CreatePdfThumbnail()
{
Media.AfterSave += CreateThumbnail;
}
private static void CreateThumbnail(Media sender, SaveEventArgs e)
{
if (sender.getProperty("umbracoFile") != null && sender.getProperty("umbracoFile").Value != null &&
!string.IsNullOrEmpty(sender.getProperty("umbracoFile").Value.ToString()))
{
try
{
var fullPath = sender.getProperty("umbracoFile").Value.ToString();
var fileName = Path.GetFileName(fullPath);
var filePath = fullPath.Replace(fileName, "");
var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fullPath);
GhostscriptWrapper.GeneratePageThumb(HttpContext.Current.Server.MapPath( sender.getProperty("umbracoFile").Value.ToString()), HttpContext.Current.Server.MapPath(String.Format("{0}{1}_thumb.jpg", filePath, fileNameWithoutExtension)), 1, 7, 8);
}
catch (Exception ex)
{
// Log error to Elmah - optional ;)
Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
}
}
}
}