|
| 1 | +--- |
| 2 | +title: Create Word documents in ASP.NET Core Web API | Syncfusion |
| 3 | +description: Create Word document without Microsoft Word or interop dependencies in ASP.NET Core Web API applications using Syncfusion<sup>®</sup> .NET Word (DocIO) library. |
| 4 | +platform: document-processing |
| 5 | +control: DocIO |
| 6 | +documentation: UG |
| 7 | +--- |
| 8 | + |
| 9 | +# Create a Word document using ASP.NET Core Web API |
| 10 | + |
| 11 | +Syncfusion<sup>®</sup> Essential<sup>®</sup> DocIO is a [.NET Word library](https://www.syncfusion.com/document-processing/word-framework/net/word-library) used to create, read, and edit **Word** documents programmatically without **Microsoft Word** or interop dependencies. Using this library, you can **create a Word document in ASP.NET Core Web API**. |
| 12 | + |
| 13 | +## Steps to create Word document programmatically: |
| 14 | + |
| 15 | +The below steps illustrate creating a simple Word document in ASP.NET Core Web API. |
| 16 | + |
| 17 | +**Prerequisites:** |
| 18 | + |
| 19 | +* Visual Studio 2022. |
| 20 | +* Install **.NET desktop development** workload with necessary .NET Framework SDK. |
| 21 | + |
| 22 | +Step 1: Create a new C# ASP.NET Core Web API project. |
| 23 | + |
| 24 | + |
| 25 | + |
| 26 | +Step 2: Add a name for the project. |
| 27 | + |
| 28 | + |
| 29 | + |
| 30 | +Step 3: 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). |
| 31 | + |
| 32 | + |
| 33 | + |
| 34 | +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. |
| 35 | + |
| 36 | +Step 4: Add a new API controller empty file in the project. |
| 37 | + |
| 38 | + |
| 39 | + |
| 40 | +Step 5: Include the following namespaces in the **ValuesController.cs** file. |
| 41 | + |
| 42 | +{% tabs %} |
| 43 | + |
| 44 | +{% highlight c# tabtitle="C#" %} |
| 45 | + |
| 46 | +using Microsoft.AspNetCore.Mvc; |
| 47 | +using Syncfusion.DocIO; |
| 48 | +using Syncfusion.DocIO.DLS; |
| 49 | + |
| 50 | +{% endhighlight %} |
| 51 | + |
| 52 | +{% endtabs %} |
| 53 | + |
| 54 | +Step 6: Add a new action method CreateDocument in **ValuesController.cs** and include the below code snippet to create an Word file and download it. |
| 55 | + |
| 56 | +{% tabs %} |
| 57 | + |
| 58 | +{% highlight c# tabtitle="C#" %} |
| 59 | + |
| 60 | + [HttpGet] |
| 61 | + [Route("api/Word")] |
| 62 | + public IActionResult CreateDocument() |
| 63 | + { |
| 64 | + try |
| 65 | + { |
| 66 | + var fileDownloadName = $"Output.docx"; |
| 67 | + const string contentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; |
| 68 | + var stream = GenerateWordDocument(); |
| 69 | + stream.Position = 0; |
| 70 | + return File(stream, contentType, fileDownloadName); |
| 71 | + } |
| 72 | + catch (Exception ex) |
| 73 | + { |
| 74 | + // Log or handle the exception |
| 75 | + return BadRequest($"Error occurred while creating Excel file: {ex.Message}"); |
| 76 | + } |
| 77 | + } |
| 78 | + |
| 79 | + {% endhighlight %} |
| 80 | + |
| 81 | +{% endtabs %} |
| 82 | + |
| 83 | +Step 7: Implement the `GenerateWordDocument` method in `ValuesController.cs`. |
| 84 | + |
| 85 | +{% tabs %} |
| 86 | + |
| 87 | +{% highlight c# tabtitle="C#" %} |
| 88 | + |
| 89 | + public static MemoryStream GenerateWordDocument() |
| 90 | + { |
| 91 | + //Creating a new document |
| 92 | + WordDocument document = new WordDocument(); |
| 93 | + //Adding a new section to the document |
| 94 | + WSection section = document.AddSection() as WSection; |
| 95 | + //Set Margin of the section |
| 96 | + section.PageSetup.Margins.All = 72; |
| 97 | + //Set page size of the section |
| 98 | + section.PageSetup.PageSize = new Syncfusion.Drawing.SizeF(612, 792); |
| 99 | + |
| 100 | + //Create Paragraph styles |
| 101 | + WParagraphStyle style = document.AddParagraphStyle("Normal") as WParagraphStyle; |
| 102 | + style.CharacterFormat.FontName = "Calibri"; |
| 103 | + style.CharacterFormat.FontSize = 11f; |
| 104 | + style.ParagraphFormat.BeforeSpacing = 0; |
| 105 | + style.ParagraphFormat.AfterSpacing = 8; |
| 106 | + style.ParagraphFormat.LineSpacing = 13.8f; |
| 107 | + |
| 108 | + style = document.AddParagraphStyle("Heading 1") as WParagraphStyle; |
| 109 | + style.ApplyBaseStyle("Normal"); |
| 110 | + style.CharacterFormat.FontName = "Calibri Light"; |
| 111 | + style.CharacterFormat.FontSize = 16f; |
| 112 | + style.CharacterFormat.TextColor = Syncfusion.Drawing.Color.FromArgb(46, 116, 181); |
| 113 | + style.ParagraphFormat.BeforeSpacing = 12; |
| 114 | + style.ParagraphFormat.AfterSpacing = 0; |
| 115 | + style.ParagraphFormat.Keep = true; |
| 116 | + style.ParagraphFormat.KeepFollow = true; |
| 117 | + style.ParagraphFormat.OutlineLevel = OutlineLevel.Level1; |
| 118 | + |
| 119 | + IWParagraph paragraph = section.HeadersFooters.Header.AddParagraph(); |
| 120 | + paragraph.ApplyStyle("Normal"); |
| 121 | + paragraph.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Left; |
| 122 | + WTextRange textRange = paragraph.AppendText("Adventure Works Cycles") as WTextRange; |
| 123 | + textRange.CharacterFormat.FontSize = 12f; |
| 124 | + textRange.CharacterFormat.FontName = "Calibri"; |
| 125 | + textRange.CharacterFormat.TextColor = Syncfusion.Drawing.Color.Red; |
| 126 | + |
| 127 | + //Appends paragraph |
| 128 | + paragraph = section.AddParagraph(); |
| 129 | + paragraph.ApplyStyle("Heading 1"); |
| 130 | + paragraph.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Center; |
| 131 | + textRange = paragraph.AppendText("Adventure Works Cycles") as WTextRange; |
| 132 | + textRange.CharacterFormat.FontSize = 18f; |
| 133 | + textRange.CharacterFormat.FontName = "Calibri"; |
| 134 | + |
| 135 | + //Appends paragraph |
| 136 | + paragraph = section.AddParagraph(); |
| 137 | + paragraph.ParagraphFormat.FirstLineIndent = 36; |
| 138 | + paragraph.BreakCharacterFormat.FontSize = 12f; |
| 139 | + textRange = paragraph.AppendText("Adventure Works Cycles, the fictitious company on which the AdventureWorks sample databases are based, is a large, multinational manufacturing company. The company manufactures and sells metal and composite bicycles to North American, European and Asian commercial markets. While its base operation is in Bothell, Washington with 290 employees, several regional sales teams are located throughout their market base.") as WTextRange; |
| 140 | + textRange.CharacterFormat.FontSize = 12f; |
| 141 | + |
| 142 | + //Appends paragraph |
| 143 | + paragraph = section.AddParagraph(); |
| 144 | + paragraph.ParagraphFormat.FirstLineIndent = 36; |
| 145 | + paragraph.BreakCharacterFormat.FontSize = 12f; |
| 146 | + textRange = paragraph.AppendText("In 2000, AdventureWorks Cycles bought a small manufacturing plant, Importadores Neptuno, located in Mexico. Importadores Neptuno manufactures several critical subcomponents for the AdventureWorks 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.") as WTextRange; |
| 147 | + textRange.CharacterFormat.FontSize = 12f; |
| 148 | + |
| 149 | + //Saving the Excel to the MemoryStream |
| 150 | + MemoryStream stream = new MemoryStream(); |
| 151 | + document.Save(stream, FormatType.Docx); |
| 152 | + document.Close(); |
| 153 | + //Set the position as '0'. |
| 154 | + stream.Position = 0; |
| 155 | + return stream; |
| 156 | + } |
| 157 | + |
| 158 | +{% endhighlight %} |
| 159 | + |
| 160 | +{% endtabs %} |
| 161 | + |
| 162 | +Step 8: Build the project. |
| 163 | + |
| 164 | +Click on Build → Build Solution or press <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>B</kbd> to build the project. |
| 165 | + |
| 166 | +Step 9: Run the project. |
| 167 | + |
| 168 | +Click the Start button (green arrow) or press <kbd>F5</kbd> to run the app. |
| 169 | + |
| 170 | +A complete working sample is available on [GitHub](https://github.com/SyncfusionExamples/DocIO-Examples/tree/main/Getting-Started/ASP.NET-Core-Web-API/Create-Word-Document). |
| 171 | + |
| 172 | +## Steps for accessing the Web API using HTTP requests |
| 173 | + |
| 174 | +Step 1: Create a console application. |
| 175 | + |
| 176 | + |
| 177 | +Step 2: Add a name for the application. |
| 178 | + |
| 179 | + |
| 180 | +N> Ensure your ASP.NET Core Web API is running on the specified port before running this client. Adjust the port number if your Web API runs on a different port (check the ASP.NET Core app's launch settings). |
| 181 | + |
| 182 | +Step 3: Add the below code snippet in the **Program.cs** file for accessing the Web API using HTTP requests. |
| 183 | +This method sends a GET request to the Web API endpoint to retrieve and save the generated Word document. |
| 184 | + |
| 185 | +{% tabs %} |
| 186 | + |
| 187 | +{% highlight c# tabtitle="C#" %} |
| 188 | + |
| 189 | + // Create an HttpClient instance |
| 190 | + using (HttpClient client = new HttpClient()) |
| 191 | + { |
| 192 | + try |
| 193 | + { |
| 194 | + // Send a GET request to a URL |
| 195 | + HttpResponseMessage response = await client.GetAsync("https://localhost:7152/api/Values/api/Word"); |
| 196 | + // Check if the response is successful |
| 197 | + if (response.IsSuccessStatusCode) |
| 198 | + { |
| 199 | + // Read the content as a string |
| 200 | + Stream responseBody = await response.Content.ReadAsStreamAsync(); |
| 201 | + FileStream fileStream = File.Create("../../../Output/Output.docx"); |
| 202 | + responseBody.CopyTo(fileStream); |
| 203 | + fileStream.Close(); |
| 204 | + } |
| 205 | + else |
| 206 | + { |
| 207 | + Console.WriteLine($"HTTP error status code: {response.StatusCode}"); |
| 208 | + } |
| 209 | + } |
| 210 | + catch (HttpRequestException e) |
| 211 | + { |
| 212 | + Console.WriteLine($"Request exception: {e.Message}"); |
| 213 | + } |
| 214 | + } |
| 215 | + |
| 216 | +{% endhighlight %} |
| 217 | + |
| 218 | +{% endtabs %} |
| 219 | + |
| 220 | +Step 4: Build the project. |
| 221 | + |
| 222 | +Click on Build → Build Solution or press <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>B</kbd> to build the project. |
| 223 | + |
| 224 | +Step 5: Run the project. |
| 225 | + |
| 226 | +Click the Start button (green arrow) or press <kbd>F5</kbd> to run the app. |
| 227 | + |
| 228 | +A complete working sample is available on [GitHub](https://github.com/SyncfusionExamples/DocIO-Examples/tree/main/Getting-Started/ASP.NET-Core-Web-API/Client%20Application). |
| 229 | + |
| 230 | +Upon executing the program, the **Word document** will be generated as follows. |
| 231 | + |
| 232 | + |
0 commit comments