|
| 1 | +--- |
| 2 | +title: Open and save Word document in Azure Functions Flex Consumption | Syncfusion |
| 3 | +description: Open and save Word document in Azure Functions Flex Consumption using .NET Core Word (DocIO) library without Microsoft Word or interop dependencies. |
| 4 | +platform: document-processing |
| 5 | +control: DocIO |
| 6 | +documentation: UG |
| 7 | +--- |
| 8 | + |
| 9 | +# Open and save Word document in Azure Functions (Flex Consumption) |
| 10 | + |
| 11 | +Syncfusion<sup>®</sup> DocIO is a [.NET Core Word library](https://www.syncfusion.com/document-processing/word-framework/net/word-library) used to create, read, edit, and convert Word documents programmatically without **Microsoft Word** or interop dependencies. Using this library, you can **Open and save Word document in Azure Functions deployed on Flex (Consumption) plan**. |
| 12 | + |
| 13 | +## Steps to Open and save Word document in Azure Functions (Flex Consumption) |
| 14 | + |
| 15 | +Step 1: Create a new Azure Functions project. |
| 16 | + |
| 17 | + |
| 18 | +Step 2: Create a project name and select the location. |
| 19 | + |
| 20 | + |
| 21 | +Step 3: Select function worker as **.NET 8.0 (Long Term Support)** (isolated worker) and target Flex/Consumption hosting suitable for isolated worker. |
| 22 | + |
| 23 | + |
| 24 | +Step 4: Install the [Syncfusion.DocIO.Net.Core](https://www.nuget.org/packages/Syncfusion.DocIO.Net.Core) NuGet package as a reference to your project from [NuGet.org](https://www.nuget.org/). |
| 25 | + |
| 26 | + |
| 27 | +N> Starting with v16.2.0.x, if you reference Syncfusion<sup>®</sup> assemblies from trial setup or from the NuGet feed, you also have to add "Syncfusion.Licensing" assembly reference and include a license key in your projects. Please refer to this [link](https://help.syncfusion.com/common/essential-studio/licensing/overview) to know about registering Syncfusion<sup>®</sup> license key in your application to use our components. |
| 28 | + |
| 29 | +Step 5: Include the following namespaces in the **Function1.cs** file. |
| 30 | + |
| 31 | +{% tabs %} |
| 32 | + |
| 33 | +{% highlight c# tabtitle="C#" %} |
| 34 | +using Syncfusion.DocIO; |
| 35 | +using Syncfusion.DocIO.DLS; |
| 36 | + |
| 37 | +{% endhighlight %} |
| 38 | + |
| 39 | +{% endtabs %} |
| 40 | + |
| 41 | +Step 6: Add the following code snippet in **Run** method of **Function1** class to perform **Open and save Word document** in Azure Functions and return the resultant **Word document** to client end. |
| 42 | + |
| 43 | +{% tabs %} |
| 44 | +{% highlight c# tabtitle="C#" %} |
| 45 | + |
| 46 | +public async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Function, "post")] HttpRequest req) |
| 47 | + { |
| 48 | + try |
| 49 | + { |
| 50 | + // Create a memory stream to hold the incoming request body (Word document bytes) |
| 51 | + await using MemoryStream inputStream = new MemoryStream(); |
| 52 | + // Copy the request body into the memory stream |
| 53 | + await req.Body.CopyToAsync(inputStream); |
| 54 | + // Check if the stream is empty (no file content received) |
| 55 | + if (inputStream.Length == 0) |
| 56 | + return new BadRequestObjectResult("No file content received in request body."); |
| 57 | + // Reset stream position to the beginning for reading |
| 58 | + inputStream.Position = 0; |
| 59 | + // Load the Word document from the stream (auto-detects format type) |
| 60 | + using WordDocument document = new WordDocument(inputStream, Syncfusion.DocIO.FormatType.Automatic); |
| 61 | + //Access the section in a Word document. |
| 62 | + IWSection section = document.Sections[0]; |
| 63 | + //Add a new paragraph to the section. |
| 64 | + IWParagraph paragraph = section.AddParagraph(); |
| 65 | + paragraph.ParagraphFormat.FirstLineIndent = 36; |
| 66 | + paragraph.BreakCharacterFormat.FontSize = 12f; |
| 67 | + IWTextRange text = paragraph.AppendText("In 2000, Adventure Works Cycles bought a small manufacturing plant, Importadores Neptuno, located in Mexico. Importadores Neptuno manufactures several critical subcomponents for the Adventure Works Cycles product line. These subcomponents are shipped to the Bothell location for final product assembly. In 2001, Importadores Neptuno, became the sole manufacturer and distributor of the touring bicycle product group."); |
| 68 | + text.CharacterFormat.FontSize = 12f; |
| 69 | + MemoryStream memoryStream = new MemoryStream(); |
| 70 | + //Saves the Word document file. |
| 71 | + document.Save(memoryStream, FormatType.Docx); |
| 72 | + memoryStream.Position = 0; |
| 73 | + var bytes = memoryStream.ToArray(); |
| 74 | + return new FileContentResult(bytes, "application/vnd.openxmlformats-officedocument.wordprocessingml.document") |
| 75 | + { |
| 76 | + FileDownloadName = "document.docx" |
| 77 | + }; |
| 78 | + } |
| 79 | + catch (Exception ex) |
| 80 | + { |
| 81 | + // Log the error with details for troubleshooting |
| 82 | + _logger.LogError(ex, "Error Open and Save document."); |
| 83 | + // Prepare error message including exception details |
| 84 | + var msg = $"Exception: {ex.Message}\n\n{ex}"; |
| 85 | + // Return a 500 Internal Server Error response with the message |
| 86 | + return new ContentResult { StatusCode = 500, Content = msg, ContentType = "text/plain; charset=utf-8" }; |
| 87 | + } |
| 88 | + } |
| 89 | + |
| 90 | +{% endhighlight %} |
| 91 | +{% endtabs %} |
| 92 | + |
| 93 | +Step 7: Right click the project and select **Publish**. Then, create a new profile in the Publish Window. |
| 94 | + |
| 95 | + |
| 96 | +Step 8: Select the target as **Azure** and click **Next** button. |
| 97 | + |
| 98 | + |
| 99 | +Step 9: Select the specific target as **Azure Function App** and click **Next** button. |
| 100 | + |
| 101 | + |
| 102 | +Step 10: Select the **Create new** button. |
| 103 | + |
| 104 | + |
| 105 | +Step 11: Click **Create** button. |
| 106 | + |
| 107 | + |
| 108 | +Step 12: After creating app service then click **Finish** button. |
| 109 | + |
| 110 | + |
| 111 | +Step 13: Click the **Publish** button. |
| 112 | + |
| 113 | + |
| 114 | +Step 14: Publish has been succeed. |
| 115 | + |
| 116 | + |
| 117 | +Step 15: Now, go to Azure portal and select the App Services. After running the service, click **Get function URL by copying it**. Then, paste it in the below client sample (which will request the Azure Functions, to perform **Open and save a Word document** using the template Word document). You will get the output Word document as follows. |
| 118 | + |
| 119 | + |
| 120 | + |
| 121 | +## Steps to post the request to Azure Functions |
| 122 | + |
| 123 | +Step 1: Create a console application to request the Azure Functions API. |
| 124 | + |
| 125 | +Step 2: Add the following code snippet into Main method to post the request to Azure Functions with template Word document and get the resultant Word document. |
| 126 | + |
| 127 | +{% tabs %} |
| 128 | +{% highlight c# tabtitle="C#" %} |
| 129 | +static async Task Main() |
| 130 | + { |
| 131 | + try |
| 132 | + { |
| 133 | + Console.Write("Please enter your Azure Functions URL : "); |
| 134 | + string url = Console.ReadLine(); |
| 135 | + if (string.IsNullOrEmpty(url)) return; |
| 136 | + // Create a new HttpClient instance for sending HTTP requests |
| 137 | + using var http = new HttpClient(); |
| 138 | + // Read all bytes from the input Word document |
| 139 | + byte[] bytes = await File.ReadAllBytesAsync(@"Data/Input.docx"); |
| 140 | + // Wrap the file bytes into a ByteArrayContent object for HTTP transmission |
| 141 | + using var content = new ByteArrayContent(bytes); |
| 142 | + // Set the content type header to indicate binary data |
| 143 | + content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream"); |
| 144 | + // Send a POST request to the provided Azure Functions URL with the file content |
| 145 | + using var res = await http.PostAsync(url, content); |
| 146 | + // Read the response body as a byte array |
| 147 | + var resBytes = await res.Content.ReadAsByteArrayAsync(); |
| 148 | + // Extract the media type from the response headers |
| 149 | + string mediaType = res.Content.Headers.ContentType?.MediaType ?? string.Empty; |
| 150 | + // Decide the output file path the response is an image or txt |
| 151 | + string outputPath = mediaType.Contains("word", StringComparison.OrdinalIgnoreCase) |
| 152 | + || mediaType.Contains("officedocument", StringComparison.OrdinalIgnoreCase) |
| 153 | + || mediaType.Equals("application/vnd.openxmlformats-officedocument.wordprocessingml.document", StringComparison.OrdinalIgnoreCase) |
| 154 | + ? Path.GetFullPath(@"../../../Output/Output.docx") |
| 155 | + : Path.GetFullPath(@"../../../function-error.txt"); |
| 156 | + // Write the response bytes to the output file |
| 157 | + await File.WriteAllBytesAsync(outputPath, resBytes); |
| 158 | + Console.WriteLine($"Saved: {outputPath}"); |
| 159 | + } |
| 160 | + catch (Exception ex) |
| 161 | + { |
| 162 | + throw; |
| 163 | + } |
| 164 | + } |
| 165 | +{% endhighlight %} |
| 166 | +{% endtabs %} |
| 167 | + |
| 168 | +From GitHub, you can download the [console application](https://github.com/SyncfusionExamples/DocIO-Examples/tree/main/Read-and-Save-document/Open-and-save-Word-document/Azure/Azure_Functions/Console_App_Flex_Consumption) and [Azure Functions Flex Consumption](https://github.com/SyncfusionExamples/DocIO-Examples/tree/main/Read-and-Save-document/Open-and-save-Word-document/Azure/Azure_Functions/Azure_Function_Flex_Consumption). |
| 169 | + |
| 170 | +Click [here](https://www.syncfusion.com/document-processing/word-framework/net-core) to explore the rich set of Syncfusion<sup>®</sup> Word library (DocIO) features. |
| 171 | + |
| 172 | +An online sample link to [create a Word document](https://document.syncfusion.com/demos/word/helloworld#/tailwind) in ASP.NET Core. |
0 commit comments