.NET XPS 轉換器

.NET XPS 轉換器簡介

.NET XPS 轉換器是一個強大的庫,它允許開發人員將 XPS(XML Paper Specification)文件轉換為各種圖像格式,包括 PNG、JPEG、TIFF 等。這個指南將帶您了解庫的可用功能,並提供代碼範例來幫助您開始使用。

將 XPS 轉換為 PDF

將 XPS 文件轉換成 PDF 是一個簡單的過程,涉及加載 XPS 文件和指定輸出格式。以下代碼範例展示了如何將 XPS 文件轉換為 PDF 文檔:

XpsConverter converter = new XpsConverter();
XpsConverterToPdfOptions opt = new XpsConverterToPdfOptions();
opt.AddDataSource(new FileDataSource("input.xps"));
opt.AddSaveDataSource(new FileDataSource("output.pdf"));
converter.Process(opt);

在這個範例中,我們從流加載 XPS 文件,並創建一個新的 XpsConverter 對象。然後,我們指定輸出格式為 PDF,並將文檔保存到新流。

將 XPS 轉換為圖像

將 XPS 文件轉換成圖像是簡單的過程,涉及加載 XPS 文件和指定輸出格式。以下代碼範例展示了如何將 XPS 文件轉換為 PNG 圖像:

XpsConverter converter = new XpsConverter();
PsConverterToImageOptions opt = new PsConverterToImageOptions();
opt.AddDataSource(new FileDataSource("input.xps"));
opt.AddSaveDataSource(new FileDataSource("output.png"));
converter.Process(opt);

在這個範例中,我們從流加載 XPS 文件,並創建一個新的 XpsConverter 對象。然後,我們指定輸出格式為 PNG,並將文檔保存到新流。

支持的輸出格式

.NET XPS 轉換器支持多種輸出格式,包括:

  • PNG(便攜式網絡圖形)
  • JPEG(聯合照片專家小組)
  • TIFF(標記圖像文件格式)
  • BMP(位元圖)
  • GIF(圖形交換格式)

處理錯誤和異常

.NET XPS 轉換器在轉換過程中發生錯誤時拋出異常。您可以使用 try-catch 塊來處理這些異常。

try
{
    XpsConverter converter = new XpsConverter();
    XpsConverterToPdfOptions opt = new XpsConverterToPdfOptions();
    opt.AddDataSource(new FileDataSource("input.xps"));
    opt.AddSaveDataSource(new FileDataSource("output.pdf"));
    converter.Process(opt);
}
catch (NotSupportedException ex)
{
    Console.WriteLine($"錯誤轉換文件:{ex.Message}");
}

注意 NotSupportedException 類別提供了有關錯誤的額外資訊,例如錯誤代碼和消息。

 中文