Skip to content

Instantly share code, notes, and snippets.

@RyanABailey
Created March 1, 2016 03:37
Show Gist options
  • Select an option

  • Save RyanABailey/9e2730e9f2a0bbe8af67 to your computer and use it in GitHub Desktop.

Select an option

Save RyanABailey/9e2730e9f2a0bbe8af67 to your computer and use it in GitHub Desktop.
Sitecore PDF Indexing
public class IndexPDF : IComputedIndexField
{
/// <inheritdoc />
public string FieldName { get; set; }
/// <inheritdoc />
public string ReturnType { get; set; }
/// <inheritdoc />
public object ComputeFieldValue(IIndexable indexable)
{
Item item = indexable as SitecoreIndexableItem;
if (item != null && item.Paths.IsMediaItem) // Only for media items
{
try
{
if (item.TemplateID == new ID("{0603F166-35B8-469F-8123-E8D87BEDC171}")) // PDF template ID
{
return ParsePDF(item);
}
}
catch (Exception)
{
return null;
}
}
return null; // Return null if nothing to index
}
private string ParsePDF(MediaItem mediaItem)
{
PDDocument doc = null;
string content = string.Empty;
InputStreamWrapper wrapper = null;
if (mediaItem != null)
{
try
{
wrapper = new InputStreamWrapper(mediaItem.GetMediaStream());
doc = PDDocument.load(wrapper);
content = new PDFTextStripper().getText(doc);
}
catch (Exception ex)
{
return null;
}
finally
{
if ((doc != null) && (wrapper != null))
{
doc.close();
wrapper.close();
}
}
}
if (!string.IsNullOrEmpty(content))
{
// Replace all whitespace with single space
content = Regex.Replace(content, @"\s+", " ");
}
return content;
}
}
<fields hint="raw:AddComputedIndexField">
<field fieldName="_content" storageType="no" indexType="tokenized"
patch:after="field[last()]">Myproject.IndexPDF, MyProject</field>
</fields>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment