Skip to content

Instantly share code, notes, and snippets.

@PaulStovell
Created March 18, 2011 10:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PaulStovell/875896 to your computer and use it in GitHub Desktop.
Save PaulStovell/875896 to your computer and use it in GitHub Desktop.
public static class ComCleanupExtensions
{
public static ComProxy<TResource> WithComCleanup<TResource>(this TResource resource)
where TResource : class
{
return new ComProxy<TResource>(resource);
}
}
public class ComProxy<TResource> : IDisposable where TResource : class
{
private readonly TResource target;
public ComProxy(TResource target)
{
this.target = target;
}
public TResource Resource
{
get { return target; }
}
public void Dispose()
{
if (target != null && Marshal.IsComObject(target))
{
Marshal.ReleaseComObject(target);
}
}
}
public void Convert(string sourcePath, string resultPath)
{
object sourcePathRef = sourcePath;
using (var application = new Application().WithComCleanup())
using (var documents = application.Resource.Documents.WithComCleanup())
using (var document = documents.Resource.Open(ref sourcePathRef).WithComCleanup())
{
document.Resource.ExportAsFixedFormat(
resultPath,
WdExportFormat.wdExportFormatPDF,
From: 0,
To: 0,
IncludeDocProps: false,
CreateBookmarks: WdExportCreateBookmarks.wdExportCreateWordBookmarks);
application.Resource.Quit(SaveChanges:false);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment