Introduction and Application of Open Source Document Operating Component DocX in. NET

  • 2021-08-28 19:52:08
  • OfStack

Preface

Believe everyone should have experience, in the current software project, will be more use of the document operation, used to record and statistics related business information. Because the system itself provides the related operation of documents, it greatly simplifies the workload of software users to a certain extent.

In the. NET project, if the user puts forward the requirements for related document operation, Most developers will use Microsoft's own plug-ins. To a certain extent, it simplifies the workload of developers, but it also brings some troubles to users. For example, the need to install a huge office will reduce the user experience a lot. In China, many people still use wps, which leads to the difficulty for users who only install wps in part 1. In the operation of Excel, there is an NPOI component. Then some people may ask if there is any way to solve these problems. The answer is yes, that is, the "DocX" component that needs to be introduced today. Next, let's learn about the function and usage of this component.

1. Overview of 1. DocX components:

DocX is a. NET library that allows developers to work with Word 2007/2010/2013 files in a simple and intuitive way. The DocX is fast, lightweight, and best of all it does not require Microsoft, Word or Office. The DocX component not only fulfills the general requirements for documents, such as creating documents, tables, and text, but also creates graphical reports. DocX makes creating and manipulating documents a simple task.

It does not use the COM library and does not require the installation of Microsoft Office. When using DocX components, you need to install NET Framework 4.0 and Visual Studio 2010 or later in order to use DocX.

Main features of DocX:

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

(2). Paragraph attributes are displayed. Direction LeftToRight Or RightToLeft ; Indent; Compare.

(3). DocX also supports: pictures, hyperlinks, tables, headers and footers, custom properties.

That's all about the DocX component. If you need more information, you can go to: https://docx.codeplex.com/.

2. DocX related classes and methods resolution:

This article will combine the source code of DocX analysis, using. NET Reflector DLL file decompilation, in order to view the source code. Add the DLL file to. NET Reflector and click to open the 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 a 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 properties.


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. Analysis of AddLegend (), AddSeries () and RemoveLegend () methods of 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;
}

Above is the DocX component of a few methods of a simple analysis, if you need to know more methods to achieve code, you can download their own view.

3. DocX function 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 name </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 property settings, BarDirection Graphic direction enumeration, BarGrouping Graphic grouping enumeration 
     var c = new BarChart
     {
      BarDirection = BarDirection.Column,
      BarGrouping = BarGrouping.Standard,
      GapWidth = 400
     };
     // Set the chart legend position 
     c.AddLegend(ChartLegendPosition.Bottom, false);
     // Write 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 1 Documents with hyperlinks, images, and tables. 
  /// </summary>
  /// <param name="path"> Document save path </param>
  /// <param name="imagePath"> Loaded picture path </param>
  /// <param name="url">url Address </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.IsNullOrEmpty(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 a ").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. Writes the specified content to the document:


  /// <summary>
  ///  Writes the specified content to the document 
  /// </summary>
  /// <param name="path"> Load file path </param>
  /// <param name="content"> Write the contents of the file </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 ArgumentNullException(content);
   }
   if (string.IsNullOrEmpty(savePath))
   {
    throw new ArgumentNullException(savePath);
   }
   try
   {
    using (var document = DocX.Load(path))
    {
     //  Ensure that this document has at least 1 Images. 
     if (document.Images.Any())
     {
      var img = document.Images[0];
      //  Write content to a picture .
      var b = new Bitmap(img.GetStream(FileMode.Open, FileAccess.ReadWrite));
      // Gets the graphics object of this bitmap, which provides drawing function. 
      var g = Graphics.FromImage(b);
      //  Draw string content 
      g.DrawString
       (
        content,
        new Font("Tahoma", 20),
        Brushes.Blue,
        new PointF(0, 0)
       );
      //  Use to create \ The write stream saves 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);
   }
  }

Summarize

The above is the DocX component of API made a simple analysis, and attached a number of creating documents and creating charts for developers' reference. I hope the content of this article can bring 1 certain help to your study or work. If you have any questions, you can leave a message for communication.


Related articles: