For more information, see DocX (. NET Component Introduction) and. netdocx.

Source: Internet
Author: User
Tags getstream reflector

For more information, see DocX (. NET Component Introduction) and. netdocx.

In current software projects, document operations are often used to record and collect relevant business information. Because the system itself provides operations related to documents, it greatly simplifies the workload of software users to a certain extent.

In. if the user puts forward the relevant document operation requirements in the. NET project, many developers will use the plug-ins provided by Microsoft, which simplifies the workload of developers to a certain extent, however, it also brings some troubles to users. For example, if a large office needs to be installed, user experience will be much lower. In China, many people still use wps, as a result, some users who only installed wps are very embarrassed. In terms of Excel operations, there is an NPOI component. Someone may ask if there is any way to solve these problems. The answer is yes, that is, the DocX component to be introduced today, next, let's take a look at the functions and usage of this component.

I. DocX component Overview:

DocX is A. NET Library that allows developers to process Word 2007/2010/2013 files in a simple and intuitive way. DocX is fast and lightweight. The best thing is that it does not need to install Microsoft Word or Office. The DocX component not only meets common requirements on documents, such as creating documents, creating tables and texts, but also creating graphical reports. DocX makes creating and operating documents a simple task.

It does not use the COM library, nor does it need to install Microsoft Office. When using DocX components, you need to install to use DocX to be. NET Framework 4.0 and Visual Studio 2010 or later.

DocX features:

(1) Insert, delete, or replace text in the document. All standard text formats are available. Font {series, size, color}, bold, italic, underline, strikethrough, script {sub, super}, highlighted.

(2) Section attribute display. Direction: LeftToRight or RightToLeft; indent; comparison.

(3). DocX also supports: images, hyperlinks, tables, headers and footers, and custom attributes.

For more information about the DocX component, visit https://docx.codeplex.com /.

Ii. Analysis of DocX-related classes and methods:

This article will combine the DocX source code for parsing and use. NET Reflector to decompile the DLL file to view the source code. Add the DLL file to. NET Reflector and click open file.

1. DocX. Create (): Create a document.

 public static DocX Create(Stream stream){  MemoryStream stream2 = new MemoryStream();  PostCreation(ref Package.Open(stream2, FileMode.Create, FileAccess.ReadWrite));  DocX cx = Load(stream2);  cx.stream = stream;  return cx;}

2. Paragraph. Append: add information to a Paragraph.

 public Paragraph Append(string text){  List<XElement> content = HelperFunctions.FormatInput(text, null);  base.Xml.Add(content);  this.runs = base.Xml.Elements(XName.Get("r", DocX.w.NamespaceName)).Reverse<XElement>().Take<XElement>(content.Count<XElement>()).ToList<XElement>();  return this;}
public Paragraph Bold(){  this.ApplyTextFormattingProperty(XName.Get("b", DocX.w.NamespaceName), string.Empty, null);  return this;}

3. Table. InsertTableAfterSelf: insert data into the Table.

public override Table InsertTableAfterSelf(int rowCount, int coloumnCount){  return base.InsertTableAfterSelf(rowCount, coloumnCount);}public virtual Table InsertTableAfterSelf(int rowCount, int coloumnCount){  XElement content = HelperFunctions.CreateTable(rowCount, coloumnCount);  base.Xml.AddAfterSelf(content);  return new Table(base.Document, base.Xml.ElementsAfterSelf().First<XElement>());}

4. CustomProperty: custom attributes.

public class CustomProperty{  // Fields  private string name;  private string type;  private object value;  // Methods  public CustomProperty(string name, bool value);  public CustomProperty(string name, DateTime value);  public CustomProperty(string name, double value);  public CustomProperty(string name, int value);  public CustomProperty(string name, string value);  private CustomProperty(string name, string type, object value);  internal CustomProperty(string name, string type, string value);  // Properties  public string Name { get; }  internal string Type { get; }  public object Value { get; }}

5. BarChart: Create a bar chart.

public class BarChart : Chart{  // Methods  public BarChart();  protected override XElement CreateChartXml();  // Properties  public BarDirection BarDirection { get; set; }  public BarGrouping BarGrouping { get; set; }  public int GapWidth { get; set; }}
public abstract class Chart{  // Methods  public Chart();  public void AddLegend();  public void AddLegend(ChartLegendPosition position, bool overlay);  public void AddSeries(Series series);  protected abstract XElement CreateChartXml();  public void RemoveLegend();  // Properties  public CategoryAxis CategoryAxis { get; private set; }  protected XElement ChartRootXml { get; private set; }  protected XElement ChartXml { get; private set; }  public DisplayBlanksAs DisplayBlanksAs { get; set; }  public virtual bool IsAxisExist { get; }  public ChartLegend Legend { get; private set; }  public virtual short MaxSeriesCount { get; }  public List<Series> Series { get; }  public ValueAxis ValueAxis { get; private set; }  public bool View3D { get; set; }  public XDocument Xml { get; private set; }}

6. parse the AddLegend (), AddSeries (), and RemoveLegend () Methods of the Chart:

public void AddLegend(ChartLegendPosition position, bool overlay){  if (this.Legend != null)  {    this.RemoveLegend();  }  this.Legend = new ChartLegend(position, overlay);  this.ChartRootXml.Add(this.Legend.Xml);}
public void AddSeries(Series series){  if (this.ChartXml.Elements(XName.Get("ser", DocX.c.NamespaceName)).Count<XElement>() == this.MaxSeriesCount)  {    throw new InvalidOperationException("Maximum series for this chart is" + this.MaxSeriesCount.ToString() + "and have exceeded!");  }  this.ChartXml.Add(series.Xml);}
public void RemoveLegend(){  this.Legend.Xml.Remove();  this.Legend = null;}

The above is some simple parsing of some methods of the DocX component. If You Need To Know More method implementation code, you can download and view it on your own.

Iii. DocX implementation example:

1. Create a chart:

/// <Summary> /// create a bar chart /// </summary> /// <param name = "path"> document path </param> /// <param name = "dicValue"> bind data </param> // <param name = "categoryName"> category name </param> // <param name = "valueName"> value </param> /// <param name = "title"> icon title </param> public static bool BarChart (string path, dictionary <string, ICollection> dicValue, string categoryName, string valueName, string title) {if (string. isNullOrEmpty (path) {throw new ArgumentNullException (path);} if (dicValue = null) {throw new ArgumentNullException ("dicValue");} if (string. isNullOrEmpty (categoryName) {throw new ArgumentNullException (categoryName);} if (string. isNullOrEmpty (valueName) {throw new ArgumentNullException (valueName);} if (string. isNullOrEmpty (title) {throw new ArgumentNullException (title);} try {using (var document = DocX. create (path) {// BarChart graphic attribute settings, BarDirection graph direction enumeration, BarGrouping graph Group Enumeration var c = new BarChart {BarDirection = BarDirection. column, BarGrouping = BarGrouping. standard, GapWidth = 400}; // set the legend position of the Chart c. addLegend (ChartLegendPosition. bottom, false); // write the icon data foreach (var chartData in dicValue) {var series = new Series (chartData. key); series. bind (chartData. value, categoryName, valueName); c. addSeries (series) ;}// set the document title document. insertParagraph (title ). fontSize (20); document. insertChart (c); document. save (); return true ;}} catch (Exception ex) {throw new Exception (ex. message );}}

2. Create a document with hyperlinks, images, and tables.

/// <Summary> /// create a document with hyperlinks, images, and tables. /// </Summary> /// <param name = "path"> file storage path </param> /// <param name = "imagePath"> path of the uploaded Image </param> // <param name = "url"> url </param> public static void HyperlinksImagesTables (string path, string imagePath, string url) {if (string. isNullOrEmpty (path) {throw new ArgumentNullException (path);} if (string. isNullOrEmpty (imagePath) {throw new ArgumentNullException (imagePath);} if (string. isNullOrEmp Ty (url) {throw new ArgumentNullException (url);} try {using (var document = DocX. create (path) {var link = document. addHyperlink ("link", new Uri (url); var table = document. addTable (2, 2); table. design = TableDesign. colorfulGridAccent2; table. alignment = Alignment. center; table. rows [0]. cells [0]. paragraphs [0]. append ("1"); table. rows [0]. cells [1]. paragraphs [0]. append ("2"); table. rows [1]. cells [0]. Paragraphs [0]. append ("3"); table. rows [1]. cells [1]. paragraphs [0]. append ("4"); var newRow = table. insertRow (table. rows [1]); newRow. replaceText ("4", "5"); var image = document. addImage (imagePath); var picture = image. createPicture (); picture. rotation = 10; picture. setPictureShape (BasicShapes. cube); var title = document. insertParagraph (). append ("Test "). fontSize (20 ). font (new FontFamily ("Comic Sans MS ") ); Title. alignment = Alignment. center; var p1 = document. insertParagraph (); p1.AppendLine ("This line contains "). append ("bold "). bold (). append ("word. "); p1.AppendLine (" Here is a cool "). appendHyperlink (link ). append (". "); p1.AppendLine (); p1.AppendLine (" Check out this picture "). appendPicture (picture ). append ("its funky don't you think? "); P1.AppendLine (); p1.AppendLine (" Can you check this Table of figures for me? "); P1.AppendLine (); p1.InsertTableAfterSelf (table); var p2 = document. InsertParagraph (); p2.AppendLine (" Is it correct? "); Document. Save () ;}} catch (Exception ex) {throw new Exception (ex. Message );}}

3. Write the specified content to the document:

/// <Summary> /// write the specified content to the document /// </summary> /// <param name = "path"> Load file path </param>/ // <param name = "content"> Write File content </param> // <param name = "savePath"> Save file path </param> public static void ProgrammaticallyManipulateImbeddedImage (string path, string content, string savePath) {if (string. isNullOrEmpty (path) {throw new ArgumentNullException (path);} if (string. isNullOrEmpty (content) {throw new Argument NullException (content);} if (string. isNullOrEmpty (savePath) {throw new ArgumentNullException (savePath);} try {using (var document = DocX. load (path) {// make sure that this document has at least one image. If (document. images. any () {var img = document. images [0]; // write the content to the image. var B = new Bitmap (img. getStream (FileMode. open, FileAccess. readWrite); // obtain the image object of this bitmap. The graphic object provides the drawing function. Var g = Graphics. fromImage (B); // draw string content g. drawString (content, new Font ("Tahoma", 20), Brushes. blue, new PointF (0, 0); // use the create \ write stream to save the bitmap to the document. B. save (img. getStream (FileMode. create, FileAccess. write), ImageFormat. png);} else {document. saveAs (savePath) ;}} catch (Exception ex) {throw new Exception (ex. message );}}

Iv. Summary:

The above is a simple analysis of the DocX component API, and some methods for creating documents and charts are attached for developers to refer. I hope it will be helpful for everyone's learning, and I hope you can support the house of helping customers more.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.