Skip to content

Commit

Permalink
Updated documentation examples according to tutorials
Browse files Browse the repository at this point in the history
  • Loading branch information
vderyushev committed Jul 17, 2024
1 parent 6f8f1e9 commit d91f9ac
Show file tree
Hide file tree
Showing 11 changed files with 76 additions and 112 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -35,24 +35,23 @@ public void DocxToRtf()
//ExStart:OpenFromStream
//GistId:1d626c7186a318d22d022dc96dd91d55
// Read only access is enough for Aspose.Words to load a document.
Stream stream = File.OpenRead(MyDir + "Document.docx");

Document doc = new Document(stream);
// You can close the stream now, it is no longer needed because the document is in memory.
stream.Close();
Document doc;
using (Stream stream = File.OpenRead(MyDir + "Document.docx"))
doc = new Document(stream);
//ExEnd:OpenFromStream

// ... do something with the document.

// Convert the document to a different format and save to stream.
MemoryStream dstStream = new MemoryStream();
doc.Save(dstStream, SaveFormat.Rtf);

// Rewind the stream position back to zero so it is ready for the next reader.
dstStream.Position = 0;
using (MemoryStream dstStream = new MemoryStream())
{
doc.Save(dstStream, SaveFormat.Rtf);
// Rewind the stream position back to zero so it is ready for the next reader.
dstStream.Position = 0;

File.WriteAllBytes(ArtifactsDir + "BaseConversions.DocxToRtf.rtf", dstStream.ToArray());
}
//ExEnd:LoadAndSaveToStream

File.WriteAllBytes(ArtifactsDir + "BaseConversions.DocxToRtf.rtf", dstStream.ToArray());
}

[Test]
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
using System.IO;
using System.Text;
using Aspose.Words;
using Aspose.Words.Loading;
using Aspose.Words.Saving;
using NUnit.Framework;

Expand Down Expand Up @@ -53,26 +55,27 @@ public void ExportResources()
}

[Test]
public void ConvertMetafilesToEmfOrWmf()
public void ConvertMetafilesToPng()
{
//ExStart:ConvertMetafilesToEmfOrWmf
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.Write("Here is an image as is: ");
builder.InsertHtml(
@"<img src=""data:image/png;base64,
iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAABGdBTUEAALGP
C/xhBQAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9YGARc5KB0XV+IA
AAAddEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIFRoZSBHSU1Q72QlbgAAAF1J
REFUGNO9zL0NglAAxPEfdLTs4BZM4DIO4C7OwQg2JoQ9LE1exdlYvBBeZ7jq
ch9//q1uH4TLzw4d6+ErXMMcXuHWxId3KOETnnXXV6MJpcq2MLaI97CER3N0
vr4MkhoXe0rZigAAAABJRU5ErkJggg=="" alt=""Red dot"" />");

HtmlSaveOptions saveOptions = new HtmlSaveOptions { MetafileFormat = HtmlMetafileFormat.EmfOrWmf };

doc.Save(ArtifactsDir + "WorkingWithHtmlSaveOptions.ConvertMetafilesToEmfOrWmf.html", saveOptions);
//ExEnd:ConvertMetafilesToEmfOrWmf
//ExStart:ConvertMetafilesToPng
string html =
@"<html>
<svg xmlns='http://www.w3.org/2000/svg' width='500' height='40' viewBox='0 0 500 40'>
<text x='0' y='35' font-family='Verdana' font-size='35'>Hello world!</text>
</svg>
</html>";

// Use 'ConvertSvgToEmf' to turn back the legacy behavior
// where all SVG images loaded from an HTML document were converted to EMF.
// Now SVG images are loaded without conversion
// if the MS Word version specified in load options supports SVG images natively.
HtmlLoadOptions loadOptions = new HtmlLoadOptions { ConvertSvgToEmf = true };
Document doc = new Document(new MemoryStream(Encoding.UTF8.GetBytes(html)), loadOptions);

HtmlSaveOptions saveOptions = new HtmlSaveOptions { MetafileFormat = HtmlMetafileFormat.Png };

doc.Save(ArtifactsDir + "WorkingWithHtmlSaveOptions.ConvertMetafilesToPng.html", saveOptions);
//ExEnd:ConvertMetafilesToPng
}

[Test]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -169,11 +169,8 @@ public void EscapeUri()
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.InsertHyperlink("Testlink",
"https://www.google.com/search?q=%2Fthe%20test", false);
builder.Writeln();
builder.InsertHyperlink("https://www.google.com/search?q=%2Fthe%20test",
"https://www.google.com/search?q=%2Fthe%20test", false);
builder.InsertHyperlink("Testlink",
"https://www.google.com/search?q= aspose", false);

doc.Save(ArtifactsDir + "WorkingWithPdfSaveOptions.EscapeUri.pdf");
//ExEnd:EscapeUri
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Linq;
using System.Xml.Linq;
using Aspose.Words;
using Aspose.Words.MailMerging;
using NUnit.Framework;
Expand All @@ -27,8 +29,8 @@ public void SimpleMailMerge()

// Fill the fields in the document with user data.
doc.MailMerge.Execute(new string[] { "CustomerName", "Item", "Quantity" },
new object[] { "John Doe", "Hawaiian", "2" });

new object[] { "John Doe", "Hawaiian", "2" });

doc.Save(ArtifactsDir + "BaseOperations.SimpleMailMerge.docx");
//ExEnd:ExecuteSimpleMailMerge
}
Expand All @@ -39,6 +41,8 @@ public void UseIfElseMustache()
//ExStart:UseIfElseMustache
//GistId:544788f602e697802e313a641cedb9b8
Document doc = new Document(MyDir + "Mail merge destinations - Mustache syntax.docx");
doc.Sections.Clear();
doc.Save(ArtifactsDir + "output.docx");

doc.MailMerge.UseNonMergeFields = true;
doc.MailMerge.Execute(new[] { "GENDER" }, new object[] { "MALE" });
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ public void CreateBookmark()
options.OutlineOptions.BookmarksOutlineLevels.Add("My Bookmark", 1);
options.OutlineOptions.BookmarksOutlineLevels.Add("Nested Bookmark", 2);

doc.Save(ArtifactsDir + "WorkingWithBookmarks.CreateBookmark.pdf", options);
doc.Save(ArtifactsDir + "WorkingWithBookmarks.CreateBookmark.docx", options);
//ExEnd:CreateBookmark
}

Expand All @@ -175,58 +175,27 @@ public void ShowHideBookmarks()
//ExStart:ShowHideBookmarks
Document doc = new Document(MyDir + "Bookmarks.docx");

ShowHideBookmarkedContent(doc, "MyBookmark1", false);
ShowHideBookmarkedContent(doc, "MyBookmark1", true);

doc.Save(ArtifactsDir + "WorkingWithBookmarks.ShowHideBookmarks.docx");
//ExEnd:ShowHideBookmarks
}

//ExStart:ShowHideBookmarkedContent
public void ShowHideBookmarkedContent(Document doc, string bookmarkName, bool showHide)
public void ShowHideBookmarkedContent(Document doc, string bookmarkName, bool isHidden)
{
Bookmark bm = doc.Range.Bookmarks[bookmarkName];

DocumentBuilder builder = new DocumentBuilder(doc);
builder.MoveToDocumentEnd();

// {IF "{MERGEFIELD bookmark}" = "true" "" ""}
Field field = builder.InsertField("IF \"", null);
builder.MoveTo(field.Start.NextSibling);
builder.InsertField("MERGEFIELD " + bookmarkName + "", null);
builder.Write("\" = \"true\" ");
builder.Write("\"");
builder.Write("\"");
builder.Write(" \"\"");

Node currentNode = field.Start;
bool flag = true;
while (currentNode != null && flag)
Node currentNode = bm.BookmarkStart;
while (currentNode != null && currentNode.NodeType != NodeType.BookmarkEnd)
{
if (currentNode.NodeType == NodeType.Run)
if (currentNode.ToString(SaveFormat.Text).Trim() == "\"")
flag = false;

Node nextNode = currentNode.NextSibling;

bm.BookmarkStart.ParentNode.InsertBefore(currentNode, bm.BookmarkStart);
currentNode = nextNode;
}

Node endNode = bm.BookmarkEnd;
flag = true;
while (currentNode != null && flag)
{
if (currentNode.NodeType == NodeType.FieldEnd)
flag = false;

Node nextNode = currentNode.NextSibling;

bm.BookmarkEnd.ParentNode.InsertAfter(currentNode, endNode);
endNode = currentNode;
currentNode = nextNode;
{
Run run = currentNode as Run;
run.Font.Hidden = isHidden;
}
currentNode = currentNode.NextSibling;
}

doc.MailMerge.Execute(new[] { bookmarkName }, new object[] { showHide });
}
//ExEnd:ShowHideBookmarkedContent

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,6 @@ public void BuildTable()

Table table = builder.StartTable();
builder.InsertCell();
table.AutoFit(AutoFitBehavior.FixedColumnWidths);

builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
builder.Write("This is row 1 cell 1");
Expand All @@ -76,6 +75,8 @@ public void BuildTable()
builder.EndRow();
builder.EndTable();

table.AutoFit(AutoFitBehavior.FixedColumnWidths);

doc.Save(ArtifactsDir + "AddContentUsingDocumentBuilder.BuildTable.docx");
//ExEnd:BuildTable
}
Expand Down Expand Up @@ -196,14 +197,13 @@ public void InsertHyperlink()
//ExStart:InsertHyperlink
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.Write("Please make sure to visit ");
builder.Font.Color = Color.Blue;
builder.Font.Underline = Underline.Single;


builder.Font.Style = doc.Styles[StyleIdentifier.Hyperlink];
builder.InsertHyperlink("Aspose Website", "http://www.aspose.com", false);

builder.Font.ClearFormatting();

builder.Write(" for more information.");

doc.Save(ArtifactsDir + "AddContentUsingDocumentBuilder.InsertHyperlink.docx");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -192,8 +192,7 @@ public void InsertMergeFieldUsingDOM()
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Paragraph para = (Paragraph) doc.GetChildNodes(NodeType.Paragraph, true)[0];

Paragraph para = (Paragraph) doc.GetChild(NodeType.Paragraph, 0, true);
builder.MoveTo(para);

// We want to insert a merge field like this:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -189,8 +189,8 @@ public void MultipleFolders()
public void SetFontsFoldersSystemAndCustomFolder()
{
//ExStart:SetFontsFoldersSystemAndCustomFolder
Document doc = new Document(MyDir + "Rendering.docx");
Document doc = new Document(MyDir + "Rendering.docx");

FontSettings fontSettings = new FontSettings();
// Retrieve the array of environment-dependent font sources that are searched by default.
// For example this will contain a "Windows\Fonts\" source on a Windows machines.
Expand All @@ -199,15 +199,14 @@ public void SetFontsFoldersSystemAndCustomFolder()

// Add a new folder source which will instruct Aspose.Words to search the following folder for fonts.
FolderFontSource folderFontSource = new FolderFontSource("C:\\MyFonts\\", true);

// Add the custom folder which contains our fonts to the list of existing font sources.
fontSources.Add(folderFontSource);

FontSourceBase[] updatedFontSources = fontSources.ToArray();
fontSettings.SetFontsSources(updatedFontSources);
doc.FontSettings = fontSettings;
fontSettings.SetFontsSources(updatedFontSources);

doc.FontSettings = fontSettings;

doc.Save(ArtifactsDir + "WorkingWithFonts.SetFontsFoldersSystemAndCustomFolder.pdf");
//ExEnd:SetFontsFoldersSystemAndCustomFolder
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ public void LinkToPreviousHeaderFooter()
builder.Font.Size = 14;
builder.Write("Header for the first page.");

builder.MoveToDocumentEnd();
builder.MoveToDocumentEnd();
builder.InsertBreak(BreakType.SectionBreakNewPage);

Section currentSection = builder.CurrentSection;
Expand All @@ -173,7 +173,7 @@ public void LinkToPreviousHeaderFooter()

builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;
builder.Font.Name = "Arial";
builder.Font.Name = "Arial";
builder.Font.Size = 12;
builder.Write("New Header for the first page.");

Expand All @@ -184,8 +184,8 @@ public void LinkToPreviousHeaderFooter()
[Test]
public void SectionsWithDifferentHeaders()
{
//ExStart:SectionsWithDifferentHeaders
//GistId:1afca4d3da7cb4240fb91c3d93d8c30d
//ExStart:SectionsWithDifferentHeaders
//GistId:1afca4d3da7cb4240fb91c3d93d8c30d
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,11 +99,8 @@ public void Image()
DocumentBuilder builder = new DocumentBuilder();

// Insert image.
Shape shape = new Shape(builder.Document, ShapeType.Image);
shape.WrapType = WrapType.Inline;
shape.ImageData.SourceFullName = "/attachment/1456/pic001.png";
Shape shape = builder.InsertImage(ImagesDir + "Logo.jpg");
shape.ImageData.Title = "title";
builder.InsertNode(shape);
//ExEnd:Image
}

Expand Down Expand Up @@ -249,9 +246,7 @@ public void OrderedList()
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.ListFormat.ApplyBulletDefault();
builder.ListFormat.List.ListLevels[0].NumberFormat = $"{(char) 0}.";
builder.ListFormat.List.ListLevels[1].NumberFormat = $"{(char) 1}.";
builder.ListFormat.ApplyNumberDefault();

builder.Writeln("Item 1");
builder.Writeln("Item 2");
Expand All @@ -276,6 +271,8 @@ public void Table()
builder.InsertCell();
builder.Writeln("b");

builder.EndRow();

// Add the second row.
builder.InsertCell();
builder.Writeln("c");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -391,9 +391,6 @@ public void InsertTableDirectly()
row.RowFormat.AllowBreakAcrossPages = true;
table.AppendChild(row);

// We can now apply any auto fit settings.
table.AutoFit(AutoFitBehavior.FixedColumnWidths);

Cell cell = new Cell(doc);
cell.CellFormat.Shading.BackgroundPatternColor = Color.LightBlue;
cell.CellFormat.Width = 80;
Expand All @@ -407,7 +404,10 @@ public void InsertTableDirectly()
row.AppendChild(cell.Clone(false));
row.LastCell.AppendChild(new Paragraph(doc));
row.LastCell.FirstParagraph.AppendChild(new Run(doc, "Row 1, Cell 2 Text"));


// We can now apply any auto fit settings.
table.AutoFit(AutoFitBehavior.FixedColumnWidths);

doc.Save(ArtifactsDir + "WorkingWithTables.InsertTableDirectly.docx");
//ExEnd:InsertTableDirectly
}
Expand Down Expand Up @@ -623,7 +623,6 @@ public void SplitTable()
firstTable.ParentNode.InsertAfter(new Paragraph(doc), firstTable);

Row currentRow;

do
{
currentRow = firstTable.LastRow;
Expand Down Expand Up @@ -1048,8 +1047,6 @@ public void PreferredWidthSettings()
DocumentBuilder builder = new DocumentBuilder(doc);

// Insert a table row made up of three cells which have different preferred widths.
builder.StartTable();

// Insert an absolute sized cell.
builder.InsertCell();
builder.CellFormat.PreferredWidth = PreferredWidth.FromPoints(40);
Expand Down

0 comments on commit d91f9ac

Please sign in to comment.