This project is read-only.

Office.Automation.Word.Print.To.Pdf


Massive conversion of DOCX to PDF using Office Automation and Task Parallel Library:
void Main()
{
	var stopwatch = Stopwatch.StartNew();
	var folderPath = @"FOLDER_PATH";
	
	PrintToPdfAllDocuments(folderPath, true);
	
	stopwatch.Stop();
	stopwatch.Elapsed.Dump();
}

public void PrintToPdfAllDocuments(string folderPath, bool deleteExistingPdfFile = false)
{
	var files = new DirectoryInfo(folderPath).EnumerateFiles("*.docx", SearchOption.AllDirectories);
	Parallel.ForEach(files, file => ConvertToPdf(file, deleteExistingPdfFile));
}

public void ConvertToPdf(FileInfo file, bool deleteExistingPdfFile)
{
	using (var wordAutomation = new WordAutomation())
	{
		var pdfFile = 
			new FileInfo(Path.Combine(file.DirectoryName, "Pdf", Path.GetFileNameWithoutExtension(file.Name) + ".pdf"));
			
		Console.WriteLine("Printing... {0}", pdfFile.FullName);
		
		if (!pdfFile.Directory.Exists)
		{
			pdfFile.Directory.Create();	
		}
		
		if (pdfFile.Exists)
		{
			if (deleteExistingPdfFile)
			{
				pdfFile.Delete();
			}
		}
	
		wordAutomation.PrintToPdf(file.FullName, pdfFile.FullName);
	}
}

public class WordAutomation
	: IDisposable
{
	private Word.Application word = null;
	
	public void PrintToPdf(string wordDocumentPath, string pdfDocumentPath)
	{
		if (File.Exists(pdfDocumentPath))
		{
			throw new ArgumentException("The PDF document already exists. Delete the file before printing.");
		}		
		
		Word.Document document = null;
		try
		{
			if (word == null)
			{
				word = new Word.Application { Visible = false };
			}

			document = word.Documents.Open(wordDocumentPath, false, true);
			document.ExportAsFixedFormat(pdfDocumentPath, Word.WdExportFormat.wdExportFormatPDF);
			document.Close(false, Missing.Value, Missing.Value);
		}
		catch (Exception ex)
		{
			throw new InvalidOperationException(string.Format("Error on file {0}", wordDocumentPath), ex); 
		}
		finally
		{
			if (document != null)
			{
				Marshal.ReleaseComObject(document);
			}
		}
	}
	
	public void Dispose()
	{
		if (word != null)
		{
			word.Quit(false, Missing.Value, Missing.Value);
			Marshal.ReleaseComObject(word);
		}
	}
}

Last edited May 9, 2012 at 11:01 AM by teoarch, version 3

Comments

spottedmahn Aug 8, 2012 at 6:48 PM 
Sweet, thanks for sharing!

Regards,
Mike DePouw