Browse Source

Refactor the Table class: RowCount, ColumnCount, Rows properties and Insert/Remove methods. Also refactor CreateTable method - extract the same method CreateTableCell. Add powerfull unit test for this.

master
DragonFire_cp 14 years ago
parent
commit
a51588f35e
5 changed files with 228 additions and 185 deletions
  1. 18
    9
      DocX/HelperFunctions.cs
  2. 136
    129
      DocX/Table.cs
  3. 0
    1
      Examples/Examples.csproj
  4. BIN
      Examples/bin/Debug/docs/Input.docx
  5. 74
    46
      UnitTests/UnitTest1.cs

+ 18
- 9
DocX/HelperFunctions.cs View File

for (int j = 0; j < coloumnCount; j++) for (int j = 0; j < coloumnCount; j++)
{ {
XElement cell =
new XElement
(
XName.Get("tc", DocX.w.NamespaceName),
new XElement(XName.Get("tcPr", DocX.w.NamespaceName),
new XElement(XName.Get("tcW", DocX.w.NamespaceName), new XAttribute(XName.Get("w", DocX.w.NamespaceName), "2310"), new XAttribute(XName.Get("type", DocX.w.NamespaceName), "dxa"))),
new XElement(XName.Get("p", DocX.w.NamespaceName), new XElement(XName.Get("pPr", DocX.w.NamespaceName)))
);
XElement cell = CreateTableCell();
row.Add(cell); row.Add(cell);
} }
return newTable; return newTable;
} }
/// <summary>
/// Create and return a cell of a table
/// </summary>
internal static XElement CreateTableCell()
{
return new XElement
(
XName.Get("tc", DocX.w.NamespaceName),
new XElement(XName.Get("tcPr", DocX.w.NamespaceName),
new XElement(XName.Get("tcW", DocX.w.NamespaceName),
new XAttribute(XName.Get("w", DocX.w.NamespaceName), "2310"),
new XAttribute(XName.Get("type", DocX.w.NamespaceName), "dxa"))),
new XElement(XName.Get("p", DocX.w.NamespaceName),
new XElement(XName.Get("pPr", DocX.w.NamespaceName)))
);
}
internal static void RenumberIDs(DocX document) internal static void RenumberIDs(DocX document)
{ {
IEnumerable<XAttribute> trackerIDs = IEnumerable<XAttribute> trackerIDs =

+ 136
- 129
DocX/Table.cs View File

using System.Globalization; using System.Globalization;
namespace Novacode namespace Novacode
{
{
/// <summary> /// <summary>
/// Represents a Table in a document. /// Represents a Table in a document.
/// </summary> /// </summary>
{ {
private Alignment alignment; private Alignment alignment;
private AutoFit autofit; private AutoFit autofit;
private List<Row> rows;
private int rowCount, columnCount;
/// <summary> /// <summary>
/// Returns a list of all Paragraphs inside this container. /// Returns a list of all Paragraphs inside this container.
{ {
XElement tblPr = GetOrCreate_tblPr(); XElement tblPr = GetOrCreate_tblPr();
tblPr.Add(new XElement(DocX.w + "bidiVisual")); tblPr.Add(new XElement(DocX.w + "bidiVisual"));
foreach (Row r in Rows) foreach (Row r in Rows)
r.SetDirection(direction); r.SetDirection(direction);
} }
/// <summary> /// <summary>
/// Returns the number of rows in this table. /// Returns the number of rows in this table.
/// </summary> /// </summary>
public int RowCount { get { return rowCount; } }
public Int32 RowCount
{
get
{
return Xml.Elements(XName.Get("tr", DocX.w.NamespaceName)).Count();
}
}
/// <summary> /// <summary>
/// Returns the number of coloumns in this table. /// Returns the number of coloumns in this table.
/// </summary> /// </summary>
public int ColumnCount { get { return columnCount; } }
public Int32 ColumnCount
{
get
{
if (RowCount == 0)
return 0;
return Xml.Elements(XName.Get("tr", DocX.w.NamespaceName)) // select rows
.First() // get first row
.Elements(XName.Get("tc", DocX.w.NamespaceName)).Count(); // return column count from first row
}
}
/// <summary> /// <summary>
/// Returns a list of rows in this table. /// Returns a list of rows in this table.
/// </summary> /// </summary>
public List<Row> Rows
{
get
public List<Row> Rows
{
get
{ {
List<Row> rows =
List<Row> rows =
( (
from r in Xml.Elements(XName.Get("tr", DocX.w.NamespaceName)) from r in Xml.Elements(XName.Get("tr", DocX.w.NamespaceName))
select new Row(this, Document, r) select new Row(this, Document, r)
).ToList(); ).ToList();
rowCount = rows.Count;
if (rows.Count > 0)
if (rows[0].Cells.Count > 0)
columnCount = rows[0].Cells.Count;
return rows; return rows;
}
}
} }
private TableDesign design; private TableDesign design;
internal PackagePart mainPart; internal PackagePart mainPart;
internal Table(DocX document, XElement xml):base(document, xml)
internal Table(DocX document, XElement xml)
: base(document, xml)
{ {
autofit = AutoFit.ColoumnWidth; autofit = AutoFit.ColoumnWidth;
this.Xml = xml; this.Xml = xml;
switch (value) switch (value)
{ {
case Alignment.left: case Alignment.left:
{
alignmentString = "left";
break;
}
{
alignmentString = "left";
break;
}
case Alignment.both: case Alignment.both:
{
alignmentString = "both";
break;
}
{
alignmentString = "both";
break;
}
case Alignment.right: case Alignment.right:
{
alignmentString = "right";
break;
}
{
alignmentString = "right";
break;
}
case Alignment.center: case Alignment.center:
{
alignmentString = "center";
break;
}
{
alignmentString = "center";
break;
}
} }
XElement tblPr = Xml.Descendants(XName.Get("tblPr", DocX.w.NamespaceName)).First(); XElement tblPr = Xml.Descendants(XName.Get("tblPr", DocX.w.NamespaceName)).First();
XElement jc = tblPr.Descendants(XName.Get("jc", DocX.w.NamespaceName)).FirstOrDefault(); XElement jc = tblPr.Descendants(XName.Get("jc", DocX.w.NamespaceName)).FirstOrDefault();
if(jc != null)
if (jc != null)
jc.Remove(); jc.Remove();
jc = new XElement(XName.Get("jc", DocX.w.NamespaceName), new XAttribute(XName.Get("val", DocX.w.NamespaceName), alignmentString)); jc = new XElement(XName.Get("jc", DocX.w.NamespaceName), new XAttribute(XName.Get("val", DocX.w.NamespaceName), alignmentString));
/// </summary> /// </summary>
public AutoFit AutoFit public AutoFit AutoFit
{ {
get{return autofit;}
get { return autofit; }
set set
{ {
string attributeValue = string.Empty; string attributeValue = string.Empty;
switch(value)
switch (value)
{ {
case AutoFit.ColoumnWidth: case AutoFit.ColoumnWidth:
{
attributeValue = "dxa";
break;
}
{
attributeValue = "dxa";
break;
}
case AutoFit.Contents: case AutoFit.Contents:
{
attributeValue = "auto";
break;
}
{
attributeValue = "auto";
break;
}
case AutoFit.Window: case AutoFit.Window:
{
attributeValue = "pct";
break;
}
{
attributeValue = "pct";
break;
}
} }
var query = from d in Xml.Descendants() var query = from d in Xml.Descendants()
/// <summary> /// <summary>
/// The design\style to apply to this table. /// The design\style to apply to this table.
/// </summary> /// </summary>
public TableDesign Design
public TableDesign Design
{ {
get { return design; } get { return design; }
set set
} }
XAttribute val = style.Attribute(XName.Get("val", DocX.w.NamespaceName)); XAttribute val = style.Attribute(XName.Get("val", DocX.w.NamespaceName));
if(val == null)
if (val == null)
{ {
style.Add(new XAttribute(XName.Get("val", DocX.w.NamespaceName), "")); style.Add(new XAttribute(XName.Get("val", DocX.w.NamespaceName), ""));
val = style.Attribute(XName.Get("val", DocX.w.NamespaceName)); val = style.Attribute(XName.Get("val", DocX.w.NamespaceName));
} }
} }
/// <summary>
/// Insert a row at the end of this table.
/// </summary>
/// <example>
/// <code>
/// // Load a document.
/// using (DocX document = DocX.Load(@"C:\Example\Test.docx"))
/// {
/// // Get the first table in this document.
/// Table table = document.Tables[0];
///
/// // Insert a new row at the end of this table.
/// Row row = table.InsertRow();
///
/// // Loop through each cell in this new row.
/// foreach (Cell c in row.Cells)
/// {
/// // Set the text of each new cell to "Hello".
/// c.Paragraphs[0].InsertText("Hello", false);
/// }
///
/// // Save the document to a new file.
/// document.SaveAs(@"C:\Example\Test2.docx");
/// }// Release this document from memory.
/// </code>
/// </example>
/// <returns>A new row.</returns>
public Row InsertRow()
{
return InsertRow(Rows.Count);
}
/// <summary> /// <summary>
/// Returns the index of this Table. /// Returns the index of this Table.
/// </summary> /// </summary>
Xml.Remove(); Xml.Remove();
} }
/// <summary>
/// Insert a row at the end of this table.
/// </summary>
/// <example>
/// <code>
/// // Load a document.
/// using (DocX document = DocX.Load(@"C:\Example\Test.docx"))
/// {
/// // Get the first table in this document.
/// Table table = document.Tables[0];
///
/// // Insert a new row at the end of this table.
/// Row row = table.InsertRow();
///
/// // Loop through each cell in this new row.
/// foreach (Cell c in row.Cells)
/// {
/// // Set the text of each new cell to "Hello".
/// c.Paragraphs[0].InsertText("Hello", false);
/// }
///
/// // Save the document to a new file.
/// document.SaveAs(@"C:\Example\Test2.docx");
/// }// Release this document from memory.
/// </code>
/// </example>
/// <returns>A new row.</returns>
public Row InsertRow()
{
return InsertRow(RowCount);
}
/// <summary> /// <summary>
/// Insert a column to the right of a Table. /// Insert a column to the right of a Table.
/// </summary> /// </summary>
/// </example> /// </example>
public void InsertColumn() public void InsertColumn()
{ {
InsertColumn(columnCount);
InsertColumn(ColumnCount);
} }
/// <summary> /// <summary>
/// </example> /// </example>
public void RemoveRow() public void RemoveRow()
{ {
RemoveRow(rowCount - 1);
RemoveRow(RowCount - 1);
} }
/// <summary> /// <summary>
/// </example> /// </example>
public void RemoveRow(int index) public void RemoveRow(int index)
{ {
if (index < 0 || index > Rows.Count)
if (index < 0 || index > RowCount - 1)
throw new IndexOutOfRangeException(); throw new IndexOutOfRangeException();
Rows[index].Xml.Remove(); Rows[index].Xml.Remove();
if (Rows.Count == 0) if (Rows.Count == 0)
Remove(); Remove();
} }
/// </example> /// </example>
public void RemoveColumn() public void RemoveColumn()
{ {
RemoveColumn(columnCount - 1);
RemoveColumn(ColumnCount - 1);
} }
/// <summary> /// <summary>
/// </example> /// </example>
public void RemoveColumn(int index) public void RemoveColumn(int index)
{ {
if (index < 0 || index > columnCount - 1)
if (index < 0 || index > ColumnCount - 1)
throw new IndexOutOfRangeException(); throw new IndexOutOfRangeException();
foreach (Row r in Rows) foreach (Row r in Rows)
/// <returns>A new Row</returns> /// <returns>A new Row</returns>
public Row InsertRow(int index) public Row InsertRow(int index)
{ {
if (index < 0 || index > Rows.Count)
if (index < 0 || index > RowCount)
throw new IndexOutOfRangeException(); throw new IndexOutOfRangeException();
List<XElement> content = new List<XElement>(); List<XElement> content = new List<XElement>();
for (int i = 0; i < columnCount; i++ )
content.Add(new XElement(XName.Get("tc", DocX.w.NamespaceName), new XElement(XName.Get("p", DocX.w.NamespaceName))));
for (int i = 0; i < ColumnCount; i++)
{
XElement cell = HelperFunctions.CreateTableCell();
content.Add(cell);
}
XElement e = new XElement(XName.Get("tr", DocX.w.NamespaceName), content); XElement e = new XElement(XName.Get("tr", DocX.w.NamespaceName), content);
Row newRow = new Row(this, Document, e); Row newRow = new Row(this, Document, e);
rowXml = Rows.Last().Xml; rowXml = Rows.Last().Xml;
rowXml.AddAfterSelf(newRow.Xml); rowXml.AddAfterSelf(newRow.Xml);
} }
else else
{ {
rowXml = Rows[index].Xml; rowXml = Rows[index].Xml;
rowXml.AddBeforeSelf(newRow.Xml); rowXml.AddBeforeSelf(newRow.Xml);
} }
rowCount = Rows.Count;
return newRow; return newRow;
} }
/// </example> /// </example>
public void InsertColumn(int index) public void InsertColumn(int index)
{ {
if (Rows.Count > 0)
if (RowCount > 0)
{ {
foreach (Row r in Rows) foreach (Row r in Rows)
{ {
if(columnCount == index)
r.Cells[index - 1].Xml.AddAfterSelf(new XElement(XName.Get("tc", DocX.w.NamespaceName), new XElement(XName.Get("p", DocX.w.NamespaceName))));
// create cell
XElement cell = HelperFunctions.CreateTableCell();
// insert cell
if (r.Cells.Count == index)
r.Cells[index - 1].Xml.AddAfterSelf(cell);
else else
r.Cells[index].Xml.AddBeforeSelf(new XElement(XName.Get("tc", DocX.w.NamespaceName), new XElement(XName.Get("p", DocX.w.NamespaceName))));
r.Cells[index].Xml.AddBeforeSelf(cell);
} }
rows = (from r in Xml.Elements(XName.Get("tr", DocX.w.NamespaceName))
select new Row(this, Document, r)).ToList();
rowCount = Rows.Count;
if (rows.Count > 0)
if (rows[0].Cells.Count > 0)
columnCount = rows[0].Cells.Count;
} }
} }
/// </summary> /// </summary>
/// <example> /// <example>
/// <code> /// <code>
///// Create a new document.
/// // Create a new document.
///using (DocX document = DocX.Create("Test.docx")) ///using (DocX document = DocX.Create("Test.docx"))
///{ ///{
/// // Insert a table into this document. /// // Insert a table into this document.
/// <summary> /// <summary>
/// A list of Cells in this Row. /// A list of Cells in this Row.
/// </summary> /// </summary>
public List<Cell> Cells
{
get
public List<Cell> Cells
{
get
{ {
List<Cell> cells =
List<Cell> cells =
( (
from c in Xml.Elements(XName.Get("tc", DocX.w.NamespaceName)) from c in Xml.Elements(XName.Get("tc", DocX.w.NamespaceName))
select new Cell(this, Document, c) select new Cell(this, Document, c)
).ToList(); ).ToList();
return cells; return cells;
}
}
} }
public void Remove() public void Remove()
{ {
XElement table = Xml.Parent; XElement table = Xml.Parent;
Xml.Remove(); Xml.Remove();
if (table.Elements(XName.Get("tr", DocX.w.NamespaceName)).Count() == 0) if (table.Elements(XName.Get("tr", DocX.w.NamespaceName)).Count() == 0)
table.Remove(); table.Remove();
internal Table table; internal Table table;
internal PackagePart mainPart; internal PackagePart mainPart;
internal Row(Table table, DocX document, XElement xml):base(document, xml)
internal Row(Table table, DocX document, XElement xml)
: base(document, xml)
{ {
this.table = table; this.table = table;
this.mainPart = table.mainPart; this.mainPart = table.mainPart;
XElement trPr = Xml.Element(XName.Get("trPr", DocX.w.NamespaceName)); XElement trPr = Xml.Element(XName.Get("trPr", DocX.w.NamespaceName));
// If trPr is null, this row contains no height information. // If trPr is null, this row contains no height information.
if(trPr == null)
if (trPr == null)
return double.NaN; return double.NaN;
/* /*
* null will be return if no such element exists. * null will be return if no such element exists.
*/ */
XElement trHeight = trPr.Element(XName.Get("trHeight", DocX.w.NamespaceName)); XElement trHeight = trPr.Element(XName.Get("trHeight", DocX.w.NamespaceName));
// If trHeight is null, this row contains no height information. // If trHeight is null, this row contains no height information.
if (trHeight == null) if (trHeight == null)
return double.NaN; return double.NaN;
// The sum of all merged gridSpans. // The sum of all merged gridSpans.
int gridSpanSum = 0; int gridSpanSum = 0;
// Foreach each Cell between startIndex and endIndex inclusive. // Foreach each Cell between startIndex and endIndex inclusive.
foreach (Cell c in Cells.Where((z, i) => i > startIndex && i <= endIndex)) foreach (Cell c in Cells.Where((z, i) => i > startIndex && i <= endIndex))
{ {
// Add this cells Pragraph to the merge start Cell. // Add this cells Pragraph to the merge start Cell.
Cells[startIndex].Xml.Add(c.Xml.Elements(XName.Get("p", DocX.w.NamespaceName))); Cells[startIndex].Xml.Add(c.Xml.Elements(XName.Get("p", DocX.w.NamespaceName)));
// Remove this Cell. // Remove this Cell.
c.Xml.Remove(); c.Xml.Remove();
} }
} }
} }
public class Cell:Container
public class Cell : Container
{ {
internal Row row; internal Row row;
internal PackagePart mainPart; internal PackagePart mainPart;
internal Cell(Row row, DocX document, XElement xml):base(document, xml)
internal Cell(Row row, DocX document, XElement xml)
: base(document, xml)
{ {
this.row = row; this.row = row;
this.mainPart = row.mainPart; this.mainPart = row.mainPart;
// If shd is null, this cell contains no Color information. // If shd is null, this cell contains no Color information.
if (shd == null) if (shd == null)
return Color.White; return Color.White;
// Get the w attribute of the tcW element. // Get the w attribute of the tcW element.
XAttribute fill = shd.Attribute(XName.Get("fill", DocX.w.NamespaceName)); XAttribute fill = shd.Attribute(XName.Get("fill", DocX.w.NamespaceName));
if (fill == null) if (fill == null)
return Color.White; return Color.White;
return ColorTranslator.FromHtml(string.Format("#{0}", fill.Value));
return ColorTranslator.FromHtml(string.Format("#{0}", fill.Value));
} }
set set
// If tcW is null, this cell contains no width information. // If tcW is null, this cell contains no width information.
if (tcW == null) if (tcW == null)
return double.NaN; return double.NaN;
// Get the w attribute of the tcW element. // Get the w attribute of the tcW element.
XAttribute w = tcW.Attribute(XName.Get("w", DocX.w.NamespaceName)); XAttribute w = tcW.Attribute(XName.Get("w", DocX.w.NamespaceName));
tcMar.SetElementValue(XName.Get("left", DocX.w.NamespaceName), string.Empty); tcMar.SetElementValue(XName.Get("left", DocX.w.NamespaceName), string.Empty);
tcMarLeft = tcMar.Element(XName.Get("left", DocX.w.NamespaceName)); tcMarLeft = tcMar.Element(XName.Get("left", DocX.w.NamespaceName));
} }
// The type attribute needs to be set to dxa which represents "twips" or twentieths of a point. In other words, 1/1440th of an inch. // The type attribute needs to be set to dxa which represents "twips" or twentieths of a point. In other words, 1/1440th of an inch.
tcMarLeft.SetAttributeValue(XName.Get("type", DocX.w.NamespaceName), "dxa"); tcMarLeft.SetAttributeValue(XName.Get("type", DocX.w.NamespaceName), "dxa");
switch (border.Size) switch (border.Size)
{ {
case BorderSize.one: size = 2; break; case BorderSize.one: size = 2; break;
case BorderSize.two: size = 4; break;
case BorderSize.two: size = 4; break;
case BorderSize.three: size = 6; break; case BorderSize.three: size = 6; break;
case BorderSize.four: size = 8; break; case BorderSize.four: size = 8; break;
case BorderSize.five: size = 12; break; case BorderSize.five: size = 12; break;
/// } /// }
/// </code> /// </code>
/// </example> /// </example>
public Color FillColor
{
public Color FillColor
{
get get
{ {
/* /*

+ 0
- 1
Examples/Examples.csproj View File

<Content Include="bin\Debug\images\logo_the_happy_builder.png" /> <Content Include="bin\Debug\images\logo_the_happy_builder.png" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<None Include="bin\Debug\docs\Input.docx" />
<None Include="Input.docx"> <None Include="Input.docx">
<CopyToOutputDirectory>Always</CopyToOutputDirectory> <CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None> </None>

BIN
Examples/bin/Debug/docs/Input.docx View File


+ 74
- 46
UnitTests/UnitTest1.cs View File

{"COURT NAME","Fred Frump"}, {"COURT NAME","Fred Frump"},
{"Case Number","cr-md-2011-1234567"} {"Case Number","cr-md-2011-1234567"}
}; };
using (DocX replaceDoc = DocX.Load(directory_documents + "ReplaceTests.docx")) using (DocX replaceDoc = DocX.Load(directory_documents + "ReplaceTests.docx"))
{ {
foreach (var t in replaceDoc.Tables) foreach (var t in replaceDoc.Tables)
Assert.IsTrue(t.Rows.Count == 1); Assert.IsTrue(t.Rows.Count == 1);
Assert.IsTrue(t.RowCount == 1); Assert.IsTrue(t.RowCount == 1);
} }
// Make sure the origional strings are in the document. // Make sure the origional strings are in the document.
Assert.IsTrue(replaceDoc.FindAll("<COURT NAME>").Count == 2); Assert.IsTrue(replaceDoc.FindAll("<COURT NAME>").Count == 2);
Assert.IsTrue(replaceDoc.FindAll("<Case Number>").Count == 2); Assert.IsTrue(replaceDoc.FindAll("<Case Number>").Count == 2);
// There are only two patterns, even though each pattern is used more than once // There are only two patterns, even though each pattern is used more than once
Assert.IsTrue(replaceDoc.FindUniqueByPattern(@"<[\w \=]{4,}>", RegexOptions.IgnoreCase).Count == 2); Assert.IsTrue(replaceDoc.FindUniqueByPattern(@"<[\w \=]{4,}>", RegexOptions.IgnoreCase).Count == 2);
// Make sure the new strings are not in the document. // Make sure the new strings are not in the document.
Assert.IsTrue(replaceDoc.FindAll("Fred Frump").Count == 0); Assert.IsTrue(replaceDoc.FindAll("Fred Frump").Count == 0);
Assert.IsTrue(replaceDoc.FindAll("cr-md-2011-1234567").Count == 0); Assert.IsTrue(replaceDoc.FindAll("cr-md-2011-1234567").Count == 0);
// Make sure the replacement worked. // Make sure the replacement worked.
Assert.IsTrue(replaceDoc.Text == "\t\t\t\t\t\t\t\t\t\t\t\t\t\tThese two tables should look identical:\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSTATE OF IOWA,\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tPlaintiff,\t\t\t\t\t\t\t\t\t\t\t\t\t\tvs.\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tFRED FRUMP,\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tDefendant.\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tCase No.: cr-md-2011-1234567\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tORDER SETTING ASIDE DEFAULT JUDGMENT\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSTATE OF IOWA,\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tPlaintiff,\t\t\t\t\t\t\t\t\t\t\t\t\t\tvs.\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tFRED FRUMP,\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tDefendant.\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tCase No.: cr-md-2011-1234567\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tORDER SETTING ASIDE DEFAULT JUDGMENT\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t"); Assert.IsTrue(replaceDoc.Text == "\t\t\t\t\t\t\t\t\t\t\t\t\t\tThese two tables should look identical:\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSTATE OF IOWA,\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tPlaintiff,\t\t\t\t\t\t\t\t\t\t\t\t\t\tvs.\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tFRED FRUMP,\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tDefendant.\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tCase No.: cr-md-2011-1234567\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tORDER SETTING ASIDE DEFAULT JUDGMENT\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSTATE OF IOWA,\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tPlaintiff,\t\t\t\t\t\t\t\t\t\t\t\t\t\tvs.\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tFRED FRUMP,\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tDefendant.\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tCase No.: cr-md-2011-1234567\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tORDER SETTING ASIDE DEFAULT JUDGMENT\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t");
} }
} }
[TestMethod] [TestMethod]
{ {
// Extract Images from Document. // Extract Images from Document.
List<Novacode.Image> document_images = document.Images; List<Novacode.Image> document_images = document.Images;
// Make sure there are 3 Images in this document. // Make sure there are 3 Images in this document.
Assert.IsTrue(document_images.Count() == 3); Assert.IsTrue(document_images.Count() == 3);
// Simple // Simple
Paragraph p1 = document.InsertParagraph("AC"); Paragraph p1 = document.InsertParagraph("AC");
p1.InsertHyperlink(h); Assert.IsTrue(p1.Text == "linkAC");
p1.InsertHyperlink(h, p1.Text.Length); Assert.IsTrue(p1.Text == "linkAClink");
p1.InsertHyperlink(h); Assert.IsTrue(p1.Text == "linkAC");
p1.InsertHyperlink(h, p1.Text.Length); Assert.IsTrue(p1.Text == "linkAClink");
p1.InsertHyperlink(h, p1.Text.IndexOf("C")); Assert.IsTrue(p1.Text == "linkAlinkClink"); p1.InsertHyperlink(h, p1.Text.IndexOf("C")); Assert.IsTrue(p1.Text == "linkAlinkClink");
// Difficult // Difficult
Paragraph p2 = document.InsertParagraph("\tA\tC\t"); Paragraph p2 = document.InsertParagraph("\tA\tC\t");
p2.InsertHyperlink(h); Assert.IsTrue(p2.Text == "link\tA\tC\t");
p2.InsertHyperlink(h, p2.Text.Length); Assert.IsTrue(p2.Text == "link\tA\tC\tlink");
p2.InsertHyperlink(h); Assert.IsTrue(p2.Text == "link\tA\tC\t");
p2.InsertHyperlink(h, p2.Text.Length); Assert.IsTrue(p2.Text == "link\tA\tC\tlink");
p2.InsertHyperlink(h, p2.Text.IndexOf("C")); Assert.IsTrue(p2.Text == "link\tA\tlinkC\tlink"); p2.InsertHyperlink(h, p2.Text.IndexOf("C")); Assert.IsTrue(p2.Text == "link\tA\tlinkC\tlink");
// Contrived // Contrived
// Add a contrived Hyperlink to this document. // Add a contrived Hyperlink to this document.
Hyperlink h2 = document.AddHyperlink("\tlink\t", new Uri("http://www.google.com")); Hyperlink h2 = document.AddHyperlink("\tlink\t", new Uri("http://www.google.com"));
Paragraph p3 = document.InsertParagraph("\tA\tC\t"); Paragraph p3 = document.InsertParagraph("\tA\tC\t");
p3.InsertHyperlink(h2); Assert.IsTrue(p3.Text == "\tlink\t\tA\tC\t");
p3.InsertHyperlink(h2); Assert.IsTrue(p3.Text == "\tlink\t\tA\tC\t");
p3.InsertHyperlink(h2, p3.Text.Length); Assert.IsTrue(p3.Text == "\tlink\t\tA\tC\t\tlink\t"); p3.InsertHyperlink(h2, p3.Text.Length); Assert.IsTrue(p3.Text == "\tlink\t\tA\tC\t\tlink\t");
p3.InsertHyperlink(h2, p3.Text.IndexOf("C")); Assert.IsTrue(p3.Text == "\tlink\t\tA\t\tlink\tC\t\tlink\t"); p3.InsertHyperlink(h2, p3.Text.IndexOf("C")); Assert.IsTrue(p3.Text == "\tlink\t\tA\t\tlink\tC\t\tlink\t");
} }
[TestMethod] [TestMethod]
public void Test_Paragraph_RemoveHyperlink() public void Test_Paragraph_RemoveHyperlink()
{
{
// Create a new document // Create a new document
using (DocX document = DocX.Create("Test.docx")) using (DocX document = DocX.Create("Test.docx"))
{ {
// Try and remove a Hyperlink at an index greater than the last. // Try and remove a Hyperlink at an index greater than the last.
// This should throw an exception. // This should throw an exception.
try
try
{ {
p1.RemoveHyperlink(3); p1.RemoveHyperlink(3);
Assert.Fail(); Assert.Fail();
} }
catch (ArgumentException) {}
catch (ArgumentException) { }
catch (Exception) { Assert.Fail(); } catch (Exception) { Assert.Fail(); }
p1.RemoveHyperlink(0); Assert.IsTrue(p1.Text == "AlinkClink"); p1.RemoveHyperlink(0); Assert.IsTrue(p1.Text == "AlinkClink");
} }
[TestMethod] [TestMethod]
public void Test_Table_InsertRow()
public void Test_Table_InsertRowAndColumn()
{ {
// Create a table
using (DocX document = DocX.Create(directory_documents + "Tables2.docx")) using (DocX document = DocX.Create(directory_documents + "Tables2.docx"))
{ {
// Add a Table to a document. // Add a Table to a document.
Table t = document.AddTable(2, 2); Table t = document.AddTable(2, 2);
t.Design = TableDesign.TableGrid; t.Design = TableDesign.TableGrid;
t.Rows[0].Cells[0].Paragraphs[0].InsertText("X");
t.Rows[0].Cells[1].Paragraphs[0].InsertText("X");
t.Rows[1].Cells[0].Paragraphs[0].InsertText("X");
t.Rows[1].Cells[1].Paragraphs[0].InsertText("X");
// Insert the Table into the main section of the document. // Insert the Table into the main section of the document.
Table t1 = document.InsertTable(t); Table t1 = document.InsertTable(t);
t1.InsertRow();
t1.InsertColumn();
// ... and add a column and a row
t1.InsertRow(1);
t1.InsertColumn(1);
// Save the document. // Save the document.
document.Save(); document.Save();
} }
// Check table
using (DocX document = DocX.Load(directory_documents + "Tables2.docx"))
{
// Get a table from a document
Table t = document.Tables[0];
// Check that the table is equal this:
// X - X
// - - -
// X - X
Assert.AreEqual("X", t.Rows[0].Cells[0].Paragraphs[0].Text);
Assert.AreEqual("X", t.Rows[2].Cells[0].Paragraphs[0].Text);
Assert.AreEqual("X", t.Rows[0].Cells[2].Paragraphs[0].Text);
Assert.AreEqual("X", t.Rows[2].Cells[2].Paragraphs[0].Text);
Assert.IsTrue(String.IsNullOrEmpty(t.Rows[1].Cells[0].Paragraphs[0].Text));
Assert.IsTrue(String.IsNullOrEmpty(t.Rows[1].Cells[1].Paragraphs[0].Text));
Assert.IsTrue(String.IsNullOrEmpty(t.Rows[1].Cells[2].Paragraphs[0].Text));
Assert.IsTrue(String.IsNullOrEmpty(t.Rows[0].Cells[1].Paragraphs[0].Text));
Assert.IsTrue(String.IsNullOrEmpty(t.Rows[2].Cells[1].Paragraphs[0].Text));
}
} }
[TestMethod]
public void Test_Document_ApplyTemplate()
{
using (MemoryStream documentStream = new MemoryStream())
[TestMethod]
public void Test_Document_ApplyTemplate()
{ {
using (DocX document = DocX.Create(documentStream))
{
document.ApplyTemplate(directory_documents + "Template.dotx");
document.Save();
Header firstHeader = document.Headers.first;
Header oddHeader = document.Headers.odd;
Header evenHeader = document.Headers.even;
using (MemoryStream documentStream = new MemoryStream())
{
using (DocX document = DocX.Create(documentStream))
{
document.ApplyTemplate(directory_documents + "Template.dotx");
document.Save();
Header firstHeader = document.Headers.first;
Header oddHeader = document.Headers.odd;
Header evenHeader = document.Headers.even;
Footer firstFooter = document.Footers.first;
Footer oddFooter = document.Footers.odd;
Footer evenFooter = document.Footers.even;
Footer firstFooter = document.Footers.first;
Footer oddFooter = document.Footers.odd;
Footer evenFooter = document.Footers.even;
Assert.IsTrue(firstHeader.Paragraphs.Count==1, "More than one paragraph in header.");
Assert.IsTrue(firstHeader.Paragraphs[0].Text.Equals("First page header"), "Header isn't retrieved from template.");
Assert.IsTrue(firstHeader.Paragraphs.Count == 1, "More than one paragraph in header.");
Assert.IsTrue(firstHeader.Paragraphs[0].Text.Equals("First page header"), "Header isn't retrieved from template.");
Assert.IsTrue(oddHeader.Paragraphs.Count == 1, "More than one paragraph in header.");
Assert.IsTrue(oddHeader.Paragraphs[0].Text.Equals("Odd page header"), "Header isn't retrieved from template.");
Assert.IsTrue(oddHeader.Paragraphs.Count == 1, "More than one paragraph in header.");
Assert.IsTrue(oddHeader.Paragraphs[0].Text.Equals("Odd page header"), "Header isn't retrieved from template.");
Assert.IsTrue(evenHeader.Paragraphs.Count == 1, "More than one paragraph in header.");
Assert.IsTrue(evenHeader.Paragraphs[0].Text.Equals("Even page header"), "Header isn't retrieved from template.");
Assert.IsTrue(evenHeader.Paragraphs.Count == 1, "More than one paragraph in header.");
Assert.IsTrue(evenHeader.Paragraphs[0].Text.Equals("Even page header"), "Header isn't retrieved from template.");
Assert.IsTrue(firstFooter.Paragraphs.Count == 1, "More than one paragraph in footer.");
Assert.IsTrue(firstFooter.Paragraphs[0].Text.Equals("First page footer"), "Footer isn't retrieved from template.");
Assert.IsTrue(firstFooter.Paragraphs.Count == 1, "More than one paragraph in footer.");
Assert.IsTrue(firstFooter.Paragraphs[0].Text.Equals("First page footer"), "Footer isn't retrieved from template.");
Assert.IsTrue(oddFooter.Paragraphs.Count == 1, "More than one paragraph in footer.");
Assert.IsTrue(oddFooter.Paragraphs[0].Text.Equals("Odd page footer"), "Footer isn't retrieved from template.");
Assert.IsTrue(oddFooter.Paragraphs.Count == 1, "More than one paragraph in footer.");
Assert.IsTrue(oddFooter.Paragraphs[0].Text.Equals("Odd page footer"), "Footer isn't retrieved from template.");
Assert.IsTrue(evenFooter.Paragraphs.Count == 1, "More than one paragraph in footer.");
Assert.IsTrue(evenFooter.Paragraphs[0].Text.Equals("Even page footer"), "Footer isn't retrieved from template.");
Assert.IsTrue(evenFooter.Paragraphs.Count == 1, "More than one paragraph in footer.");
Assert.IsTrue(evenFooter.Paragraphs[0].Text.Equals("Even page footer"), "Footer isn't retrieved from template.");
Paragraph firstParagraph = document.Paragraphs[0];
Assert.IsTrue(firstParagraph.StyleName.Equals("DocXSample"), "First paragraph isn't of style from template.");
}
Paragraph firstParagraph = document.Paragraphs[0];
Assert.IsTrue(firstParagraph.StyleName.Equals("DocXSample"), "First paragraph isn't of style from template.");
}
}
} }
}
} }
} }

Loading…
Cancel
Save