Skip to content

Commit ea2e246

Browse files
Merge pull request #191 from SyncfusionExamples/Word-Azure
Add samples for opening and saving Word document in Azure Blob cloud storage
2 parents 9f98fa9 + 52904d3 commit ea2e246

File tree

156 files changed

+149965
-0
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

156 files changed

+149965
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
2+
Microsoft Visual Studio Solution File, Format Version 12.00
3+
# Visual Studio Version 17
4+
VisualStudioVersion = 17.10.34928.147
5+
MinimumVisualStudioVersion = 10.0.40219.1
6+
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Open-Word-document", "Open-Word-document\Open-Word-document.csproj", "{B0715446-1BBE-434C-84D8-24CC2A410F8F}"
7+
EndProject
8+
Global
9+
GlobalSection(SolutionConfigurationPlatforms) = preSolution
10+
Debug|Any CPU = Debug|Any CPU
11+
Release|Any CPU = Release|Any CPU
12+
EndGlobalSection
13+
GlobalSection(ProjectConfigurationPlatforms) = postSolution
14+
{B0715446-1BBE-434C-84D8-24CC2A410F8F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
15+
{B0715446-1BBE-434C-84D8-24CC2A410F8F}.Debug|Any CPU.Build.0 = Debug|Any CPU
16+
{B0715446-1BBE-434C-84D8-24CC2A410F8F}.Release|Any CPU.ActiveCfg = Release|Any CPU
17+
{B0715446-1BBE-434C-84D8-24CC2A410F8F}.Release|Any CPU.Build.0 = Release|Any CPU
18+
EndGlobalSection
19+
GlobalSection(SolutionProperties) = preSolution
20+
HideSolutionNode = FALSE
21+
EndGlobalSection
22+
GlobalSection(ExtensibilityGlobals) = postSolution
23+
SolutionGuid = {1DED06B4-E665-476E-9849-FE31604E5DD9}
24+
EndGlobalSection
25+
EndGlobal
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
using Azure.Storage.Blobs.Models;
2+
using Azure.Storage.Blobs;
3+
using Microsoft.AspNetCore.Mvc;
4+
using Open_Word_document.Models;
5+
using System.Diagnostics;
6+
using static System.Net.Mime.MediaTypeNames;
7+
using Syncfusion.DocIO.DLS;
8+
using System.IO;
9+
using Microsoft.AspNetCore.DataProtection.KeyManagement;
10+
using System.IO.Pipes;
11+
12+
namespace Open_Word_document.Controllers
13+
{
14+
public class HomeController : Controller
15+
{
16+
private readonly ILogger<HomeController> _logger;
17+
18+
public HomeController(ILogger<HomeController> logger)
19+
{
20+
_logger = logger;
21+
}
22+
23+
public IActionResult Index()
24+
{
25+
return View();
26+
}
27+
public async Task<IActionResult> EditDocument()
28+
{
29+
//Your Azure Storage Account connection string
30+
string connectionString = "Your_connection_string";
31+
32+
//Name of the Azure Blob Storage container
33+
string containerName = "Your_container_name";
34+
35+
//Name of the Word file you want to load
36+
string blobName = "WordTemplate.docx";
37+
38+
try
39+
{
40+
//Retrieve the document from Azure
41+
MemoryStream stream = await GetDocumentFromAzure(connectionString, containerName, blobName);
42+
43+
//Set the position to the beginning of the MemoryStream
44+
stream.Position = 0;
45+
46+
//Create an instance of WordDocument
47+
using (WordDocument wordDocument = new WordDocument(stream, Syncfusion.DocIO.FormatType.Docx))
48+
{
49+
//Access the section in a Word document
50+
IWSection section = wordDocument.Sections[0];
51+
52+
//Add new paragraph to the section
53+
IWParagraph paragraph = section.AddParagraph();
54+
paragraph.ParagraphFormat.FirstLineIndent = 36;
55+
paragraph.BreakCharacterFormat.FontSize = 12f;
56+
57+
//Add new text to the paragraph
58+
IWTextRange 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 IWTextRange;
59+
textRange.CharacterFormat.FontSize = 12f;
60+
61+
//Saving the Word document to a MemoryStream
62+
MemoryStream outputStream = new MemoryStream();
63+
wordDocument.Save(outputStream, Syncfusion.DocIO.FormatType.Docx);
64+
65+
//Download the Word file in the browser
66+
FileStreamResult fileStreamResult = new FileStreamResult(outputStream, "application/msword");
67+
fileStreamResult.FileDownloadName = "EditWord.docx";
68+
return fileStreamResult;
69+
}
70+
71+
}
72+
catch (Exception ex)
73+
{
74+
Console.WriteLine($"Error: {ex.Message}");
75+
return Content("Error occurred while processing the file.");
76+
}
77+
}
78+
/// <summary>
79+
/// Download file from Azure Blob cloud storage
80+
/// </summary>
81+
/// <param name="bucketName"></param>
82+
/// <param name="key"></param>
83+
/// <returns></returns>
84+
public async Task<MemoryStream> GetDocumentFromAzure(string connectionString, string containerName, string blobName)
85+
{
86+
try
87+
{
88+
//Download the Word document from Azure Blob Storage
89+
BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString);
90+
BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(containerName);
91+
BlobClient blobClient = containerClient.GetBlobClient(blobName);
92+
BlobDownloadInfo download = await blobClient.DownloadAsync();
93+
94+
//Create a MemoryStream to copy the file content
95+
MemoryStream stream = new MemoryStream();
96+
await download.Content.CopyToAsync(stream);
97+
98+
return stream;
99+
}
100+
catch (Exception ex)
101+
{
102+
Console.WriteLine($"Error retrieving document from Azure Blob Storage: {ex.Message}");
103+
throw; // or handle the exception as needed
104+
}
105+
}
106+
public IActionResult Privacy()
107+
{
108+
return View();
109+
}
110+
111+
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
112+
public IActionResult Error()
113+
{
114+
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
115+
}
116+
}
117+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
namespace Open_Word_document.Models
2+
{
3+
public class ErrorViewModel
4+
{
5+
public string? RequestId { get; set; }
6+
7+
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
8+
}
9+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
<Project Sdk="Microsoft.NET.Sdk.Web">
2+
3+
<PropertyGroup>
4+
<TargetFramework>net8.0</TargetFramework>
5+
<Nullable>enable</Nullable>
6+
<ImplicitUsings>enable</ImplicitUsings>
7+
<RootNamespace>Open_Word_document</RootNamespace>
8+
</PropertyGroup>
9+
10+
<ItemGroup>
11+
<PackageReference Include="Azure.Storage.Blobs" Version="12.20.0" />
12+
<PackageReference Include="Syncfusion.DocIO.Net.Core" Version="26.1.40" />
13+
</ItemGroup>
14+
15+
</Project>
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
var builder = WebApplication.CreateBuilder(args);
2+
3+
// Add services to the container.
4+
builder.Services.AddControllersWithViews();
5+
6+
var app = builder.Build();
7+
8+
// Configure the HTTP request pipeline.
9+
if (!app.Environment.IsDevelopment())
10+
{
11+
app.UseExceptionHandler("/Home/Error");
12+
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
13+
app.UseHsts();
14+
}
15+
16+
app.UseHttpsRedirection();
17+
app.UseStaticFiles();
18+
19+
app.UseRouting();
20+
21+
app.UseAuthorization();
22+
23+
app.MapControllerRoute(
24+
name: "default",
25+
pattern: "{controller=Home}/{action=Index}/{id?}");
26+
27+
app.Run();
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
{
2+
"$schema": "http://json.schemastore.org/launchsettings.json",
3+
"iisSettings": {
4+
"windowsAuthentication": false,
5+
"anonymousAuthentication": true,
6+
"iisExpress": {
7+
"applicationUrl": "http://localhost:13880",
8+
"sslPort": 44329
9+
}
10+
},
11+
"profiles": {
12+
"http": {
13+
"commandName": "Project",
14+
"dotnetRunMessages": true,
15+
"launchBrowser": true,
16+
"applicationUrl": "http://localhost:5279",
17+
"environmentVariables": {
18+
"ASPNETCORE_ENVIRONMENT": "Development"
19+
}
20+
},
21+
"https": {
22+
"commandName": "Project",
23+
"dotnetRunMessages": true,
24+
"launchBrowser": true,
25+
"applicationUrl": "https://localhost:7147;http://localhost:5279",
26+
"environmentVariables": {
27+
"ASPNETCORE_ENVIRONMENT": "Development"
28+
}
29+
},
30+
"IIS Express": {
31+
"commandName": "IISExpress",
32+
"launchBrowser": true,
33+
"environmentVariables": {
34+
"ASPNETCORE_ENVIRONMENT": "Development"
35+
}
36+
}
37+
}
38+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
@{
2+
ViewData["Title"] = "Home Page";
3+
}
4+
5+
@{
6+
Html.BeginForm("EditDocument", "Home", FormMethod.Get);
7+
{
8+
<div>
9+
<input type="submit" value="Edit Document" style="width:150px;height:27px" />
10+
</div>
11+
}
12+
Html.EndForm();
13+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
@{
2+
ViewData["Title"] = "Privacy Policy";
3+
}
4+
<h1>@ViewData["Title"]</h1>
5+
6+
<p>Use this page to detail your site's privacy policy.</p>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
@model ErrorViewModel
2+
@{
3+
ViewData["Title"] = "Error";
4+
}
5+
6+
<h1 class="text-danger">Error.</h1>
7+
<h2 class="text-danger">An error occurred while processing your request.</h2>
8+
9+
@if (Model.ShowRequestId)
10+
{
11+
<p>
12+
<strong>Request ID:</strong> <code>@Model.RequestId</code>
13+
</p>
14+
}
15+
16+
<h3>Development Mode</h3>
17+
<p>
18+
Swapping to <strong>Development</strong> environment will display more detailed information about the error that occurred.
19+
</p>
20+
<p>
21+
<strong>The Development environment shouldn't be enabled for deployed applications.</strong>
22+
It can result in displaying sensitive information from exceptions to end users.
23+
For local debugging, enable the <strong>Development</strong> environment by setting the <strong>ASPNETCORE_ENVIRONMENT</strong> environment variable to <strong>Development</strong>
24+
and restarting the app.
25+
</p>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
<head>
4+
<meta charset="utf-8" />
5+
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
6+
<title>@ViewData["Title"] - Open_Word_document</title>
7+
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
8+
<link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
9+
<link rel="stylesheet" href="~/Open_Word_document.styles.css" asp-append-version="true" />
10+
</head>
11+
<body>
12+
<header>
13+
<nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
14+
<div class="container-fluid">
15+
<a class="navbar-brand" asp-area="" asp-controller="Home" asp-action="Index">Open_Word_document</a>
16+
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target=".navbar-collapse" aria-controls="navbarSupportedContent"
17+
aria-expanded="false" aria-label="Toggle navigation">
18+
<span class="navbar-toggler-icon"></span>
19+
</button>
20+
<div class="navbar-collapse collapse d-sm-inline-flex justify-content-between">
21+
<ul class="navbar-nav flex-grow-1">
22+
<li class="nav-item">
23+
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Index">Home</a>
24+
</li>
25+
<li class="nav-item">
26+
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
27+
</li>
28+
</ul>
29+
</div>
30+
</div>
31+
</nav>
32+
</header>
33+
<div class="container">
34+
<main role="main" class="pb-3">
35+
@RenderBody()
36+
</main>
37+
</div>
38+
39+
<footer class="border-top footer text-muted">
40+
<div class="container">
41+
&copy; 2024 - Open_Word_document - <a asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
42+
</div>
43+
</footer>
44+
<script src="~/lib/jquery/dist/jquery.min.js"></script>
45+
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
46+
<script src="~/js/site.js" asp-append-version="true"></script>
47+
@await RenderSectionAsync("Scripts", required: false)
48+
</body>
49+
</html>

0 commit comments

Comments
 (0)