In this article I will explain with an example, how to dynamically create and download Word document using OpenXml in ASP.Net Core (.Net Core) Razor Pages
Install DocumentFormat.OpenXml package
Namespaces
You will need to import the following namespaces.
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
Using OpenXml Word Processing functions
Below there are two functions which are simplified in order to add Words with styles and HyperLinks.
AddRun
This function is used to add words and sentences to the document.
Inside this method, the text content to be added to the Document is created.
The AddRun function accepts the following parameters:
1. word – The text content to be added to the document.
2. font – Default value Arial. It specifies the Font of the text.
3. size – Default value 20. It specifies the Font Size of the text.
4. bold – Default value false. It specifies the text will have BOLD style.
5. italic – Default value false. It specifies the text will have ITALIC style.
6. underline – Default value false. It specifies the text will have UNDERLINE style.
7. preserveSpace – Default value true. It preserves the space before and after the text.
Inside this method, an object of Run class is created and using RunFonts and FontSize classes, the size of the text content is defined.
After that, using RunProperties, the styles are applied to the text content and the PreserveSpace value is also set using Preserve property of the SpaceProcessingModeValues class.
Finally, the Run class object is returned.
private Run AddRun(
string word,
string font = "Arial",
string size = "20",
bool bold = false,
bool italic = false,
bool underline = false,
bool preserveSpace = true)
{
// Create Run instance.
Run run = new Run();
// Create RunFonts instance.
RunFonts runFont = new RunFonts { Ascii = font };
// Create FontSize instance.
//It must be multiplication twice of the required size.
FontSize fontSize = new FontSize { Val = new StringValue(size) };
// Create Text instance.
Text text = new Text(word);
// Create RunProperties instance.
RunProperties runProperties = new RunProperties();
if (bold)
{
// Applying Bold.
runProperties.Bold = new Bold();
}
if (italic)
{
// Applying Italic.
runProperties.Italic = new Italic();
}
if (underline)
{
// Applying Underline.
runProperties.Underline = new Underline{ Val = UnderlineValues.Single };
}
if (preserveSpace)
{
// Defines the SpaceProcessingModeValues.
text.Space = SpaceProcessingModeValues.Preserve;
}
}
// Adding Font to RunProperties.
runProperties.Append(runFont);
// Adding FontSize to RunProperties.
runProperties.Append(fontSize);
// Adding RunProperties to Run.
run.Append(runProperties);
// Adding Text to Run.
run.Append(text);
return run;
}
AddLink – This function is used to create HyperLink to be added to the Document.
The AddLink function accepts the following parameters:
1. MainDocumentPart – The Document to which the HyperLink will be added.
2. text – The text to which the HyperLink will be set.
3. url – The URL which will be opened on click of HyperLink.
Inside this method, an object of HyperLink class is created and necessary properties i.e. Id and History are set.
Then, Run class object is created using AddRun method (explained earlier) and the properties i.e. Color, RunStyle and Underline are set and appended to HyperLink class object.
Finally, the HyperLink class object is returned.
private Hyperlink AddLink(ref MainDocumentPart mainPart, string text, string url)
{
// Adding HyperlinkRelationship with Relationship Id.
HyperlinkRelationship hyperlinkRelationship = mainPart.AddHyperlinkRelationship(new Uri(url), true);
// Creating Hyperlink.
Hyperlink hyperlink = new Hyperlink();
hyperlink.Id = hyperlinkRelationship.Id;
// Add to Viewed Hyperlinks.
hyperlink.History = OnOffValue.FromBoolean(true);
// Creating Run.
Run run = this.AddRun(text, underline: true);
// Specifying the Color Class.
run.RunProperties.Color = new Color { ThemeColor = ThemeColorValues.Hyperlink };
// Specifying the RunStyle Class.
run.RunProperties.RunStyle = new RunStyle { Val = "Hyperlink" };
// Underline the Hyperlink.
run.RunProperties.Underline = new Underline { Val = UnderlineValues.Single };
// Adding the Run to Hyperlink.
hyperlink.Append(run);
return hyperlink;
}
Controller
The Controller consists of following Action methods.
Action method for handling GET operation
Inside this Action method, simple the View is returned.
Action method for handling POST operation
When the Create Document Button is clicked, an object of WordprocessingDocument is created.
Then, document structure is designed and text contents and link text are added to document using AddRun method (explained earlier) and AddLink (explained earlier) method respectively.
Finally, using File function which accepts the BYTE Array, content type and the destination file name the file download operation is initiated.
public class HomeController : Controller
{
// GET: Home
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult Create()
{
using (MemoryStream stream = new MemoryStream())
{
// Create a document.
using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(stream, WordprocessingDocumentType.Document, true))
{
// Add main document part.
MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();
// Create document structure.
mainPart.Document = new Document();
// Create document body.
Body body = mainPart.Document.AppendChild(new Body());
// Create paragraph.
Paragraph paragraph = new Paragraph();
// Creating Run.
Run run = this.AddRun("Hi,");
// Adding Run to Paragraph.
paragraph.Append(run);
// Adding Paragraph to Body.
body.Append(paragraph);
// Adding new Paragraph.
paragraph = new Paragraph();
run = this.AddRun("This is ");
paragraph.Append(run);
// Adding Text with Bold and Italic.
run = this.AddRun("Mudassar Khan", bold: true, italic: true);
paragraph.Append(run);
run = this.AddRun(".");
paragraph.Append(run);
// Adding Paragraph to Body.
body.Append(paragraph);
// Adding Paragraph for Hyperlink.
paragraph = new Paragraph();
// Adding Hyperlink to Paragraph.
paragraph.Append(this.AddLink(ref mainPart, "aspsnippets", "https://www.aspsnippets.com"));
// Adding Hyperlink Paragraph to Document Body.
body.Append(paragraph);
}
return File(stream.ToArray(), "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "Sample.docx");
}
}
}
View
HTML Markup
The View consists of an HTML Form which has been created using the ASP.Net TagHelpers with the following attributes.
asp-action – Name of the Action. In this case the name is Create.
asp-controller – Name of the Controller. In this case the name is Home.
method – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
The Form consists of an HTML INPUT Submit Button.
Submitting the Form
When the Submit Button is clicked then, the form will be submitted to the Controller’s Action method.
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<form method="post" asp-controller="Home" asp-action="Create">
<input type="submit" value="Create Document" />
</form>
</body>
</html>
Screenshot
Demo
Downloads