How to Merge Multiple RTF Chapter (content) blocks into a PDF and build a TOC

Hi Nitin,

Thanks for your query. You can use Document.RemoveAllChildren() method to remove first blank page. Please see the code below.

1. The first page of the final .doc file is always blank.

<span style=“font-family: “Courier New”; color: rgb(43, 145, 175);” lang=“EN-GB”>Document<span style=“font-family: “Courier New”;” lang=“EN-GB”> FinalDoc = new
Document();<o:p></o:p>

FinalDoc.RemoveAllChildren();

Document docCoverPage = new Document();

DocumentBuilder _DocumentBuilder = new DocumentBuilder(docCoverPage);

_DocumentBuilder.InsertImage(@"image.jpg");

FinalDoc.AppendDocument(docCoverPage, ImportFormatMode.KeepSourceFormatting);

Document docTitlePage = RtfStringToDocument("RTF STring");

string txt = docTitlePage.Range.Text;

FinalDoc.AppendDocument(docTitlePage, ImportFormatMode.KeepSourceFormatting);

FinalDoc.Save(MyDir + "AsposeOut.doc", SaveFormat.Doc);


I am working over your second query (Hyperlinks [#Freedom to Be~http://freedomtobe.com.au#]) and will update you asap.

Thank you for your quick reply!

Now the TOC is not showing. I think this is because i did not specify chapter's title text. I actually hold this title text in another RTF string. I think i may need to set the STYLE of the title's text but I do not know how i should do this since this text is in RTF format. See the code below highlighted in yellow.

Document FinalDoc = newDocument();<?xml:namespace prefix = o />

FinalDoc.RemoveAllChildren();

Document docCoverPage = new Document();

DocumentBuilder _DocumentBuilder = new DocumentBuilder(docCoverPage);

_DocumentBuilder.InsertImage(@"image.jpg");

FinalDoc.AppendDocument(docCoverPage,ImportFormatMode.KeepSourceFormatting);

Document docTitlePage = RtfStringToDocument("RTF STring");

FinalDoc.AppendDocument(docTitlePage,ImportFormatMode.KeepSourceFormatting);

I want to insert a TOC after my title page here

Document docChapter1Title = RtfStringToDocument("chapter 1 title RTF STring");

// how do i set the style on docChapterTitle?

FinalDoc.AppendDocument(docChapter1Title,ImportFormatMode.KeepSourceFormatting);

Document docChapter1Content = RtfStringToDocument("chapter 1 content RTF STring");

FinalDoc.AppendDocument(docChapter1Content,ImportFormatMode.KeepSourceFormatting);

FinalDoc.Save(MyDir + "AsposeOut.doc", SaveFormat.Doc);

Hi Nitin,

Thanks for your query. It would be great if you please share your document/RTF along with code for investigation purposes.

Hi Nitin,

Please use the following code snippet for your your second query. Hope this helps you. Please read following documentation links for your kind reference. Please let us know if you have any more queries.

http://www.aspose.com/docs/display/wordsnet/Find+and+Replace+Overview
http://www.aspose.com/docs/display/wordsnet/How+to++Find+and+Highlight+Text

2. In each document, I have special tags like this
[#Freedom to Be~http://freedomtobe.com.au#]

<!–[if gte mso 10]>

/* Style Definitions */ table.MsoNormalTable {mso-style-name:"Table Normal"; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-priority:99; mso-style-qformat:yes; mso-style-parent:""; mso-padding-alt:0cm 5.4pt 0cm 5.4pt; mso-para-margin-top:10.0pt; mso-para-margin-right:0cm; mso-para-margin-bottom:10.0pt; mso-para-margin-left:47.9pt; line-height:115%; mso-pagination:widow-orphan; font-size:11.0pt; font-family:"Calibri","sans-serif"; mso-ascii-font-family:Calibri; mso-ascii-theme-font:minor-latin; mso-fareast-font-family:"Times New Roman"; mso-fareast-theme-font:minor-fareast; mso-hansi-font-family:Calibri; mso-hansi-theme-font:minor-latin; mso-bidi-font-family:Arial; mso-bidi-theme-font:minor-bidi;}

<![endif]–>


Document doc = new Document(MyDir + "in.docx");

DocumentBuilder builder = new DocumentBuilder(doc);

Regex regex = new Regex("\\[#", RegexOptions.IgnoreCase);

FindLinks obj = new FindLinks();

doc.Range.Replace(regex, obj, true);

String link = "";

Node endNode = null;

Node currentNode = null;

ArrayList removenodes = new ArrayList();

foreach (Run run in obj.nodes)

{

currentNode = run;

link += currentNode.Range.Text;

removenodes.Add(currentNode);

while (!currentNode.Range.Text.Contains("#]"))

{

currentNode = currentNode.NextPreOrder(doc);

removenodes.Add(currentNode);

link += currentNode.Range.Text;

}

String[] LinkNode = link.Split(new Char[] { '~' });

link = "";

builder.MoveTo(run);

builder.InsertHyperlink(LinkNode[0].Replace("[#", ""), LinkNode[1].Replace("#]", ""), false);

}

foreach (Node node in removenodes)

{

node.Remove();

}

doc.Save(MyDir + "AsposeOut.docx");

///

/// This is called during a replace operation each time a match is found.

/// This method appends a number to the match string and returns it as a replacement string.

///

public class FindLinks : IReplacingCallback

{

//Store Matched nodes

public ArrayList nodes = new ArrayList();

ReplaceAction IReplacingCallback.Replacing(ReplacingArgs e)

{

// This is a Run node that contains either the beginning or the complete match.

Node currentNode = e.MatchNode;

nodes.Add(currentNode);

return ReplaceAction.Skip;

}

}


Hi Tahir,

here’s a complete example of what I want to achieve.

The content (of a book) is held in my Object Model in a List of Objects -
and i want to convert this content into a final word document:

My Object Model objects are as follows…

Object 1: Filepath to an image (.jpg) file
Object 2: RTF Content (Title and some Copyright information)

Object 3: How We came to Mexico (This is JUST the first chapter’s title text and is in RTF format)
Object 4: RTF Content - This is the content that belongs to the above chapter
Object 5: A Word of Protest - This is the above Chapter’s Sub Section Title Text (In RTF format)
Object 6: RTF Content - Sub Section Content (In RTF format)

Object 7 : Mexico Traditions and Celebrations - This is the 2nd chapter’s Title text in RTF format
Object 8 : RTF Content - This is the content that belongs to the “Mexico Traditions and Celebrations” chapter
Object 9 : Tips for the Traveller in Mexico - This is the above Chapter’s Sub Section Title Text (In RTF format)
Object 10: RTF Content - Sub Section Content (In RTF format)


I would like the above Object model content to be converted into a word document with a TOC on the page after the title page.
Please see the attached word doc which is the final generated word doc I would like to see.

Please note that the Chapter’s header text (and also the Chapter’s sub section’s header text is in RTF format because there is font, size, justification etc formatting on the title text)


Hi Nitin,

Thanks for sharing the details. I am working over this query and will get back to you soon.

Hi Nitin,

Thanks for sharing the details. I have read your Object Model and suggest you following code snippet. You can get idea from following code snippet and use it in your application. Please also read following documentation links for your kind reference.

http://www.aspose.com/docs/display/wordsnet/How+to++Insert+a+Document+into+another+Document
http://www.aspose.com/docs/display/wordsnet/DocumentBuilder+Class
http://www.aspose.com/docs/display/wordsnet/DocumentBuilder+Members



<!–[if gte mso 9]>
<w:WordDocument>
<w:View>Normal</w:View>
<w:Zoom>0</w:Zoom>
<w:TrackMoves/>
<w:TrackFormatting/>
<w:HyphenationZone>21</w:HyphenationZone>
<w:PunctuationKerning/>
<w:ValidateAgainstSchemas/>
<w:SaveIfXMLInvalid>false</w:SaveIfXMLInvalid>
<w:IgnoreMixedContent>false</w:IgnoreMixedContent>
<w:AlwaysShowPlaceholderText>false</w:AlwaysShowPlaceholderText>
<w:DoNotPromoteQF/>
<w:LidThemeOther>PL</w:LidThemeOther>
<w:LidThemeAsian>X-NONE</w:LidThemeAsian>
<w:LidThemeComplexScript>AR-SA</w:LidThemeComplexScript>
<w:Compatibility>
<w:BreakWrappedTables/>
<w:SnapToGridInCell/>
<w:WrapTextWithPunct/>
<w:UseAsianBreakRules/>
<w:DontGrowAutofit/>
<w:SplitPgBreakAndParaMark/>
<w:DontVertAlignCellWithSp/>
<w:DontBreakConstrainedForcedTables/>
<w:DontVertAlignInTxbx/>
<w:Word11KerningPairs/>
<w:CachedColBalance/>
</w:Compatibility>
<w:BrowserLevel>MicrosoftInternetExplorer4</w:BrowserLevel>
<m:mathPr>
<m:mathFont m:val=“Cambria Math”/>
<m:brkBin m:val=“before”/>
<m:brkBinSub m:val=“–”/>
<m:smallFrac m:val=“off”/>
<m:dispDef/>
<m:lMargin m:val=“0”/>
<m:rMargin m:val=“0”/>
<m:defJc m:val=“centerGroup”/>
<m:wrapIndent m:val=“1440”/>
<m:intLim m:val=“subSup”/>
<m:naryLim m:val=“undOvr”/>
</m:mathPr></w:WordDocument>
<![endif]–><!–[if gte mso 10]>

/* Style Definitions */ table.MsoNormalTable {mso-style-name:"Table Normal"; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-priority:99; mso-style-qformat:yes; mso-style-parent:""; mso-padding-alt:0cm 5.4pt 0cm 5.4pt; mso-para-margin-top:10.0pt; mso-para-margin-right:0cm; mso-para-margin-bottom:10.0pt; mso-para-margin-left:47.9pt; line-height:115%; mso-pagination:widow-orphan; font-size:11.0pt; font-family:"Calibri","sans-serif"; mso-ascii-font-family:Calibri; mso-ascii-theme-font:minor-latin; mso-fareast-font-family:"Times New Roman"; mso-fareast-theme-font:minor-fareast; mso-hansi-font-family:Calibri; mso-hansi-theme-font:minor-latin; mso-bidi-font-family:Arial; mso-bidi-theme-font:minor-bidi;}

<![endif]–>

Document FinalDoc = new Document();

DocumentBuilder builder = new DocumentBuilder(FinalDoc);

builder.MoveTo(FinalDoc.FirstSection.Body.FirstParagraph);

//Object 1: Filepath to an image (.jpg) file

Shape image = builder.InsertImage("d:\\Chrysanthemum.jpg");

//Object 2: RTF Content (Title and some Copyright information)

Document docChapter1Title = RtfStringToDocument("chapter 1 title RTF STring");

Paragraph paragraph = builder.InsertParagraph();

InsertDocument(paragraph, docChapter1Title);

builder.Writeln("");

builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading1;

builder.Font.Color = Color.Blue;

builder.Writeln("Table of Contents ");

builder.InsertTableOfContents("\\o \"1-3\" \\h \\z \\u");

builder.Writeln("");

//Object 3: How We came to Mexico (This is JUST the first chapter's title text and is in RTF format)

builder.Writeln("How We Came to Mexico");

builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Normal;

builder.Font.Color = Color.Black;

//Object 4: RTF Content - This is the content that belongs to the above chapter

builder.Writeln(@"It started on the beaches, both in Ixtapa, on the Pacific coast, and Playa del Carmen on the Gulf. In the 90s we began to come down for ....");

builder.Writeln("");

builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading2;

builder.Font.Color = Color.Blue;

builder.Writeln("A Word of Protest");

builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Normal;

builder.Font.Color = Color.Black;

builder.Writeln(@"One of the points I made in the Conclusions section of my book on the expatriate experience, San Miguel de Allende: a Pla .....");

FinalDoc.UpdateFields();

FinalDoc.Save(MyDir + "AsposeOut.doc", SaveFormat.Doc);

public void InsertDocument(Node insertAfterNode, Document srcDoc)

{

// Make sure that the node is either a paragraph or table.

if ((!insertAfterNode.NodeType.Equals(NodeType.Paragraph)) &

(!insertAfterNode.NodeType.Equals(NodeType.Table)))

throw new ArgumentException("The destination node should be either a paragraph or table.");

// We will be inserting into the parent of the destination paragraph.

CompositeNode dstStory = insertAfterNode.ParentNode;

// This object will be translating styles and lists during the import.

NodeImporter importer = new NodeImporter(srcDoc, insertAfterNode.Document, ImportFormatMode.KeepSourceFormatting);

// Loop through all sections in the source document.

foreach (Section srcSection in srcDoc.Sections)

{

// Loop through all block level nodes (paragraphs and tables) in the body of the section.

foreach (Node srcNode in srcSection.Body)

{

// Let's skip the node if it is a last empty paragraph in a section.

if (srcNode.NodeType.Equals(NodeType.Paragraph))

{

Paragraph para = (Paragraph)srcNode;

if (para.IsEndOfSection && !para.HasChildNodes)

continue;

}

// This creates a clone of the node, suitable for insertion into the destination document.

Node newNode = importer.ImportNode(srcNode, true);

// Insert new node after the reference node.

dstStory.InsertAfter(newNode, insertAfterNode);

insertAfterNode = newNode;

}

}

}

Please let us know if you have any more queries.

Hi Tahir,

It did not work completely. Plus I think I need to clarify some more as your
understanding was not quite what i wanted.

ok, so here goes again…

The contents (of a book) is held in my Object Model in a List of Objects -
and i want to convert this content into a final word document:

My Object Model objects are as follows…

Object 1: Filepath to an image (.jpg) file - This must appear on the FIRST page and resize and fit the page.
forced page break here

Object 2: RTF Content (This is RTF content)
forced page break here

Object 3: RTF Content (This is title of the Chapter1 so this must be of style Heading 1 so that it will appear in the TOC)
Object 4: RTF Content - This is the RTF content (contains text and images) that belongs to the above chapter1

Object 5: RTF Content (This is a sub section title 1 under Chapter1 so this must be of style Heading 2 so that it will appear in the TOC under Chapter 1)
Object 6: RTF Content for section 1 - can contain text and images!

Object 5: RTF Content (This is a sub section title 2 under Chapter1 so this must be of style Heading 2 so that it will appear in the TOC under Chapter 1)
Object 6: RTF Content for section 2- can contain text and images!


** Please note that there are many many Chapters and Sub Sections in the whole book so some form
of iteration is invloved
for example
I could have the following chapter and sections

- Chapter 1
section 1a
section 1b
section 1c
- Chapter 2
section 2a
- Chapter 3
section 3a
section 3b




I would like the above Object model content to be converted into a word document with an automatically
generated TOC on the page AFTER the title page. i.e The Book Cover Image (page1), Title & Copyright (Page 2), TOC (Page 3), followed by all chapters and sections etc…

Please see the previously attached word doc which is the final generated word doc I would like to see.

Hi Nitin,

Please accept my apologies for late response. Thanks for sharing the details. We’re checking the shared scenario and will get back to you soon.

Hi Tahir,

No need to apologize. In fact I THANK YOU! You are doing an awsome job. My company and myself (of course) love your products! We have Aspose Total and it's well worth the money. Plus your support response is the very best!

I look forward to your reply for the above secanrio i have given. Plus also note that

FYI...
I am using Aspose Word version 9.5.0.0

Hi Nitin,

Thanks for your queries.You are using an old version of Aspose.Words. Please note that every new release of Aspose.Words comes up with some new features, enhancements in the existing features and bug fixes. Please use the latest version of Aspose.Words for .NET.

The code shared in my previous post is a sample code for your Object Model. You can get idea from following code snippet for your Object Model. As per your queries, you want to do followings:

  • Insert Table of Contents in document
  • Set the styles of Table of Contents
  • How to insert image into document and set its size
  • How to insert RTF contents into your document
You can get idea from following code snippet and modify it as per your Object Model. Hope this answers your query. Please let us know if you have any more queries.

Sample Code:

<span style=“font-family: “Courier New”; color: rgb(43, 145, 175);” lang=“EN-GB”>Document<span style=“font-family: “Courier New”;” lang=“EN-GB”> FinalDoc = new
Document();<o:p></o:p>

DocumentBuilder builder = new DocumentBuilder(FinalDoc);

builder.MoveTo(FinalDoc.FirstSection.Body.FirstParagraph);

//Object 1: Filepath to an image (.jpg) file - This must appear on the FIRST page and resize and fit the page.

//forced page break here

builder.MoveToParagraph(0, 0);

//Read image from file to Image object

Image img = Image.FromFile("d:\\Chrysanthemum.jpg");

double targetHeight;

double targetWidth;

CalculateImageSize(builder, img, out targetHeight, out targetWidth);

//Add the image to the document and set it's position and size

Shape shp = builder.InsertImage(img, targetWidth, targetHeight);

shp.WrapType = WrapType.Inline;

//Object 2: RTF Content (Title and some Copyright information)

Document docChapter1Title = RtfStringToDocument("chapter 1 title RTF STring");

Paragraph paragraph = builder.InsertParagraph();

InsertDocument(paragraph, docChapter1Title);

builder.InsertBreak(BreakType.PageBreak);

//Object 3: RTF Content (This is title of the Chapter1 so this must be of style Heading 1 so that it will appear in the TOC)

builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading1;

builder.Font.Color = Color.Blue;

builder.Writeln("Table of Contents ");

builder.InsertTableOfContents("\\o \"1-3\" \\h \\z \\u");

builder.Writeln("");

// Your Code......

//Object 4: RTF Content - This is the RTF content (contains text and images) that belongs to the above chapter1

Document Object4Doc = RtfStringToDocument("Object 4: RTF Content - This is the RTF content (contains text and images) that belongs to the above chapter1");

paragraph = builder.InsertParagraph();

InsertDocument(paragraph, Object4Doc);

//Your Code...

//Call the UpdateFields method before saving the document

FinalDoc.UpdateFields();

FinalDoc.Save(MyDir + "AsposeOut.doc", SaveFormat.Doc);

//

/// Calculates size of Image

///

/// DocumentBuilder is used to determine Height and Width of current Page

/// Original image

/// Height of the image

/// Width of the image

private void CalculateImageSize(DocumentBuilder builder, Image img, out double targetHeight, out double targetWidth)

{

//Calculate width and height of the page

PageSetup ps = builder.CurrentSection.PageSetup;

targetHeight = ps.PageHeight - ps.TopMargin - ps.BottomMargin;

targetWidth = ps.PageWidth - ps.LeftMargin - ps.RightMargin;

//Get size of an image

double imgHeight = ConvertUtil.PixelToPoint(img.Height);

double imgWidth = ConvertUtil.PixelToPoint(img.Width);

if (imgHeight < targetHeight && imgWidth < targetWidth)

{

targetHeight = imgHeight;

targetWidth = imgWidth;

}

else

{

//Calculate size of an image in the document

double ratioWidth = imgWidth / targetWidth;

double ratioHeight = imgHeight / targetHeight;

if (ratioWidth > ratioHeight)

targetHeight = (targetHeight * (ratioHeight / ratioWidth));

else

targetHeight = (targetWidth * (ratioWidth / ratioHeight));

}

}


Please read following forum link for your kind reference.

https://forum.aspose.com/t/52359


Hi Tahir,
The code is still not producing the correct .doc file. Please see the attached doc files.
lion-Generated-By-Aspose.doc - created by aspose word
Lion-Good-Final.doc - Manually created by me. This is what i want the final .doc to look like.

here’s the C# code method I am using:

Document FinalDoc = new Document();
DocumentBuilder builder = new DocumentBuilder(FinalDoc);

builder.MoveTo(FinalDoc.FirstSection.Body.FirstParagraph);

builder.MoveToParagraph(0, 0);

// =============================================
// COVER PAGE
// =============================================
// Read image from file to Image object
Image img = Image.FromFile(@_EBookMaker.CoverPage.CoverPageImageFileName);

double targetHeight;
double targetWidth;
AsposeHelperManager.CalculateImageSize(builder, img, out targetHeight, out targetWidth);

//Add the image to the document and set it’s position and size
Shape shp = builder.InsertImage(img, targetWidth, targetHeight);
shp.WrapType = WrapType.Inline;
builder.InsertBreak(BreakType.PageBreak);


// =============================================
// TITLE PAGE AND COPYRIGHT INFO
// =============================================
//Object 2: RTF Content (Title and some Copyright information)
Document docTitlePage = AsposeHelperManager.RtfStringToDocument(@_EBookMaker.TitlePage.RtfContent);//“chapter 1 title RTF STring”);
Paragraph paragraph = builder.InsertParagraph();
AsposeHelperManager.InsertDocument(paragraph, docTitlePage);
builder.InsertBreak(BreakType.PageBreak);


// =============================================
// TOC
// =============================================
builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading1;
builder.Font.Color = Color.Blue;
builder.Writeln(“Table of Contents “);
builder.InsertTableOfContents(”\o “1-3” \h \z \u”);
builder.InsertBreak(BreakType.PageBreak);


// =============================================
// NOW PROCESS ALL CHAPTERS …
// =============================================
foreach (EBookSectionChapter chapter in _EBookMaker.ChapterList)
{
// Chapter Title
Document docChapterTitle = AsposeHelperManager.RtfStringToDocument(chapter.TitleAsRtf);
builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading1;
builder.Font.Color = Color.Black;
Paragraph ChapterTitleParagraph = builder.InsertParagraph();
AsposeHelperManager.InsertDocument(ChapterTitleParagraph, docChapterTitle);

// Chapter Content
Document docChapterContent = AsposeHelperManager.RtfStringToDocument(chapter.RtfContent);
builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Normal;
builder.Font.Color = Color.Black;
Paragraph ChapterContentParagraph = builder.InsertParagraph();
AsposeHelperManager.InsertDocument(ChapterContentParagraph, docChapterContent);

builder.Writeln("");

// =============================================
// PROCESS ALL SECTIONS …
// =============================================
foreach (EBookSectionChapterSection section in chapter.EBookSectionChapterSectionList)
{
// Section Title
Document docSectionTitle = AsposeHelperManager.RtfStringToDocument(chapter.TitleAsRtf);
builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading2;
builder.Font.Color = Color.Black;
Paragraph SectionTitleParagraph = builder.InsertParagraph();
AsposeHelperManager.InsertDocument(SectionTitleParagraph, docSectionTitle);

// Section Content
Document docSectionContent = AsposeHelperManager.RtfStringToDocument(chapter.RtfContent);
builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Normal;
builder.Font.Color = Color.Black;
Paragraph SectionContentParagraph = builder.InsertParagraph();
AsposeHelperManager.InsertDocument(SectionContentParagraph, docSectionContent);

builder.Writeln("");
}
}

// =============================================
// REFRESH THE TOC …
// =============================================
FinalDoc.UpdateFields();

FinalDoc.Save(OutputFilePath, SaveFormat.Doc);

Hi Nitin,

Thanks for sharing the document. I have modfied the code according to the shared document. Please find the output document in attachment. You can use the same code in your object model. Hope this helps you. Please let us know if you have any more queries.

Document FinalDoc = new Document();

DocumentBuilder builder = new DocumentBuilder(FinalDoc);

Style Heading1 = FinalDoc.Styles[StyleIdentifier.Heading1];

Style Heading2 = FinalDoc.Styles[StyleIdentifier.Heading2];

Heading1.Font.Name = "Cambria";

Heading1.Font.Size = 14;

Heading1.Font.Bold = true;

Heading1.Font.Color = Color.DarkBlue;

Heading2.Font.Name = "Cambria";

Heading2.Font.Size = 13;

Heading2.Font.Bold = true;

Heading2.Font.Color = Color.DarkBlue;

builder.MoveTo(FinalDoc.FirstSection.Body.FirstParagraph);

builder.MoveToParagraph(0, 0);

builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;

// =============================================

// COVER PAGE

// =============================================

// Read image from file to Image object

Image img = Image.FromFile(MyDir + "Lion.png");

//Add the image to the document and set it's position and size

Shape shp = builder.InsertImage(img);

shp.WrapType = WrapType.Inline;

//builder.InsertBreak(BreakType.PageBreak);

Paragraph para = builder.InsertParagraph();

para.AppendChild(new Run(FinalDoc, ""));

// =============================================

// TITLE PAGE AND COPYRIGHT INFO

// =============================================

//Object 2: RTF Content (Title and some Copyright information)

//Document docTitlePage = AsposeHelperManager.RtfStringToDocument(@_EBookMaker.TitlePage.RtfContent);//"chapter 1 title RTF STring");

String str = @"This is the Title and Copyright Page. This should be right after the cover image page

Copyright © 2012 by Joe Blog. All rights reserved worldwide. part of this publication may be replicated, redistributed, or given away in any form without the prior written consent of the author/publisher or the terms relayed to you herein.

Joe Blog, Book Wizard Group,

1023 King Street, Toronto, M6W 2K5, Canada

www.wizardGroup.com

";

Document docTitlePage = RtfStringToDocument(str);//"chapter 1 title RTF STring");

foreach (Paragraph para2 in docTitlePage.GetChildNodes(NodeType.Paragraph, true))

{

para2.ParagraphFormat.Alignment = ParagraphAlignment.Center;

}

InsertDocument(para, docTitlePage);

builder.MoveTo(para);

builder.InsertBreak(BreakType.PageBreak);

// =============================================

// TOC

// =============================================

builder.MoveToDocumentEnd();

builder.InsertBreak(BreakType.PageBreak);

builder.ParagraphFormat.ClearFormatting();

builder.Font.Color = Color.DarkBlue;

builder.Font.Name = "Cambria";

builder.Font.Size = 14;

builder.Writeln("Contents ");

builder.Font.Color = Color.Black;

builder.Font.Name = "Calibri";

builder.Font.Size = 11;

builder.InsertTableOfContents("\\o \"1-3\" \\h \\z \\u");

builder.InsertBreak(BreakType.PageBreak);

builder.Font.ClearFormatting();

builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading1;

builder.Writeln("Chapter 1");

shp = builder.InsertImage(img);

shp.WrapType = WrapType.Inline;

builder.Writeln("");

str = @"This is Chapter 1 content...

Africa's lions of the Serengeti Park. This is a amazing peek into the lives of a tribe of lions that live and hunt on the vast plains of the Serengeti National Park.

";

builder.ParagraphFormat.ClearFormatting();

builder.Font.Name = "Arial";

builder.Font.Size = 12;

builder.Font.Color = Color.Black;

builder.Font.Bold = false;

builder.ParagraphFormat.Alignment = ParagraphAlignment.Left;

builder.Writeln(str);

builder.Font.ClearFormatting();

builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading2;

builder.Writeln("Introduction");

builder.Writeln("");

str = @"This is Section 1 of Chapter 1 content...

Lions are the only cats that live in groups, which are called prides. Prides are family units that may include up to three males, a dozen or so females, and their young. All of a pride's lionesses are related, and female cubs typically stay with the group as they age. Young males eventually leave and establish their own prides by taking over a group headed by another male.

";

builder.ParagraphFormat.ClearFormatting();

builder.Font.Name = "Arial";

builder.Font.Size = 12;

builder.Font.Color = Color.Black;

builder.Font.Bold = false;

builder.ParagraphFormat.Alignment = ParagraphAlignment.Left;

builder.Writeln(str);

// Your code................

// Your code................

// Your code................

FinalDoc.UpdateFields();

FinalDoc.Save(MyDir + "AsposeOut.doc", SaveFormat.Doc);

Hi Tahir,
Thanks for the code. Just one question though.
I do not know what is in the chapter content. SOme may have many images and text, and some may only have text. All the content however is held in RTF format.
So how would the code work then?


Hi Nitin,

Thanks for your query. You can use the same following code snippet to insert RTF contents into your document by using RtfStringToDocument and InsertDocument methods.

Document rtfDoc = RtfStringToDocument("RTF contents .....");

/// Node in the destination document after which the content

InsertDocument(insertAfterNode, rtfDoc);

//You can also laod RTF document by using Document class

//Document rtfDoc = new Document("in.rtf")


Please read following documentation links for your kind reference.

http://www.aspose.com/docs/display/wordsnet/How+to++Insert+a+Document+into+another+Document

http://www.aspose.com/docs/display/wordsnet/DocumentBuilder+Class

http://www.aspose.com/docs/display/wordsnet/DocumentBuilder+Members

Hi Tahir,

Thank for the code. I kind of got it to work but not 100%. I have 3 more requirements.

1. My Chapter titles are held in my object as RTF - this is because the title can have font, style, justification on it. So how do I take that Title now (in RTF format) and convert that to a style of Heading1?

2. I have special tags inside my content like this: []

how do I convert this into a bookmark?

3. I also have a special tag which is a link to a bookmark

like this: [>jump to b1~b1<]

The format is: [>Display Text~Bookmark<]

How do i convert this to a link to a bookmark called "b1"

so the link in the final word doc would look like this: jump to b1

which links to the b1 bookmark

Hi Nitin,


Please accept my apologies for late response. I am working over your query and will get back to you shortly.

Hi Nitin,


Thanks for your queries.

nitin.mistry@bell.ca:
1. My Chapter titles are held in my object as RTF - this is because the title can have font, style, justification on it. So how do I take that Title now (in RTF format) and convert that to a style of Heading1?

Please use the ParagraphFormat.Style property to set the style as Heading1.

<span lang=“EN-GB” style=“font-family:“Courier New”;color:#2B91AF;mso-ansi-language:EN-GB;
mso-no-proof:yes”>Document<span lang=“EN-GB” style=“font-family:“Courier New”;
mso-ansi-language:EN-GB;mso-no-proof:yes”> rtfDoc = RtfStringToDocument(“RTF Title contents …”);<o:p></o:p>

Aspose.Words.Style h1style = rtfDoc.Styles[StyleIdentifier.Heading1];

// Loop through every run node.

foreach (Paragraph para in rtfDoc.GetChildNodes(NodeType.Paragraph, true))

{

para.ParagraphFormat.Style = h1style;

}

nitin.mistry@bell.ca:

2. I have special tags inside my content like this: []

Please read following documentation links for your kind reference. You can use IReplacingCallback Interface, find such special tags and insert bookmark at that position.

http://www.aspose.com/docs/display/wordsnet/Bookmarks+in+Aspose.Words
http://www.aspose.com/docs/display/wordsnet/Find+and+Replace+Overview
http://www.aspose.com/docs/display/wordsnet/How+to++Find+and+Highlight+Text

nitin.mistry@bell.ca:

3. I also have a special tag which is a link to a bookmark
like this: [>jump to b1~b1<]
The format is: [>Display Text~Bookmark<]

Please check my reply at following forum link.
https://forum.aspose.com/t/29656

Hi Tahir,

I saw the code at that link, but that code is for external links.
These are internal bookmarks and links to bookmark.

So this is what i want to do.
I have a WORD document with the following my special custom tags as follows

[] - this represents a bookmark ‘b1’

[>jump~b1<] - this represents a link to the b1 bookmark (where ‘jump’ is the link’s display text.

How do i convert these tags into proper bookmarks and link to bookmarks.
I have many in a typical word document.

Thanks





Hi Nitin,

Please accept my apologies for late response.

Thanks for your inquiry. DocumentBuilder.InsertHyperlink method inserts a hyperlink into the document. Please use third parameter value as “true” as shown in following code snippet.

Third parameter : isBookmark True if the previous parameter is a name of a bookmark inside the document; false is the previous parameter is a URL.

Please use following code snippet for your kind reference. I have attached the input and output documents with this post. Please let us know if you have any more queries.

Document doc = new Document(MyDir + “in.docx”);

DocumentBuilder builder = new DocumentBuilder(doc);

Regex regex = new Regex("\\[>", RegexOptions.IgnoreCase);

FindLinks obj = new FindLinks();

doc.Range.Replace(regex, obj, true);

String link = "";

Node endNode = null;

Node currentNode = null;

ArrayList removenodes = new ArrayList();

foreach (Run run in obj.nodes)

{

currentNode = run;

link += currentNode.Range.Text;

removenodes.Add(currentNode);

while (!currentNode.Range.Text.Contains("<]"))

{

currentNode = currentNode.NextPreOrder(doc);

removenodes.Add(currentNode);

link += currentNode.Range.Text;

}

String[] LinkNode = link.Split(new Char[] { '~' });

link = "";

builder.MoveTo(run);

// Specify font formatting for the hyperlink.

builder.Font.Color = Color.Blue;

builder.Font.Underline = Underline.Single;

builder.InsertHyperlink(LinkNode[0].Replace("[>", ""), LinkNode[1].Replace("<]", ""), true);

// Revert to default formatting.

builder.Font.ClearFormatting();

}

foreach (Node node in removenodes)

{

node.Remove();

}

doc.Save(MyDir + "AsposeOut.docx");

///

/// This is called during a replace operation each time a match is found.

/// This method appends a number to the match string and returns it as a replacement string.

///

public class FindLinks : IReplacingCallback

{

//Store Matched nodes

public ArrayList nodes = new ArrayList();

ReplaceAction IReplacingCallback.Replacing(ReplacingArgs e)

{

// This is a Run node that contains either the beginning or the complete match.

Node currentNode = e.MatchNode;

nodes.Add(currentNode);

return ReplaceAction.Skip;

}

}