Bläddra i källkod

Added Examples Project.

This projects contains many of the examples upload on my blog.
Each time docx is released, I will update these examples so as they still work regardless of API changes.
master
coffeycathal_cp 15 år sedan
förälder
incheckning
e36ca493b0

+ 15
- 12
DocX.sln Visa fil

@@ -12,11 +12,11 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DocX", "DocX\DocX.csproj",
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UnitTests", "UnitTests\UnitTests.csproj", "{3EA73F1C-9E0B-4ED5-B04B-6C043D14D1AA}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConsoleApplication1", "ConsoleApplication1\ConsoleApplication1.csproj", "{03479485-7974-4F61-95D2-22648055C4AD}"
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Examples", "Examples\Examples.csproj", "{F3022BB7-0E40-4C80-A495-37FEAF3671AB}"
EndProject
Global
GlobalSection(TeamFoundationVersionControl) = preSolution
SccNumberOfProjects = 3
SccNumberOfProjects = 4
SccEnterpriseProvider = {4CA58AB2-18FA-4F8D-95D4-32DDF27D184C}
SccTeamFoundationServer = https://tfs.codeplex.com/tfs/tfs08
SccLocalPath0 = .
@@ -26,6 +26,9 @@ Global
SccProjectUniqueName2 = UnitTests\\UnitTests.csproj
SccProjectName2 = UnitTests
SccLocalPath2 = UnitTests
SccProjectUniqueName3 = Examples\\Examples.csproj
SccProjectName3 = Examples
SccLocalPath3 = Examples
EndGlobalSection
GlobalSection(TestCaseManagementSettings) = postSolution
CategoryFile = DocX.vsmdi
@@ -59,16 +62,16 @@ Global
{3EA73F1C-9E0B-4ED5-B04B-6C043D14D1AA}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
{3EA73F1C-9E0B-4ED5-B04B-6C043D14D1AA}.Release|Mixed Platforms.Build.0 = Release|Any CPU
{3EA73F1C-9E0B-4ED5-B04B-6C043D14D1AA}.Release|x86.ActiveCfg = Release|Any CPU
{03479485-7974-4F61-95D2-22648055C4AD}.Debug|Any CPU.ActiveCfg = Debug|x86
{03479485-7974-4F61-95D2-22648055C4AD}.Debug|Mixed Platforms.ActiveCfg = Debug|x86
{03479485-7974-4F61-95D2-22648055C4AD}.Debug|Mixed Platforms.Build.0 = Debug|x86
{03479485-7974-4F61-95D2-22648055C4AD}.Debug|x86.ActiveCfg = Debug|x86
{03479485-7974-4F61-95D2-22648055C4AD}.Debug|x86.Build.0 = Debug|x86
{03479485-7974-4F61-95D2-22648055C4AD}.Release|Any CPU.ActiveCfg = Release|x86
{03479485-7974-4F61-95D2-22648055C4AD}.Release|Mixed Platforms.ActiveCfg = Release|x86
{03479485-7974-4F61-95D2-22648055C4AD}.Release|Mixed Platforms.Build.0 = Release|x86
{03479485-7974-4F61-95D2-22648055C4AD}.Release|x86.ActiveCfg = Release|x86
{03479485-7974-4F61-95D2-22648055C4AD}.Release|x86.Build.0 = Release|x86
{F3022BB7-0E40-4C80-A495-37FEAF3671AB}.Debug|Any CPU.ActiveCfg = Debug|x86
{F3022BB7-0E40-4C80-A495-37FEAF3671AB}.Debug|Mixed Platforms.ActiveCfg = Debug|x86
{F3022BB7-0E40-4C80-A495-37FEAF3671AB}.Debug|Mixed Platforms.Build.0 = Debug|x86
{F3022BB7-0E40-4C80-A495-37FEAF3671AB}.Debug|x86.ActiveCfg = Debug|x86
{F3022BB7-0E40-4C80-A495-37FEAF3671AB}.Debug|x86.Build.0 = Debug|x86
{F3022BB7-0E40-4C80-A495-37FEAF3671AB}.Release|Any CPU.ActiveCfg = Release|x86
{F3022BB7-0E40-4C80-A495-37FEAF3671AB}.Release|Mixed Platforms.ActiveCfg = Release|x86
{F3022BB7-0E40-4C80-A495-37FEAF3671AB}.Release|Mixed Platforms.Build.0 = Release|x86
{F3022BB7-0E40-4C80-A495-37FEAF3671AB}.Release|x86.ActiveCfg = Release|x86
{F3022BB7-0E40-4C80-A495-37FEAF3671AB}.Release|x86.Build.0 = Release|x86
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

+ 2
- 2
DocX/Container.cs Visa fil

@@ -381,7 +381,7 @@ namespace Novacode
public Table InsertTable(int coloumnCount, int rowCount)
{
XElement newTable = HelperFunctions.CreateTable(rowCount, coloumnCount);
Xml.Descendants(XName.Get("body", DocX.w.NamespaceName)).First().Add(newTable);
Xml.Elements().First().Add(newTable);
return new Table(Document, newTable);
}
@@ -393,7 +393,7 @@ namespace Novacode
Paragraph p = HelperFunctions.GetFirstParagraphEffectedByInsert(Document, index);
if (p == null)
Xml.Descendants(XName.Get("body", DocX.w.NamespaceName)).First().AddFirst(newTable);
Xml.Elements().First().AddFirst(newTable);
else
{

+ 22
- 9
DocX/Paragraph.cs Visa fil

@@ -864,14 +864,21 @@ namespace Novacode
// Check to see if a rel for this Picture exists, create it if not.
var Id = GetOrGenerateRel(h);
if (index == 0)
return AppendHyperlink(h);
XElement h_xml;
if (index == 0)
{
// Add this hyperlink as the last element.
Xml.AddFirst(h.Xml);
// Extract the picture back out of the DOM.
h_xml = (XElement)Xml.FirstNode;
}
else
{
// Get the first run effected by this Insert
Run run = GetFirstRunEffectedByEdit(index);
XElement h_xml;
if (run == null)
{
// Add this hyperlink as the last element.
@@ -1868,8 +1875,8 @@ namespace Novacode
// Check to see if a rel for this Picture exists, create it if not.
var Id = GetOrGenerateRel(h);
Xml.AddFirst(h.Xml);
Xml.Elements().First().SetAttributeValue(DocX.r + "id", Id);
Xml.Add(h.Xml);
Xml.Elements().Last().SetAttributeValue(DocX.r + "id", Id);
this.runs = Xml.Elements().Last().Elements(XName.Get("r", DocX.w.NamespaceName)).ToList();
@@ -1921,12 +1928,12 @@ namespace Novacode
var Id = GetOrGenerateRel(p);
// Add the Picture Xml to the end of the Paragragraph Xml.
Xml.AddFirst(p.Xml);
Xml.Add(p.Xml);
// Extract the attribute id from the Pictures Xml.
XAttribute a_id =
(
from e in Xml.Elements().First().Descendants()
from e in Xml.Elements().Last().Descendants()
where e.Name.LocalName.Equals("blip")
select e.Attribute(XName.Get("embed", "http://schemas.openxmlformats.org/officeDocument/2006/relationships"))
).Single();
@@ -2054,15 +2061,21 @@ namespace Novacode
// Check to see if a rel for this Picture exists, create it if not.
var Id = GetOrGenerateRel(p);
XElement p_xml;
if (index == 0)
return AppendPicture(p);
{
// Add this hyperlink as the last element.
Xml.AddFirst(p.Xml);
// Extract the picture back out of the DOM.
p_xml = (XElement)Xml.FirstNode;
}
else
{
// Get the first run effected by this Insert
Run run = GetFirstRunEffectedByEdit(index);
XElement p_xml;
if (run == null)
{
// Add this picture as the last element.

+ 7
- 8
DocX/Table.cs Visa fil

@@ -515,7 +515,7 @@ namespace Novacode
/// <returns>A new row.</returns>
public Row InsertRow()
{
return InsertRow(rows.Count);
return InsertRow(Rows.Count);
}
/// <summary>
@@ -767,32 +767,31 @@ namespace Novacode
/// <returns>A new Row</returns>
public Row InsertRow(int index)
{
if (index < 0 || index > rows.Count)
if (index < 0 || index > Rows.Count)
throw new IndexOutOfRangeException();
List<XElement> content = new List<XElement>();
foreach (Cell c in rows[0].Cells)
foreach (Cell c in Rows[0].Cells)
content.Add(new XElement(XName.Get("tc", DocX.w.NamespaceName), new XElement(XName.Get("p", DocX.w.NamespaceName))));
XElement e = new XElement(XName.Get("tr", DocX.w.NamespaceName), content);
Row newRow = new Row(this, Document, e);
XElement rowXml;
if (index == rows.Count)
if (index == Rows.Count)
{
rowXml = rows.Last().Xml;
rowXml = Rows.Last().Xml;
rowXml.AddAfterSelf(newRow.Xml);
}
else
{
rowXml = rows[index].Xml;
rowXml = Rows[index].Xml;
rowXml.AddBeforeSelf(newRow.Xml);
}
rows.Insert(index, newRow);
rowCount = rows.Count;
rowCount = Rows.Count;
return newRow;
}

+ 75
- 0
Examples/Examples.csproj Visa fil

@@ -0,0 +1,75 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">x86</Platform>
<ProductVersion>8.0.30703</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{F3022BB7-0E40-4C80-A495-37FEAF3671AB}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Examples</RootNamespace>
<AssemblyName>Examples</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<TargetFrameworkProfile>Client</TargetFrameworkProfile>
<FileAlignment>512</FileAlignment>
<SccProjectName>SAK</SccProjectName>
<SccLocalPath>SAK</SccLocalPath>
<SccAuxPath>SAK</SccAuxPath>
<SccProvider>SAK</SccProvider>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
<PlatformTarget>x86</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
<PlatformTarget>x86</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Drawing" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\DocX\DocX.csproj">
<Project>{E863D072-AA8B-4108-B5F1-785241B37F67}</Project>
<Name>DocX</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<Content Include="bin\Debug\images\logo_template.png" />
<Content Include="bin\Debug\images\logo_the_happy_builder.png" />
</ItemGroup>
<ItemGroup>
<None Include="bin\Debug\docs\Input.docx" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

+ 10
- 0
Examples/Examples.csproj.vspscc Visa fil

@@ -0,0 +1,10 @@
""
{
"FILE_VERSION" = "9237"
"ENLISTMENT_CHOICE" = "NEVER"
"PROJECT_FILE_RELATIVE_PATH" = ""
"NUMBER_OF_EXCLUDED_FILES" = "0"
"ORIGINAL_PROJECT_FILE_PATH" = ""
"NUMBER_OF_NESTED_PROJECTS" = "0"
"SOURCE_CONTROL_SETTINGS_PROVIDER" = "PROVIDER"
}

+ 686
- 0
Examples/Program.cs Visa fil

@@ -0,0 +1,686 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Novacode;
using System.Drawing;
using System.IO;
using System.Drawing.Imaging;
using System.Threading.Tasks;
using System.Data;
namespace Examples
{
class Program
{
static void Main(string[] args)
{
// Easy
Console.WriteLine("\nRunning Easy Examples");
HelloWorld();
RightToLeft();
Indentation();
HeadersAndFooters();
HyperlinksImagesTables();
// Intermediate
Console.WriteLine("\nRunning Intermediate Examples");
CreateInvoice();
// Advanced
Console.WriteLine("\nRunning Advanced Examples");
ProgrammaticallyManipulateImbeddedImage();
ReplaceTextParallel();
Console.WriteLine("\nPress any key to exit.");
Console.ReadKey();
}
/// <summary>
/// Create a document with a Paragraph whos first line is indented.
/// </summary>
private static void Indentation()
{
Console.WriteLine("\tIndentation()");
// Create a new document.
using (DocX document = DocX.Create(@"docs\Indentation.docx"))
{
// Create a new Paragraph.
Paragraph p = document.InsertParagraph("Line 1\nLine 2\nLine 3");
// Indent only the first line of the Paragraph.
p.IndentationFirstLine = 1.0f;
// Save all changes made to this document.
document.Save();
Console.WriteLine("\tCreated: docs\\Indentation.docx\n");
}
}
/// <summary>
/// Create a document that with RightToLeft text flow.
/// </summary>
private static void RightToLeft()
{
Console.WriteLine("\tRightToLeft()");
// Create a new document.
using (DocX document = DocX.Create(@"docs\RightToLeft.docx"))
{
// Create a new Paragraph with the text "Hello World".
Paragraph p = document.InsertParagraph("Hello World.");
// Make this Paragraph flow right to left. Default is left to right.
p.Direction = Direction.RightToLeft;
// You don't need to manually set the text direction foreach Paragraph, you can just call this function.
document.SetDirection(Direction.RightToLeft);
// Save all changes made to this document.
document.Save();
Console.WriteLine("\tCreated: docs\\RightToLeft.docx\n");
}
}
/// <summary>
/// Creates a document with a Hyperlink, an Image and a Table.
/// </summary>
private static void HyperlinksImagesTables()
{
Console.WriteLine("\tHyperlinksImagesTables()");
// Create a document.
using (DocX document = DocX.Create(@"docs\HyperlinksImagesTables.docx"))
{
// Add a hyperlink into the document.
Hyperlink link = document.AddHyperlink("link", new Uri("http://www.google.com"));
// Add a Table into the document.
Table table = document.AddTable(2, 2);
table.Design = TableDesign.ColorfulGridAccent2;
table.Alignment = Alignment.center;
table.Rows[0].Cells[0].Paragraphs[0].Append("3");
table.Rows[0].Cells[1].Paragraphs[0].Append("1");
table.Rows[1].Cells[0].Paragraphs[0].Append("4");
table.Rows[1].Cells[1].Paragraphs[0].Append("1");
// Add an image into the document.
Novacode.Image image = document.AddImage(@"images\logo_template.png");
// Create a picture (A custom view of an Image).
Picture picture = image.CreatePicture();
picture.Rotation = 10;
picture.SetPictureShape(BasicShapes.cube);
// Insert a new Paragraph into the document.
Paragraph title = document.InsertParagraph().Append("Test").FontSize(20).Font(new FontFamily("Comic Sans MS"));
title.Alignment = Alignment.center;
// Insert a new Paragraph into the document.
Paragraph p1 = document.InsertParagraph();
// Append content to the Paragraph
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();
// Insert the Table after Paragraph 1.
p1.InsertTableAfterSelf(table);
// Insert a new Paragraph into the document.
Paragraph p2 = document.InsertParagraph();
// Append content to the Paragraph.
p2.AppendLine("Is it correct?");
// Save this document.
document.Save();
Console.WriteLine("\tCreated: docs\\HyperlinksImagesTables.docx\n");
}
}
private static void HeadersAndFooters()
{
Console.WriteLine("\tHeadersAndFooters()");
// Create a new document.
using (DocX document = DocX.Create(@"docs\HeadersAndFooters.docx"))
{
// Add Headers and Footers to this document.
document.AddHeaders();
document.AddFooters();
// Force the first page to have a different Header and Footer.
document.DifferentFirstPage = true;
// Force odd & even pages to have different Headers and Footers.
document.DifferentOddAndEvenPages = true;
// Get the first, odd and even Headers for this document.
Header header_first = document.Headers.first;
Header header_odd = document.Headers.odd;
Header header_even = document.Headers.even;
// Get the first, odd and even Footer for this document.
Footer footer_first = document.Footers.first;
Footer footer_odd = document.Footers.odd;
Footer footer_even = document.Footers.even;
// Insert a Paragraph into the first Header.
Paragraph p0 = header_first.InsertParagraph();
p0.Append("Hello First Header.").Bold();
// Insert a Paragraph into the odd Header.
Paragraph p1 = header_odd.InsertParagraph();
p1.Append("Hello Odd Header.").Bold();
// Insert a Paragraph into the even Header.
Paragraph p2 = header_even.InsertParagraph();
p2.Append("Hello Even Header.").Bold();
// Insert a Paragraph into the first Footer.
Paragraph p3 = footer_first.InsertParagraph();
p3.Append("Hello First Footer.").Bold();
// Insert a Paragraph into the odd Footer.
Paragraph p4 = footer_odd.InsertParagraph();
p4.Append("Hello Odd Footer.").Bold();
// Insert a Paragraph into the even Header.
Paragraph p5 = footer_even.InsertParagraph();
p5.Append("Hello Even Footer.").Bold();
// Insert a Paragraph into the document.
Paragraph p6 = document.InsertParagraph();
p6.AppendLine("Hello First page.");
// Create a second page to show that the first page has its own header and footer.
p6.InsertPageBreakAfterSelf();
// Insert a Paragraph after the page break.
Paragraph p7 = document.InsertParagraph();
p7.AppendLine("Hello Second page.");
// Create a third page to show that even and odd pages have different headers and footers.
p7.InsertPageBreakAfterSelf();
// Insert a Paragraph after the page break.
Paragraph p8 = document.InsertParagraph();
p8.AppendLine("Hello Third page.");
// Save all changes to this document.
document.Save();
Console.WriteLine("\tCreated: docs\\HeadersAndFooters.docx\n");
}// Release this document from memory.
}
private static void CreateInvoice()
{
Console.WriteLine("\tCreateInvoice()");
DocX g_document;
try
{
// Store a global reference to the loaded document.
g_document = DocX.Load(@"docs\InvoiceTemplate.docx");
/*
* The template 'InvoiceTemplate.docx' does exist,
* so lets use it to create an invoice for a factitious company
* called "The Happy Builder" and store a global reference it.
*/
g_document = CreateInvoiceFromTemplate(DocX.Load(@"docs\InvoiceTemplate.docx"));
// Save all changes made to this template as Invoice_The_Happy_Builder.docx (We don't want to replace InvoiceTemplate.docx).
g_document.SaveAs(@"docs\Invoice_The_Happy_Builder.docx");
Console.WriteLine("\tCreated: docs\\Invoice_The_Happy_Builder.docx\n");
}
// The template 'InvoiceTemplate.docx' does not exist, so create it.
catch (FileNotFoundException)
{
// Create and store a global reference to the template 'InvoiceTemplate.docx'.
g_document = CreateInvoiceTemplate();
// Save the template 'InvoiceTemplate.docx'.
g_document.Save();
Console.WriteLine("\tCreated: docs\\InvoiceTemplate.docx");
// The template exists now so re-call CreateInvoice().
CreateInvoice();
}
}
// Create an invoice for a factitious company called "The Happy Builder".
private static DocX CreateInvoiceFromTemplate(DocX template)
{
#region Logo
// A quick glance at the template shows us that the logo Paragraph is in row zero cell 1.
Paragraph logo_paragraph = template.Tables[0].Rows[0].Cells[1].Paragraphs[0];
// Remove the template Picture that is in this Paragraph.
logo_paragraph.Pictures[0].Remove();
// Add the Happy Builders logo to this document.
Novacode.Image logo = template.AddImage(@"images\logo_the_happy_builder.png");
// Insert the Happy Builders logo into this Paragraph.
logo_paragraph.InsertPicture(logo.CreatePicture());
#endregion
#region Set CustomProperty values
// Set the value of the custom property 'company_name'.
template.AddCustomProperty(new CustomProperty("company_name", "The Happy Builder"));
// Set the value of the custom property 'company_slogan'.
template.AddCustomProperty(new CustomProperty("company_slogan", "No job too small"));
// Set the value of the custom properties 'hired_company_address_line_one', 'hired_company_address_line_two' and 'hired_company_address_line_three'.
template.AddCustomProperty(new CustomProperty("hired_company_address_line_one", "The Crooked House,"));
template.AddCustomProperty(new CustomProperty("hired_company_address_line_two", "Dublin,"));
template.AddCustomProperty(new CustomProperty("hired_company_address_line_three", "12345"));
// Set the value of the custom property 'invoice_date'.
template.AddCustomProperty(new CustomProperty("invoice_date", DateTime.Today.Date.ToString("d")));
// Set the value of the custom property 'invoice_number'.
template.AddCustomProperty(new CustomProperty("invoice_number", 1));
// Set the value of the custom property 'hired_company_details_line_one' and 'hired_company_details_line_two'.
template.AddCustomProperty(new CustomProperty("hired_company_details_line_one", "Business Street, Dublin, 12345"));
template.AddCustomProperty(new CustomProperty("hired_company_details_line_two", "Phone: 012-345-6789, Fax: 012-345-6789, e-mail: support@thehappybuilder.com"));
#endregion
/*
* InvoiceTemplate.docx contains a blank Table,
* we want to replace this with a new Table that
* contains all of our invoice data.
*/
Table t = template.Tables[1];
Table invoice_table = CreateAndInsertInvoiceTableAfter(t, ref template);
t.Remove();
// Return the template now that it has been modified to hold all of our custom data.
return template;
}
// Create an invoice template.
private static DocX CreateInvoiceTemplate()
{
// Create a new document.
DocX document = DocX.Create(@"docs\InvoiceTemplate.docx");
// Create a table for layout purposes (This table will be invisible).
Table layout_table = document.InsertTable(2, 2);
layout_table.Design = TableDesign.TableNormal;
layout_table.AutoFit = AutoFit.Window;
// Dark formatting
Formatting dark_formatting = new Formatting();
dark_formatting.Bold = true;
dark_formatting.Size = 12;
dark_formatting.FontColor = Color.FromArgb(31, 73, 125);
// Light formatting
Formatting light_formatting = new Formatting();
light_formatting.Italic = true;
light_formatting.Size = 11;
light_formatting.FontColor = Color.FromArgb(79, 129, 189);
#region Company Name
// Get the upper left Paragraph in the layout_table.
Paragraph upper_left_paragraph = layout_table.Rows[0].Cells[0].Paragraphs[0];
// Create a custom property called company_name
CustomProperty company_name = new CustomProperty("company_name", "Company Name");
// Insert a field of type doc property (This will display the custom property 'company_name')
layout_table.Rows[0].Cells[0].Paragraphs[0].InsertDocProperty(company_name, f:dark_formatting);
// Force the next text insert to be on a new line.
upper_left_paragraph.InsertText("\n", false);
#endregion
#region Company Slogan
// Create a custom property called company_slogan
CustomProperty company_slogan = new CustomProperty("company_slogan", "Company slogan goes here.");
// Insert a field of type doc property (This will display the custom property 'company_slogan')
upper_left_paragraph.InsertDocProperty(company_slogan, f:light_formatting);
#endregion
#region Company Logo
// Get the upper right Paragraph in the layout_table.
Paragraph upper_right_paragraph = layout_table.Rows[0].Cells[1].Paragraphs[0];
// Add a template logo image to this document.
Novacode.Image logo = document.AddImage(@"images\logo_template.png");
// Insert this template logo into the upper right Paragraph.
upper_right_paragraph.InsertPicture(logo.CreatePicture());
upper_right_paragraph.Alignment = Alignment.right;
#endregion
// Custom properties cannot contain newlines, so the company address must be split into 3 custom properties.
#region Hired Company Address
// Create a custom property called company_address_line_one
CustomProperty hired_company_address_line_one = new CustomProperty("hired_company_address_line_one", "Street Address,");
// Get the lower left Paragraph in the layout_table.
Paragraph lower_left_paragraph = layout_table.Rows[1].Cells[0].Paragraphs[0];
lower_left_paragraph.InsertText("TO:\n", false, dark_formatting);
// Insert a field of type doc property (This will display the custom property 'hired_company_address_line_one')
lower_left_paragraph.InsertDocProperty(hired_company_address_line_one, f:light_formatting);
// Force the next text insert to be on a new line.
lower_left_paragraph.InsertText("\n", false);
// Create a custom property called company_address_line_two
CustomProperty hired_company_address_line_two = new CustomProperty("hired_company_address_line_two", "City,");
// Insert a field of type doc property (This will display the custom property 'hired_company_address_line_two')
lower_left_paragraph.InsertDocProperty(hired_company_address_line_two, f:light_formatting);
// Force the next text insert to be on a new line.
lower_left_paragraph.InsertText("\n", false);
// Create a custom property called company_address_line_two
CustomProperty hired_company_address_line_three = new CustomProperty("hired_company_address_line_three", "Zip Code");
// Insert a field of type doc property (This will display the custom property 'hired_company_address_line_three')
lower_left_paragraph.InsertDocProperty(hired_company_address_line_three, f:light_formatting);
#endregion
#region Date & Invoice number
// Get the lower right Paragraph from the layout table.
Paragraph lower_right_paragraph = layout_table.Rows[1].Cells[1].Paragraphs[0];
CustomProperty invoice_date = new CustomProperty("invoice_date", DateTime.Today.Date.ToString("d"));
lower_right_paragraph.InsertText("Date: ", false, dark_formatting);
lower_right_paragraph.InsertDocProperty(invoice_date, f:light_formatting);
CustomProperty invoice_number = new CustomProperty("invoice_number", 1);
lower_right_paragraph.InsertText("\nInvoice: ", false, dark_formatting);
lower_right_paragraph.InsertText("#", false, light_formatting);
lower_right_paragraph.InsertDocProperty(invoice_number, f:light_formatting);
lower_right_paragraph.Alignment = Alignment.right;
#endregion
// Insert an empty Paragraph between two Tables, so that they do not touch.
document.InsertParagraph(string.Empty, false);
// This table will hold all of the invoice data.
Table invoice_table = document.InsertTable(4, 4);
invoice_table.Design = TableDesign.LightShadingAccent1;
invoice_table.Alignment = Alignment.center;
// A nice thank you Paragraph.
Paragraph thankyou = document.InsertParagraph("\nThank you for your business, we hope to work with you again soon.", false, dark_formatting);
thankyou.Alignment = Alignment.center;
#region Hired company details
CustomProperty hired_company_details_line_one = new CustomProperty("hired_company_details_line_one", "Street Address, City, ZIP Code");
CustomProperty hired_company_details_line_two = new CustomProperty("hired_company_details_line_two", "Phone: 000-000-0000, Fax: 000-000-0000, e-mail: support@companyname.com");
Paragraph companyDetails = document.InsertParagraph(string.Empty, false);
companyDetails.InsertDocProperty(hired_company_details_line_one, f:light_formatting);
companyDetails.InsertText("\n", false);
companyDetails.InsertDocProperty(hired_company_details_line_two, f:light_formatting);
companyDetails.Alignment = Alignment.center;
#endregion
// Return the document now that it has been created.
return document;
}
private static Table CreateAndInsertInvoiceTableAfter(Table t, ref DocX document)
{
// Grab data from somewhere (Most likely a database)
DataTable data = GetDataFromDatabase();
/*
* The trick to replacing one Table with another,
* is to insert the new Table after the old one,
* and then remove the old one.
*/
Table invoice_table = t.InsertTableAfterSelf(data.Rows.Count + 1, data.Columns.Count);
invoice_table.Design = TableDesign.LightShadingAccent1;
#region Table title
Formatting table_title = new Formatting();
table_title.Bold = true;
invoice_table.Rows[0].Cells[0].Paragraphs[0].InsertText("Description", false, table_title);
invoice_table.Rows[0].Cells[0].Paragraphs[0].Alignment = Alignment.center;
invoice_table.Rows[0].Cells[1].Paragraphs[0].InsertText("Hours", false, table_title);
invoice_table.Rows[0].Cells[1].Paragraphs[0].Alignment = Alignment.center;
invoice_table.Rows[0].Cells[2].Paragraphs[0].InsertText("Rate", false, table_title);
invoice_table.Rows[0].Cells[2].Paragraphs[0].Alignment = Alignment.center;
invoice_table.Rows[0].Cells[3].Paragraphs[0].InsertText("Amount", false, table_title);
invoice_table.Rows[0].Cells[3].Paragraphs[0].Alignment = Alignment.center;
#endregion
// Loop through the rows in the Table and insert data from the data source.
for (int row = 1; row < invoice_table.RowCount; row++)
{
for (int cell = 0; cell < invoice_table.Rows[row].Cells.Count; cell++)
{
Paragraph cell_paragraph = invoice_table.Rows[row].Cells[cell].Paragraphs[0];
cell_paragraph.InsertText(data.Rows[row - 1].ItemArray[cell].ToString(), false);
}
}
// We want to fill in the total by suming the values from the amount coloumn.
Row total = invoice_table.InsertRow();
total.Cells[0].Paragraphs[0].InsertText("Total:", false);
Paragraph total_paragraph = total.Cells[invoice_table.ColumnCount - 1].Paragraphs[0];
/*
* Lots of people are scared of LINQ,
* so I will walk you through this line by line.
*
* invoice_table.Rows is an IEnumerable<Row> (i.e a collection of rows), with LINQ you can query collections.
* .Where(condition) is a filter that you want to apply to the items of this collection.
* My condition is that the index of the row must be greater than 0 and less than RowCount.
* .Select(something) lets you select something from each item in the filtered collection.
* I am selecting the Text value from each row, for example €100, then I am remove the €,
* and then I am parsing the remaining string as a double. This will return a collection of doubles,
* the final thing I do is call .Sum() on this collection which return one double the sum of all the doubles,
* this is the total.
*/
double totalCost =
(
invoice_table.Rows
.Where((row, index) => index > 0 && index < invoice_table.RowCount - 1)
.Select(row => double.Parse(row.Cells[row.Cells.Count() - 1].Paragraphs[0].Text.Remove(0, 1)))
).Sum();
// Insert the total calculated above using LINQ into the total Paragraph.
total_paragraph.InsertText(string.Format("€{0}", totalCost), false);
// Let the tables coloumns expand to fit its contents.
invoice_table.AutoFit = AutoFit.Contents;
// Center the Table
invoice_table.Alignment = Alignment.center;
// Return the invloce table now that it has been created.
return invoice_table;
}
// You need to rewrite this function to grab data from your data source.
private static DataTable GetDataFromDatabase()
{
DataTable table = new DataTable();
table.Columns.AddRange(new DataColumn[] { new DataColumn("Description"), new DataColumn("Hours"), new DataColumn("Rate"), new DataColumn("Amount") });
table.Rows.Add
(
"Install wooden doors (Kitchen, Sitting room, Dining room & Bedrooms)",
"5",
"€25",
string.Format("€{0}", 5 * 25)
);
table.Rows.Add
(
"Fit stairs",
"20",
"€30",
string.Format("€{0}", 20 * 30)
);
table.Rows.Add
(
"Replace Sitting room window",
"6",
"€50",
string.Format("€{0}", 6 * 50)
);
table.Rows.Add
(
"Build garden shed",
"10",
"€10",
string.Format("€{0}", 10 * 10)
);
table.Rows.Add
(
"Fit new lock on back door",
"0.5",
"€30",
string.Format("€{0}", 0.5 * 30)
);
table.Rows.Add
(
"Tile Kitchen floor",
"24",
"€25",
string.Format("€{0}", 24 * 25)
);
return table;
}
/// <summary>
/// Creates a simple document with the text Hello World.
/// </summary>
static void HelloWorld()
{
Console.WriteLine("\tHelloWorld()");
// Create a new document.
using (DocX document = DocX.Create(@"docs\Hello World.docx"))
{
// Insert a Paragraph into this document.
Paragraph p = document.InsertParagraph();
// Append some text and add formatting.
p.Append("Hello World")
.Font(new FontFamily("Times New Roman"))
.FontSize(32)
.Color(Color.Blue)
.Bold();
// Save this document to disk.
document.Save();
Console.WriteLine("\tCreated: docs\\Hello World.docx\n");
}
}
/// <summary>
/// Loads a document 'Input.docx' and writes the text 'Hello World' into the first imbedded Image.
/// This code creates the file 'Output.docx'.
/// </summary>
static void ProgrammaticallyManipulateImbeddedImage()
{
Console.WriteLine("\tProgrammaticallyManipulateImbeddedImage()");
const string str = "Hello World";
// Open the document Input.docx.
using (DocX document = DocX.Load(@"docs\Input.docx"))
{
// Make sure this document has at least one Image.
if (document.Images.Count() > 0)
{
Novacode.Image img = document.Images[0];
// Write "Hello World" into this Image.
Bitmap b = new Bitmap(img.GetStream(FileMode.Open, FileAccess.ReadWrite));
/*
* Get the Graphics object for this Bitmap.
* The Graphics object provides functions for drawing.
*/
Graphics g = Graphics.FromImage(b);
// Draw the string "Hello World".
g.DrawString
(
str,
new Font("Tahoma", 20),
Brushes.Blue,
new PointF(0, 0)
);
// Save this Bitmap back into the document using a Create\Write stream.
b.Save(img.GetStream(FileMode.Create, FileAccess.Write), ImageFormat.Png);
}
else
Console.WriteLine("The provided document contains no Images.");
// Save this document as Output.docx.
document.SaveAs(@"docs\Output.docx");
Console.WriteLine("\tCreated: docs\\Output.docx\n");
}
}
/// <summary>
/// For each of the documents in the folder 'docs\',
/// Replace the string a with the string b,
/// Do this in Parrallel accross many CPU cores.
/// </summary>
static void ReplaceTextParallel()
{
Console.WriteLine("\tReplaceTextParallel()\n");
const string a = "apple";
const string b = "pear";
// Directory containing many .docx documents.
DirectoryInfo di = new DirectoryInfo(@"docs\");
// Loop through each document in this specified direction.
Parallel.ForEach
(
di.GetFiles(),
currentFile =>
{
// Load the document.
using (DocX document = DocX.Load(currentFile.FullName))
{
// Replace text in this document.
document.ReplaceText(a, b);
// Save changes made to this document.
document.Save();
} // Release this document from memory.
}
);
Console.WriteLine("\tCreated: None\n");
}
}
}

+ 36
- 0
Examples/Properties/AssemblyInfo.cs Visa fil

@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Examples")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Examples")]
[assembly: AssemblyCopyright("Copyright © 2010")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("b18a3992-244e-430f-8ba2-cc3dd17971e6")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

Binär
Examples/bin/Debug/docs/Input.docx Visa fil


Binär
Examples/bin/Debug/images/logo_template.png Visa fil


Binär
Examples/bin/Debug/images/logo_the_happy_builder.png Visa fil


+ 441
- 35
UnitTests/UnitTest1.cs Visa fil

@@ -9,6 +9,7 @@ using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Xml.Linq;
using System.IO.Packaging;
namespace UnitTests
{
@@ -23,7 +24,6 @@ namespace UnitTests
string directory_documents;
string file_temp = "temp.docx";
const string package_part_document = "/word/document.xml";
public UnitTest1()
@@ -36,6 +36,194 @@ namespace UnitTests
directory_documents = String.Join("\\", steps) + "\\documents\\";
}
[TestMethod]
public void Test_EverybodyHasAHome_Loaded()
{
// Load a document.
using (DocX document = DocX.Load(directory_documents + "EverybodyHasAHome.docx"))
{
// Main document tests.
string document_xml_file = document.mainPart.Uri.OriginalString;
Assert.IsTrue(document.Paragraphs[0].mainPart.Uri.OriginalString.Equals(document_xml_file));
Assert.IsTrue(document.Tables[0].mainPart.Uri.OriginalString.Equals(document_xml_file));
Assert.IsTrue(document.Tables[0].Rows[0].mainPart.Uri.OriginalString.Equals(document_xml_file));
Assert.IsTrue(document.Tables[0].Rows[0].Cells[0].mainPart.Uri.OriginalString.Equals(document_xml_file));
Assert.IsTrue(document.Tables[0].Rows[0].Cells[0].Paragraphs[0].mainPart.Uri.OriginalString.Equals(document_xml_file));
// header first
Header header_first = document.Headers.first;
string header_first_xml_file = header_first.mainPart.Uri.OriginalString;
Assert.IsTrue(header_first.Paragraphs[0].mainPart.Uri.OriginalString.Equals(header_first_xml_file));
Assert.IsTrue(header_first.Tables[0].mainPart.Uri.OriginalString.Equals(header_first_xml_file));
Assert.IsTrue(header_first.Tables[0].Rows[0].mainPart.Uri.OriginalString.Equals(header_first_xml_file));
Assert.IsTrue(header_first.Tables[0].Rows[0].Cells[0].mainPart.Uri.OriginalString.Equals(header_first_xml_file));
Assert.IsTrue(header_first.Tables[0].Rows[0].Cells[0].Paragraphs[0].mainPart.Uri.OriginalString.Equals(header_first_xml_file));
// header odd
Header header_odd = document.Headers.odd;
string header_odd_xml_file = header_odd.mainPart.Uri.OriginalString;
Assert.IsTrue(header_odd.mainPart.Uri.OriginalString.Equals(header_odd_xml_file));
Assert.IsTrue(header_odd.Paragraphs[0].mainPart.Uri.OriginalString.Equals(header_odd_xml_file));
Assert.IsTrue(header_odd.Tables[0].mainPart.Uri.OriginalString.Equals(header_odd_xml_file));
Assert.IsTrue(header_odd.Tables[0].Rows[0].mainPart.Uri.OriginalString.Equals(header_odd_xml_file));
Assert.IsTrue(header_odd.Tables[0].Rows[0].Cells[0].mainPart.Uri.OriginalString.Equals(header_odd_xml_file));
Assert.IsTrue(header_odd.Tables[0].Rows[0].Cells[0].Paragraphs[0].mainPart.Uri.OriginalString.Equals(header_odd_xml_file));
// header even
Header header_even = document.Headers.even;
string header_even_xml_file = header_even.mainPart.Uri.OriginalString;
Assert.IsTrue(header_even.mainPart.Uri.OriginalString.Equals(header_even_xml_file));
Assert.IsTrue(header_even.Paragraphs[0].mainPart.Uri.OriginalString.Equals(header_even_xml_file));
Assert.IsTrue(header_even.Tables[0].mainPart.Uri.OriginalString.Equals(header_even_xml_file));
Assert.IsTrue(header_even.Tables[0].Rows[0].mainPart.Uri.OriginalString.Equals(header_even_xml_file));
Assert.IsTrue(header_even.Tables[0].Rows[0].Cells[0].mainPart.Uri.OriginalString.Equals(header_even_xml_file));
Assert.IsTrue(header_even.Tables[0].Rows[0].Cells[0].Paragraphs[0].mainPart.Uri.OriginalString.Equals(header_even_xml_file));
// footer first
Footer footer_first = document.Footers.first;
string footer_first_xml_file = footer_first.mainPart.Uri.OriginalString;
Assert.IsTrue(footer_first.mainPart.Uri.OriginalString.Equals(footer_first_xml_file));
Assert.IsTrue(footer_first.Paragraphs[0].mainPart.Uri.OriginalString.Equals(footer_first_xml_file));
Assert.IsTrue(footer_first.Tables[0].mainPart.Uri.OriginalString.Equals(footer_first_xml_file));
Assert.IsTrue(footer_first.Tables[0].Rows[0].mainPart.Uri.OriginalString.Equals(footer_first_xml_file));
Assert.IsTrue(footer_first.Tables[0].Rows[0].Cells[0].mainPart.Uri.OriginalString.Equals(footer_first_xml_file));
Assert.IsTrue(footer_first.Tables[0].Rows[0].Cells[0].Paragraphs[0].mainPart.Uri.OriginalString.Equals(footer_first_xml_file));
// footer odd
Footer footer_odd = document.Footers.odd;
string footer_odd_xml_file = footer_odd.mainPart.Uri.OriginalString;
Assert.IsTrue(footer_odd.mainPart.Uri.OriginalString.Equals(footer_odd_xml_file));
Assert.IsTrue(footer_odd.Paragraphs[0].mainPart.Uri.OriginalString.Equals(footer_odd_xml_file));
Assert.IsTrue(footer_odd.Tables[0].mainPart.Uri.OriginalString.Equals(footer_odd_xml_file));
Assert.IsTrue(footer_odd.Tables[0].Rows[0].mainPart.Uri.OriginalString.Equals(footer_odd_xml_file));
Assert.IsTrue(footer_odd.Tables[0].Rows[0].Cells[0].mainPart.Uri.OriginalString.Equals(footer_odd_xml_file));
Assert.IsTrue(footer_odd.Tables[0].Rows[0].Cells[0].Paragraphs[0].mainPart.Uri.OriginalString.Equals(footer_odd_xml_file));
// footer even
Footer footer_even = document.Footers.even;
string footer_even_xml_file = footer_even.mainPart.Uri.OriginalString;
Assert.IsTrue(footer_even.mainPart.Uri.OriginalString.Equals(footer_even_xml_file));
Assert.IsTrue(footer_even.Paragraphs[0].mainPart.Uri.OriginalString.Equals(footer_even_xml_file));
Assert.IsTrue(footer_even.Tables[0].mainPart.Uri.OriginalString.Equals(footer_even_xml_file));
Assert.IsTrue(footer_even.Tables[0].Rows[0].mainPart.Uri.OriginalString.Equals(footer_even_xml_file));
Assert.IsTrue(footer_even.Tables[0].Rows[0].Cells[0].mainPart.Uri.OriginalString.Equals(footer_even_xml_file));
Assert.IsTrue(footer_even.Tables[0].Rows[0].Cells[0].Paragraphs[0].mainPart.Uri.OriginalString.Equals(footer_even_xml_file));
}
}
[TestMethod]
public void Test_EverybodyHasAHome_Created()
{
// Create a new document.
using (DocX document = DocX.Create("Test.docx"))
{
// Create a Table.
Table t = document.AddTable(3, 3);
t.Design = TableDesign.TableGrid;
// Insert a Paragraph and a Table into the main document.
document.InsertParagraph();
document.InsertTable(t);
// Insert a Paragraph and a Table into every Header.
document.AddHeaders();
document.Headers.odd.InsertParagraph();
document.Headers.odd.InsertTable(t);
document.Headers.even.InsertParagraph();
document.Headers.even.InsertTable(t);
document.Headers.first.InsertParagraph();
document.Headers.first.InsertTable(t);
// Insert a Paragraph and a Table into every Footer.
document.AddFooters();
document.Footers.odd.InsertParagraph();
document.Footers.odd.InsertTable(t);
document.Footers.even.InsertParagraph();
document.Footers.even.InsertTable(t);
document.Footers.first.InsertParagraph();
document.Footers.first.InsertTable(t);
// Main document tests.
string document_xml_file = document.mainPart.Uri.OriginalString;
Assert.IsTrue(document.Paragraphs[0].mainPart.Uri.OriginalString.Equals(document_xml_file));
Assert.IsTrue(document.Tables[0].mainPart.Uri.OriginalString.Equals(document_xml_file));
Assert.IsTrue(document.Tables[0].Rows[0].mainPart.Uri.OriginalString.Equals(document_xml_file));
Assert.IsTrue(document.Tables[0].Rows[0].Cells[0].mainPart.Uri.OriginalString.Equals(document_xml_file));
Assert.IsTrue(document.Tables[0].Rows[0].Cells[0].Paragraphs[0].mainPart.Uri.OriginalString.Equals(document_xml_file));
// header first
Header header_first = document.Headers.first;
string header_first_xml_file = header_first.mainPart.Uri.OriginalString;
Assert.IsTrue(header_first.Paragraphs[0].mainPart.Uri.OriginalString.Equals(header_first_xml_file));
Assert.IsTrue(header_first.Tables[0].mainPart.Uri.OriginalString.Equals(header_first_xml_file));
Assert.IsTrue(header_first.Tables[0].Rows[0].mainPart.Uri.OriginalString.Equals(header_first_xml_file));
Assert.IsTrue(header_first.Tables[0].Rows[0].Cells[0].mainPart.Uri.OriginalString.Equals(header_first_xml_file));
Assert.IsTrue(header_first.Tables[0].Rows[0].Cells[0].Paragraphs[0].mainPart.Uri.OriginalString.Equals(header_first_xml_file));
// header odd
Header header_odd = document.Headers.odd;
string header_odd_xml_file = header_odd.mainPart.Uri.OriginalString;
Assert.IsTrue(header_odd.mainPart.Uri.OriginalString.Equals(header_odd_xml_file));
Assert.IsTrue(header_odd.Paragraphs[0].mainPart.Uri.OriginalString.Equals(header_odd_xml_file));
Assert.IsTrue(header_odd.Tables[0].mainPart.Uri.OriginalString.Equals(header_odd_xml_file));
Assert.IsTrue(header_odd.Tables[0].Rows[0].mainPart.Uri.OriginalString.Equals(header_odd_xml_file));
Assert.IsTrue(header_odd.Tables[0].Rows[0].Cells[0].mainPart.Uri.OriginalString.Equals(header_odd_xml_file));
Assert.IsTrue(header_odd.Tables[0].Rows[0].Cells[0].Paragraphs[0].mainPart.Uri.OriginalString.Equals(header_odd_xml_file));
// header even
Header header_even = document.Headers.even;
string header_even_xml_file = header_even.mainPart.Uri.OriginalString;
Assert.IsTrue(header_even.mainPart.Uri.OriginalString.Equals(header_even_xml_file));
Assert.IsTrue(header_even.Paragraphs[0].mainPart.Uri.OriginalString.Equals(header_even_xml_file));
Assert.IsTrue(header_even.Tables[0].mainPart.Uri.OriginalString.Equals(header_even_xml_file));
Assert.IsTrue(header_even.Tables[0].Rows[0].mainPart.Uri.OriginalString.Equals(header_even_xml_file));
Assert.IsTrue(header_even.Tables[0].Rows[0].Cells[0].mainPart.Uri.OriginalString.Equals(header_even_xml_file));
Assert.IsTrue(header_even.Tables[0].Rows[0].Cells[0].Paragraphs[0].mainPart.Uri.OriginalString.Equals(header_even_xml_file));
// footer first
Footer footer_first = document.Footers.first;
string footer_first_xml_file = footer_first.mainPart.Uri.OriginalString;
Assert.IsTrue(footer_first.mainPart.Uri.OriginalString.Equals(footer_first_xml_file));
Assert.IsTrue(footer_first.Paragraphs[0].mainPart.Uri.OriginalString.Equals(footer_first_xml_file));
Assert.IsTrue(footer_first.Tables[0].mainPart.Uri.OriginalString.Equals(footer_first_xml_file));
Assert.IsTrue(footer_first.Tables[0].Rows[0].mainPart.Uri.OriginalString.Equals(footer_first_xml_file));
Assert.IsTrue(footer_first.Tables[0].Rows[0].Cells[0].mainPart.Uri.OriginalString.Equals(footer_first_xml_file));
Assert.IsTrue(footer_first.Tables[0].Rows[0].Cells[0].Paragraphs[0].mainPart.Uri.OriginalString.Equals(footer_first_xml_file));
// footer odd
Footer footer_odd = document.Footers.odd;
string footer_odd_xml_file = footer_odd.mainPart.Uri.OriginalString;
Assert.IsTrue(footer_odd.mainPart.Uri.OriginalString.Equals(footer_odd_xml_file));
Assert.IsTrue(footer_odd.Paragraphs[0].mainPart.Uri.OriginalString.Equals(footer_odd_xml_file));
Assert.IsTrue(footer_odd.Tables[0].mainPart.Uri.OriginalString.Equals(footer_odd_xml_file));
Assert.IsTrue(footer_odd.Tables[0].Rows[0].mainPart.Uri.OriginalString.Equals(footer_odd_xml_file));
Assert.IsTrue(footer_odd.Tables[0].Rows[0].Cells[0].mainPart.Uri.OriginalString.Equals(footer_odd_xml_file));
Assert.IsTrue(footer_odd.Tables[0].Rows[0].Cells[0].Paragraphs[0].mainPart.Uri.OriginalString.Equals(footer_odd_xml_file));
// footer even
Footer footer_even = document.Footers.even;
string footer_even_xml_file = footer_even.mainPart.Uri.OriginalString;
Assert.IsTrue(footer_even.mainPart.Uri.OriginalString.Equals(footer_even_xml_file));
Assert.IsTrue(footer_even.Paragraphs[0].mainPart.Uri.OriginalString.Equals(footer_even_xml_file));
Assert.IsTrue(footer_even.Tables[0].mainPart.Uri.OriginalString.Equals(footer_even_xml_file));
Assert.IsTrue(footer_even.Tables[0].Rows[0].mainPart.Uri.OriginalString.Equals(footer_even_xml_file));
Assert.IsTrue(footer_even.Tables[0].Rows[0].Cells[0].mainPart.Uri.OriginalString.Equals(footer_even_xml_file));
Assert.IsTrue(footer_even.Tables[0].Rows[0].Cells[0].Paragraphs[0].mainPart.Uri.OriginalString.Equals(footer_even_xml_file));
}
}
[TestMethod]
public void Test_Document_AddImage_FromDisk()
{
@@ -166,29 +354,247 @@ namespace UnitTests
}
}
// Write the string "Hello World" into this Image.
private static void CoolExample(Novacode.Image i, Stream s, string str)
[TestMethod]
public void Test_Insert_Picture()
{
// Load test document.
using (DocX document = DocX.Create(directory_documents + "Test.docx"))
{
// Add Headers and Footers into this document.
document.AddHeaders();
document.AddFooters();
document.DifferentFirstPage = true;
document.DifferentOddAndEvenPages = true;
// Add an Image to this document.
Novacode.Image img = document.AddImage(directory_documents + "purple.png");
// Create a Picture from this Image.
Picture pic = img.CreatePicture();
// Main document.
Paragraph p0 = document.InsertParagraph("Hello");
p0.InsertPicture(pic, 3);
// Header first.
Paragraph p1 = document.Headers.first.InsertParagraph("----");
p1.InsertPicture(pic, 2);
// Header odd.
Paragraph p2 = document.Headers.odd.InsertParagraph("----");
p2.InsertPicture(pic, 2);
// Header even.
Paragraph p3 = document.Headers.even.InsertParagraph("----");
p3.InsertPicture(pic, 2);
// Footer first.
Paragraph p4 = document.Footers.first.InsertParagraph("----");
p4.InsertPicture(pic, 2);
// Footer odd.
Paragraph p5 = document.Footers.odd.InsertParagraph("----");
p5.InsertPicture(pic, 2);
// Footer even.
Paragraph p6 = document.Footers.even.InsertParagraph("----");
p6.InsertPicture(pic, 2);
// Save this document.
document.Save();
}
}
[TestMethod]
public void Test_Insert_Hyperlink()
{
// Write "Hello World" into this Image.
Bitmap b = new Bitmap(s);
/*
* Get the Graphics object for this Bitmap.
* The Graphics object provides functions for drawing.
*/
Graphics g = Graphics.FromImage(b);
// Draw the string "Hello World".
g.DrawString
(
str,
new Font("Tahoma", 20),
Brushes.Blue,
new PointF(0, 0)
);
// Save this Bitmap back into the document using a Create\Write stream.
b.Save(i.GetStream(FileMode.Create, FileAccess.Write), ImageFormat.Png);
// Load test document.
using (DocX document = DocX.Create(directory_documents + "Test.docx"))
{
// Add Headers and Footers into this document.
document.AddHeaders();
document.AddFooters();
document.DifferentFirstPage = true;
document.DifferentOddAndEvenPages = true;
// Add a Hyperlink into this document.
Hyperlink h = document.AddHyperlink("google", new Uri("http://www.google.com"));
// Main document.
Paragraph p0 = document.InsertParagraph("Hello");
p0.InsertHyperlink(h, 3);
// Header first.
Paragraph p1 = document.Headers.first.InsertParagraph("----");
p1.InsertHyperlink(h, 3);
// Header odd.
Paragraph p2 = document.Headers.odd.InsertParagraph("----");
p2.InsertHyperlink(h, 3);
// Header even.
Paragraph p3 = document.Headers.even.InsertParagraph("----");
p3.InsertHyperlink(h, 3);
// Footer first.
Paragraph p4 = document.Footers.first.InsertParagraph("----");
p4.InsertHyperlink(h, 3);
// Footer odd.
Paragraph p5 = document.Footers.odd.InsertParagraph("----");
p5.InsertHyperlink(h, 3);
// Footer even.
Paragraph p6 = document.Footers.even.InsertParagraph("----");
p6.InsertHyperlink(h, 3);
// Save this document.
document.Save();
}
}
[TestMethod]
public void Test_Append_Hyperlink()
{
// Load test document.
using (DocX document = DocX.Create(directory_documents + "Test.docx"))
{
// Add Headers and Footers into this document.
document.AddHeaders();
document.AddFooters();
document.DifferentFirstPage = true;
document.DifferentOddAndEvenPages = true;
// Add a Hyperlink to this document.
Hyperlink h = document.AddHyperlink("google", new Uri("http://www.google.com"));
// Main document.
Paragraph p0 = document.InsertParagraph("----");
p0.AppendHyperlink(h);
Assert.IsTrue(p0.Text == "----google");
// Header first.
Paragraph p1 = document.Headers.first.InsertParagraph("----");
p1.AppendHyperlink(h);
Assert.IsTrue(p1.Text == "----google");
// Header odd.
Paragraph p2 = document.Headers.odd.InsertParagraph("----");
p2.AppendHyperlink(h);
Assert.IsTrue(p2.Text == "----google");
// Header even.
Paragraph p3 = document.Headers.even.InsertParagraph("----");
p3.AppendHyperlink(h);
Assert.IsTrue(p3.Text == "----google");
// Footer first.
Paragraph p4 = document.Footers.first.InsertParagraph("----");
p4.AppendHyperlink(h);
Assert.IsTrue(p4.Text == "----google");
// Footer odd.
Paragraph p5 = document.Footers.odd.InsertParagraph("----");
p5.AppendHyperlink(h);
Assert.IsTrue(p5.Text == "----google");
// Footer even.
Paragraph p6 = document.Footers.even.InsertParagraph("----");
p6.AppendHyperlink(h);
Assert.IsTrue(p6.Text == "----google");
// Save the document.
document.Save();
}
}
[TestMethod]
public void Test_Append_Picture()
{
// Create test document.
using (DocX document = DocX.Create(directory_documents + "Test.docx"))
{
// Add Headers and Footers into this document.
document.AddHeaders();
document.AddFooters();
document.DifferentFirstPage = true;
document.DifferentOddAndEvenPages = true;
// Add an Image to this document.
Novacode.Image img = document.AddImage(directory_documents + "purple.png");
// Create a Picture from this Image.
Picture pic = img.CreatePicture();
// Main document.
Paragraph p0 = document.InsertParagraph();
p0.AppendPicture(pic);
// Header first.
Paragraph p1 = document.Headers.first.InsertParagraph();
p1.AppendPicture(pic);
// Header odd.
Paragraph p2 = document.Headers.odd.InsertParagraph();
p2.AppendPicture(pic);
// Header even.
Paragraph p3 = document.Headers.even.InsertParagraph();
p3.AppendPicture(pic);
// Footer first.
Paragraph p4 = document.Footers.first.InsertParagraph();
p4.AppendPicture(pic);
// Footer odd.
Paragraph p5 = document.Footers.odd.InsertParagraph();
p5.AppendPicture(pic);
// Footer even.
Paragraph p6 = document.Footers.even.InsertParagraph();
p6.AppendPicture(pic);
// Save the document.
document.Save();
}
}
[TestMethod]
public void Test_Move_Picture_Load()
{
// Load test document.
using (DocX document = DocX.Load(directory_documents + "MovePicture.docx"))
{
// Extract the first Picture from the first Paragraph.
Picture picture = document.Paragraphs.First().Pictures.First();
// Move it into the first Header.
Header header_first = document.Headers.first;
header_first.Paragraphs.First().AppendPicture(picture);
// Move it into the even Header.
Header header_even = document.Headers.even;
header_even.Paragraphs.First().AppendPicture(picture);
// Move it into the odd Header.
Header header_odd = document.Headers.odd;
header_odd.Paragraphs.First().AppendPicture(picture);
// Move it into the first Footer.
Footer footer_first = document.Footers.first;
footer_first.Paragraphs.First().AppendPicture(picture);
// Move it into the even Footer.
Footer footer_even = document.Footers.even;
footer_even.Paragraphs.First().AppendPicture(picture);
// Move it into the odd Footer.
Footer footer_odd = document.Footers.odd;
footer_odd.Paragraphs.First().AppendPicture(picture);
// Save this as MovedPicture.docx
document.SaveAs(directory_documents + "MovedPicture.docx");
}
}
[TestMethod]
@@ -202,23 +608,23 @@ namespace UnitTests
// Simple
Paragraph p1 = document.InsertParagraph("AC");
p1.InsertHyperlink(0, h); Assert.IsTrue(p1.Text == "linkAC");
p1.InsertHyperlink(p1.Text.Length, h); Assert.IsTrue(p1.Text == "linkAClink");
p1.InsertHyperlink(p1.Text.IndexOf("C"), h); Assert.IsTrue(p1.Text == "linkAlinkClink");
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");
// Difficult
Paragraph p2 = document.InsertParagraph("\tA\tC\t");
p2.InsertHyperlink(0, h); Assert.IsTrue(p2.Text == "link\tA\tC\t");
p2.InsertHyperlink(p2.Text.Length, h); Assert.IsTrue(p2.Text == "link\tA\tC\tlink");
p2.InsertHyperlink(p2.Text.IndexOf("C"), h); Assert.IsTrue(p2.Text == "link\tA\tlinkC\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");
// Contrived
// Add a contrived Hyperlink to this document.
Hyperlink h2 = document.AddHyperlink("\tlink\t", new Uri("http://www.google.com"));
Paragraph p3 = document.InsertParagraph("\tA\tC\t");
p3.InsertHyperlink(0, h2); Assert.IsTrue(p3.Text == "\tlink\t\tA\tC\t");
p3.InsertHyperlink(p3.Text.Length, h2); Assert.IsTrue(p3.Text == "\tlink\t\tA\tC\t\tlink\t");
p3.InsertHyperlink(p3.Text.IndexOf("C"), h2); Assert.IsTrue(p3.Text == "\tlink\t\tA\t\tlink\tC\t\tlink\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.IndexOf("C")); Assert.IsTrue(p3.Text == "\tlink\t\tA\t\tlink\tC\t\tlink\t");
}
}
@@ -233,9 +639,9 @@ namespace UnitTests
// Simple
Paragraph p1 = document.InsertParagraph("AC");
p1.InsertHyperlink(0, h); Assert.IsTrue(p1.Text == "linkAC");
p1.InsertHyperlink(p1.Text.Length, h); Assert.IsTrue(p1.Text == "linkAClink");
p1.InsertHyperlink(p1.Text.IndexOf("C"), h); Assert.IsTrue(p1.Text == "linkAlinkClink");
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");
// Try and remove a Hyperlink using a negative index.
// This should throw an exception.

+ 1
- 0
UnitTests/UnitTests.csproj Visa fil

@@ -66,6 +66,7 @@
<Compile Include="UnitTest1.cs" />
</ItemGroup>
<ItemGroup>
<None Include="documents\EverybodyHasAHome.docx" />
<None Include="documents\Images.docx" />
<None Include="documents\Paragraphs.docx" />
<None Include="documents\Tables.docx" />

Binär
UnitTests/documents/EverybodyHasAHome.docx Visa fil


Laddar…
Avbryt
Spara