在 Azure 函數中使用 Aspose.Words 轉換包含圖像的文檔
Aspose.Words是一種高級Word文檔處理API,用于執行各種文檔管理和操作任務。API支持生成,修改,轉換,呈現和打印文檔,而無需在跨平臺應用程序中直接使用Microsoft Word。
Aspose API支持流行文件格式處理,并允許將各類文檔導出或轉換為固定布局文件格式和最常用的圖像/多媒體格式。
在部署到 Azure 時,使用 Azure Functions 中的 Aspose.Words 將包含圖像的文檔轉換為固定頁面格式在部署到 Azure 時無法正常工作,因為圖像未保留。但是,這種轉換在本地計算機上正常工作。此問題背后的原因是 SkiaSharp 原生資產未正確發布。此問題在 Github 中報告給 Azure。
為了解決此問題,您可以在 .csproj 文件中添加以下部分,以便正確復制本機資產:
<Target Name="CopyRequiredNativeAssets" AfterTargets="_FunctionsPostPublish"> <ItemGroup> <NativeAssetToCopy Include="$(PublishDir)runtimes\win-x86\native\libSkiaSharp.dll" /> </ItemGroup> <Copy SourceFiles="@(NativeAssetToCopy)" DestinationFolder="$(PublishDir)bin" /> </Target>
以下示例演示如何在 Azure 函數中使用 Aspose.Words,并詳細介紹如何添加上述代碼。
先決條件
- Active Azure 訂閱。如果您沒有免費帳戶,請在開始之前創建一個免費帳戶。
- Visual Studio 2019 或 Visual Studio 2017 使用最新安裝的 Azure Functions 工具來創建項目。
創建 Azure 函數應用程序
您需要使用 Visual Studio 創建 Azure Functions 應用程序。創建的應用程序已經有一個簡單的“Hello World”函數代碼。
在此示例中,您將創建一個簡單的“Hello World”文檔,并將其作為 PDF 文件返回到用戶的瀏覽器。要實現此目的,請執行以下操作
1、開始使用 Aspose.Words 創建函數,方法是添加對最新版本的 Aspose.Words 的 NuGet 引用。然后修改代碼,如下所示:
using System.IO; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Extensions.Http; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using Aspose.Words; namespace AsposeWordsAzureTestApp { public static class CreateTestDocument { [FunctionName("CreateTestDocument")] public static async Task<IActionResult> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req, ILogger log) { log.LogInformation("C# HTTP trigger function processed a request."); // Create a simple document using DocumentBuilder. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Write some text in the document. builder.Writeln("Hello Aspose.Words!"); // Write OS we are running on. builder.Writeln("You are running on " + System.Environment.OSVersion.VersionString); // Insert some image into the document. builder.InsertImage(@"http://cms.admin.containerize.com/templates/aspose/App_Themes/V3/images/aspose-logo.png"); // Now save the created document to PDF and return as a FileContentResult. using (MemoryStream ms = new MemoryStream()) { doc.Save(ms, SaveFormat.Pdf); return new FileContentResult(ms.ToArray(), "application/pdf") { FileDownloadName = "out.pdf" }; } } } }
2、在Visual Studio中運行代碼以對其進行測試。結果將顯示在控制臺輸出中。
3、將 URL 從控制臺輸出復制到您喜歡的瀏覽器以獲取輸出文檔,該文檔應如下所示:
4、現在,如果將創建的函數部署到 Azure,則由于本文開頭所述的問題,將不會呈現映像。輸出如下所示:
5、在記事本中打開 .csproj 文件,并向其添加以下部分:
<Target Name="CopyRequiredNativeAssets" AfterTargets="_FunctionsPostPublish"> <br> <ItemGroup> <br> <NativeAssetToCopy<br> Include="$(PublishDir)runtimes\win-x86\native\libSkiaSharp.dll" /> <br> </ItemGroup> <br> <Copy SourceFiles="@(NativeAssetToCopy)" <br> DestinationFolder="$(PublishDir)bin" /> <br> </Target>
6、再次發布項目,并驗證圖像現在是否存在于生成的輸出中。