Results for tag "converter"

Office-Dokument in PDF/XPS umwandeln

Vielleicht hat ja jemand von euch meinen damaligen Blog gelesen. Wie ich dort geschrieben habe, ist die Generierung von PNG-Grafiken aus/für ein(em) Office-Dokument eine recht unpraktikable Geschichte. Alleine schon wg. der Limitierungen, die das PNG-Format mt sich bringt.

Es fiel daher die Entscheidung die Office-Dokumente (Word, Excel, Powerpoint) lediglich in XPS/PDF umwandeln. Um möglichst nahe am Microsoft Office zu bleiben, wurde entschieden die Interop-Assemblies (welche eine Office-Installation am Server vorraussetzen!!) zu verwenden. Diese bieten die Möglichkeit die Dokumente zu öffnen und als PDF/XPS abzuspeichern.

Nachfolgend mein Code dafür.

[sourcecode language=“csharp“]
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using Microsoft.Office.Interop.PowerPoint;
using Microsoft.Office.Interop.Word;
using Excel = Microsoft.Office.Interop.Excel;
using PowerPoint = Microsoft.Office.Interop.PowerPoint;
using Word = Microsoft.Office.Interop.Word;

namespace euernamespace
{
public class OfficeToXpsPdf
{
#region Properties & Constants

public static readonly ExtensionList WordExtensions = GetAllowedExtensions("Word");
public static readonly ExtensionList ExcelExtensions = GetAllowedExtensions("Excel");
public static readonly ExtensionList PowerpointExtensions = GetAllowedExtensions("Powerpoint");

public class ExtensionList : List<string>
{
public new bool Contains(string item)
{
bool rv = false;
rv = base.Contains(item);

if(!rv && item.Contains("."))
{
item = item.Replace(".", "").Trim();
rv = base.Contains(item);
}
return rv;
}
}

/// <summary>
/// Gets the allowed extensions.
/// </summary>
/// <param name="application">The application.</param>
/// <returns></returns>
public static ExtensionList GetAllowedExtensions(string application)
{
string configKey = "AllowedExtensions" + application;
string value = ConfigurationManager.AppSettings[configKey];
var list = new ExtensionList();

if (string.IsNullOrEmpty(value))
throw utils.Helper.PrepareException(new ConfigurationErrorsException("Setting ‚" + configKey + "‘ ist in der Config nicht gepflegt!"));

list.AddRange(value.Split(‚|‘).Where(extension => extension.Length > 1));
return list;
}

#endregion

#region enumerations
/// <summary>
/// Specifies all possible convert modes (xps & pdf)
/// </summary>
public enum OfficeConvertModes
{
Xps,
Pdf,
Unknown
}
#endregion

#region Public Methods
public static OfficeToXpsPdfConversionResult ConvertToXpsPdf(string sourceFilePath, OfficeConvertModes mode, ref string resultFilePath)
{
var result = new OfficeToXpsPdfConversionResult(ConversionResult.UnexpectedError);

// Check to see if it’s a valid file
if (!IsValidFilePath(sourceFilePath))
{
result.Result = ConversionResult.InvalidFilePath;
result.ResultText = sourceFilePath;
return result;
}

var ext = Path.GetExtension(sourceFilePath).ToLower();

// Check to see if it’s in our list of convertable extensions
if (!IsConvertableFilePath(sourceFilePath))
{
result.Result = ConversionResult.InvalidFileExtension;
result.ResultText = ext;
return result;
}

// Convert if Word
if (WordExtensions.Contains(ext))
{
return ConvertFromWord(sourceFilePath, mode, ref resultFilePath);
}

// Convert if Excel
if (ExcelExtensions.Contains(ext))
{
return ConvertFromExcel(sourceFilePath, mode, ref resultFilePath);
}

// Convert if PowerPoint
if (PowerpointExtensions.Contains(ext))
{
return ConvertFromPowerPoint(sourceFilePath, mode, ref resultFilePath);
}

return result;
}
#endregion

#region Private Methods
/// <summary>
/// Determines whether [is valid file path] [the specified source file path].
/// </summary>
/// <param name="sourceFilePath">The source file path.</param>
/// <returns>
/// <c>true</c> if [is valid file path] [the specified source file path]; otherwise, <c>false</c>.
/// </returns>
public static bool IsValidFilePath(string sourceFilePath)
{
if (string.IsNullOrEmpty(sourceFilePath))
return false;

try
{
return File.Exists(sourceFilePath);
}
catch (Exception)
{
}

return false;
}

/// <summary>
/// Determines whether [is convertable file path] [the specified source file path].
/// </summary>
/// <param name="sourceFilePath">The source file path.</param>
/// <returns>
/// <c>true</c> if [is convertable file path] [the specified source file path]; otherwise, <c>false</c>.
/// </returns>
public static bool IsConvertableFilePath(string sourceFilePath)
{
var ext = Path.GetExtension(sourceFilePath).ToLower();

return IsConvertableExtension(ext);
}

/// <summary>
/// Determines whether [is convertable extension] [the specified extension].
/// </summary>
/// <param name="extension">The extension.</param>
/// <returns>
/// <c>true</c> if [is convertable extension] [the specified extension]; otherwise, <c>false</c>.
/// </returns>
public static bool IsConvertableExtension(string extension)
{
return WordExtensions.Contains(extension) ||
ExcelExtensions.Contains(extension) ||
PowerpointExtensions.Contains(extension);
}

/// <summary>
/// Gets the temp XPS file path.
/// </summary>
/// <returns></returns>
private static string GetTempXpsFilePath()
{
return Path.ChangeExtension(Path.GetTempFileName(), ".xps");
}

/// <summary>
/// Converts from word.
/// </summary>
/// <param name="sourceFilePath">The source file path.</param>
/// <param name="mode">The mode.</param>
/// <param name="resultFilePath">The result file path.</param>
/// <returns></returns>
private static OfficeToXpsPdfConversionResult ConvertFromWord(string sourceFilePath, OfficeConvertModes mode, ref string resultFilePath)
{
object pSourceDocPath = sourceFilePath;

string pExportFilePath = string.IsNullOrWhiteSpace(resultFilePath) ? GetTempXpsFilePath() : resultFilePath;

try
{

WdExportFormat pExportFormat = Word.WdExportFormat.wdExportFormatXPS;
if (mode == OfficeConvertModes.Pdf)
pExportFormat = WdExportFormat.wdExportFormatPDF;

const bool pOpenAfterExport = false;
const WdExportOptimizeFor pExportOptimizeFor = Word.WdExportOptimizeFor.wdExportOptimizeForOnScreen;
const WdExportRange pExportRange = Word.WdExportRange.wdExportAllDocument;
const int pStartPage = 0;
const int pEndPage = 0;
const WdExportItem pExportItem = Word.WdExportItem.wdExportDocumentContent;
const bool pIncludeDocProps = true;
const bool pKeepIrm = true;
const WdExportCreateBookmarks pCreateBookmarks = Word.WdExportCreateBookmarks.wdExportCreateWordBookmarks;
const bool pDocStructureTags = true;
const bool pBitmapMissingFonts = true;
const bool pUseIso190051 = false;

Word.Application wordApplication = null;
Word.Document wordDocument = null;

try
{
wordApplication = new Word.Application();
}
catch (Exception exc)
{
return new OfficeToXpsPdfConversionResult(ConversionResult.ErrorUnableToInitializeOfficeApp, "Word", exc);
}

try
{
try
{
wordDocument = wordApplication.Documents.Open(ref pSourceDocPath);
}
catch (Exception exc)
{
return new OfficeToXpsPdfConversionResult(ConversionResult.ErrorUnableToOpenOfficeFile, exc.Message, exc);
}

if (wordDocument != null)
{
try
{
wordDocument.ExportAsFixedFormat(
pExportFilePath,
pExportFormat,
pOpenAfterExport,
pExportOptimizeFor,
pExportRange,
pStartPage,
pEndPage,
pExportItem,
pIncludeDocProps,
pKeepIrm,
pCreateBookmarks,
pDocStructureTags,
pBitmapMissingFonts,
pUseIso190051
);
}
catch (Exception exc)
{
return new OfficeToXpsPdfConversionResult(ConversionResult.ErrorUnableToExportToXps, "Word", exc);
}
}
else
{
return new OfficeToXpsPdfConversionResult(ConversionResult.ErrorUnableToOpenOfficeFile);
}
}
finally
{
// Close and release the Document object.
if (wordDocument != null)
{
wordDocument.Close();
wordDocument = null;
}

// Quit Word and release the ApplicationClass object.
if (wordApplication != null)
{
wordApplication.Quit();
wordApplication = null;
}

GC.Collect();
}
}
catch (Exception exc)
{
return new OfficeToXpsPdfConversionResult(ConversionResult.ErrorUnableToAccessOfficeInterop, "Word", exc);
}

resultFilePath = pExportFilePath;

return new OfficeToXpsPdfConversionResult(ConversionResult.Ok, pExportFilePath);
}

/// <summary>
/// Converts from power point.
/// </summary>
/// <param name="sourceFilePath">The source file path.</param>
/// <param name="mode">The mode.</param>
/// <param name="resultFilePath">The result file path.</param>
/// <returns></returns>
private static OfficeToXpsPdfConversionResult ConvertFromPowerPoint(string sourceFilePath, OfficeConvertModes mode, ref string resultFilePath)
{
string pSourceDocPath = sourceFilePath;

string pExportFilePath = string.IsNullOrWhiteSpace(resultFilePath) ? GetTempXpsFilePath() : resultFilePath;

try
{
PowerPoint.Application pptApplication = null;
PowerPoint.Presentation pptPresentation = null;

try
{
pptApplication = new PowerPoint.Application();
}
catch (Exception exc)
{
return new OfficeToXpsPdfConversionResult(ConversionResult.ErrorUnableToInitializeOfficeApp, "PowerPoint", exc);
}

try
{
try
{
pptPresentation = pptApplication.Presentations.Open(pSourceDocPath,
Microsoft.Office.Core.MsoTriState.msoTrue,
Microsoft.Office.Core.MsoTriState.msoTrue,
Microsoft.Office.Core.MsoTriState.msoFalse);
}
catch (Exception exc)
{
return new OfficeToXpsPdfConversionResult(ConversionResult.ErrorUnableToOpenOfficeFile, exc.Message, exc);
}

if (pptPresentation != null)
{
try
{

PpFixedFormatType exportType = PpFixedFormatType.ppFixedFormatTypeXPS;
if (mode == OfficeConvertModes.Pdf)
exportType = PpFixedFormatType.ppFixedFormatTypePDF;

pptPresentation.ExportAsFixedFormat(
pExportFilePath,
exportType,
PowerPoint.PpFixedFormatIntent.ppFixedFormatIntentScreen,
Microsoft.Office.Core.MsoTriState.msoFalse,
PowerPoint.PpPrintHandoutOrder.ppPrintHandoutVerticalFirst,
PowerPoint.PpPrintOutputType.ppPrintOutputSlides,
Microsoft.Office.Core.MsoTriState.msoFalse,
null,
PowerPoint.PpPrintRangeType.ppPrintAll,
string.Empty,
true,
true,
true,
true,
false
);
}
catch (Exception exc)
{
return new OfficeToXpsPdfConversionResult(ConversionResult.ErrorUnableToExportToXps, "PowerPoint", exc);
}
}
else
{
return new OfficeToXpsPdfConversionResult(ConversionResult.ErrorUnableToOpenOfficeFile);
}
}
finally
{
// Close and release the Document object.
if (pptPresentation != null)
{
pptPresentation.Close();
pptPresentation = null;
}

// Quit Word and release the ApplicationClass object.
if (pptApplication != null)
{
pptApplication.Quit();
pptApplication = null;
}

GC.Collect();
}
}
catch (Exception exc)
{
return new OfficeToXpsPdfConversionResult(ConversionResult.ErrorUnableToAccessOfficeInterop, "PowerPoint", exc);
}

resultFilePath = pExportFilePath;

return new OfficeToXpsPdfConversionResult(ConversionResult.Ok, pExportFilePath);
}

/// <summary>
/// Converts from excel.
/// </summary>
/// <param name="sourceFilePath">The source file path.</param>
/// <param name="mode">The mode.</param>
/// <param name="resultFilePath">The result file path.</param>
/// <returns></returns>
private static OfficeToXpsPdfConversionResult ConvertFromExcel(string sourceFilePath, OfficeConvertModes mode, ref string resultFilePath)
{
string pSourceDocPath = sourceFilePath;

string pExportFilePath = string.IsNullOrWhiteSpace(resultFilePath) ? GetTempXpsFilePath() : resultFilePath;

try
{
var pExportFormat = Excel.XlFixedFormatType.xlTypeXPS;
if (mode == OfficeConvertModes.Pdf)
pExportFormat = Excel.XlFixedFormatType.xlTypePDF;

var pExportQuality = Excel.XlFixedFormatQuality.xlQualityStandard;
var pOpenAfterPublish = false;
var pIncludeDocProps = true;
var pIgnorePrintAreas = true;

Excel.Application excelApplication = null;
Excel.Workbook excelWorkbook = null;

try
{
excelApplication = new Excel.Application();
}
catch (Exception exc)
{
return new OfficeToXpsPdfConversionResult(ConversionResult.ErrorUnableToInitializeOfficeApp, "Excel", exc);
}

try
{
try
{
excelWorkbook = excelApplication.Workbooks.Open(pSourceDocPath);
}
catch (Exception exc)
{
return new OfficeToXpsPdfConversionResult(ConversionResult.ErrorUnableToOpenOfficeFile, exc.Message, exc);
}

if (excelWorkbook != null)
{
try
{
excelWorkbook.ExportAsFixedFormat(
pExportFormat,
pExportFilePath,
pExportQuality,
pIncludeDocProps,
pIgnorePrintAreas,

OpenAfterPublish: pOpenAfterPublish
);
}
catch (Exception exc)
{
return new OfficeToXpsPdfConversionResult(ConversionResult.ErrorUnableToExportToXps, "Excel", exc);
}
}
else
{
return new OfficeToXpsPdfConversionResult(ConversionResult.ErrorUnableToOpenOfficeFile);
}
}
finally
{
// Close and release the Document object.
if (excelWorkbook != null)
{
excelWorkbook.Close();
excelWorkbook = null;
}

// Quit Word and release the ApplicationClass object.
if (excelApplication != null)
{
excelApplication.Quit();
excelApplication = null;
}

GC.Collect();
}
}
catch (Exception exc)
{
return new OfficeToXpsPdfConversionResult(ConversionResult.ErrorUnableToAccessOfficeInterop, "Excel", exc);
}

resultFilePath = pExportFilePath;

return new OfficeToXpsPdfConversionResult(ConversionResult.Ok, pExportFilePath);
}
#endregion
}

public enum ConversionResult
{
Ok = 0,
InvalidFilePath = 1,
InvalidFileExtension = 2,
UnexpectedError = 3,
ErrorUnableToInitializeOfficeApp = 4,
ErrorUnableToOpenOfficeFile = 5,
ErrorUnableToAccessOfficeInterop = 6,
ErrorUnableToExportToXps = 7
}
}
[/sourcecode]
OfficeToXpsPdf-Klasse

[sourcecode language=“csharp“]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace euernamespace
{
public class OfficeToXpsPdfConversionResult
{
#region Properties
public ConversionResult Result { get; set; }
public string ResultText { get; set; }
public Exception ResultError { get; set; }
#endregion

#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="OfficeToXpsPdfConversionResult"/> class.
/// </summary>
public OfficeToXpsPdfConversionResult()
{
Result = ConversionResult.UnexpectedError;
ResultText = string.Empty;
}

/// <summary>
/// Initializes a new instance of the <see cref="OfficeToXpsPdfConversionResult"/> class.
/// </summary>
/// <param name="result">The result.</param>
public OfficeToXpsPdfConversionResult(ConversionResult result)
: this()
{
Result = result;
}

/// <summary>
/// Initializes a new instance of the <see cref="OfficeToXpsPdfConversionResult"/> class.
/// </summary>
/// <param name="result">The result.</param>
/// <param name="resultText">The result text.</param>
public OfficeToXpsPdfConversionResult(ConversionResult result, string resultText)
: this(result)
{
ResultText = resultText;
}

/// <summary>
/// Initializes a new instance of the <see cref="OfficeToXpsPdfConversionResult"/> class.
/// </summary>
/// <param name="result">The result.</param>
/// <param name="resultText">The result text.</param>
/// <param name="exc">The exc.</param>
public OfficeToXpsPdfConversionResult(ConversionResult result, string resultText, Exception exc)
: this(result, resultText)
{
ResultError = exc;
}
#endregion
}
}

[/sourcecode]
Result-Klasse

Wie gesagt, vergesst beim Verwenden dieser Klassen nicht, dass Office (in meinem Fall 2010) und die dazugehörigen Primary Interop Assemblies (PIA) installiert sein müssen! Möchtet Ihr die Klassen in einem Webservice/in einer Webapplikation verwenden, so müsst Ihr zudem noch in den Komponentendiensten (comexp.msc) unter Komponentenliste -> Arbeitsplatz -> DCOM-Konfiguration für „Microsoft Excel Application“, „Microsoft PowerPoint-Folie“ und „Microsoft Word 97-2003-Dokument“ folgende Einstellung treffen:

Update:
Im laufenden Betrieb kam es immer wieder zur nachfolgenden Fehlermeldung:
Retrieving the COM class factory for component with CLSID {000209FF-0000-0000-C000-000000000046} failed due to the following error: 8000401a The server process could not be started because the configured identity is incorrect. Check the username and password.

Um das Problem zu beheben, musste ebenfalls in den DCOM-Konfigurations-Dialogen eine Einstellung gesetzt werden. Und zwar:

Was meint Ihr? Würdet Ihr noch etwas an den Klassen (abgesehen von kosmetischen Dingen) ändern?

Cheers,
Chris