Skip to content

Instantly share code, notes, and snippets.

@sebastiandammark
Created April 28, 2016 08:32
Show Gist options
  • Save sebastiandammark/bc65f42730a13a9016170143c8875a8d to your computer and use it in GitHub Desktop.
Save sebastiandammark/bc65f42730a13a9016170143c8875a8d to your computer and use it in GitHub Desktop.
using System;
using System.Web;
using System.IO;
using Umbraco.Core;
using Umbraco.Core.Events;
using Umbraco.Core.Models;
using Umbraco.Core.Services;
using GhostscriptSharp;
using Umbraco.Core.Logging;
namespace Designit.Events {
public class PDFThumbnailHandler : ApplicationEventHandler {
public PDFThumbnailHandler(){
}
protected override void ApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext) {
LogHelper.Info(this.GetType(), string.Format("Initialized"));
MediaService.Saved += MediaServiceSaved;
}
private void MediaServiceSaved(IMediaService sender, SaveEventArgs<IMedia> e) {
LogHelper.Info(this.GetType(), string.Format("Saved"));
try {
foreach (var mediaItem in e.SavedEntities) {
if (mediaItem.GetValue("umbracoExtension").ToString().ToLower() == "pdf") {
string subPath = String.Format("/{0}/{1}", "pdf-thumbnails", mediaItem.Id);
bool exists = System.IO.Directory.Exists(HttpContext.Current.Server.MapPath(subPath));
if(!exists)
System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath(subPath));
var fullPath = mediaItem.GetValue("umbracoFile").ToString();
LogHelper.Info(this.GetType(), string.Format(fullPath));
var fileName = Path.GetFileName(fullPath);
var filePath = fullPath.Replace(fileName, "");
var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fullPath);
// Generate a thumbnail JPG @ 72dpi (~ 612px x 792px)
GhostscriptWrapper.GeneratePageThumb(HttpContext.Current.Server.MapPath(fullPath), HttpContext.Current.Server.MapPath(String.Format("/{0}/{1}/{2}_thumb.jpg", "pdf-thumbnails", mediaItem.Id, fileNameWithoutExtension)), 1, 72, 72);
LogHelper.Info(this.GetType(), String.Format("/{0}/{1}/{2}_thumb.jpg", "pdf-thumbnails", mediaItem.Id, fileNameWithoutExtension));
}
}
} catch (Exception ex) {
//LogHelper.Info(this.GetType(), string.Format(ex.Message));
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment