本文整理汇总了C#中DocumentBuilder.MoveTo方法的典型用法代码示例。如果您正苦于以下问题:C# DocumentBuilder.MoveTo方法的具体用法?C# DocumentBuilder.MoveTo怎么用?C# DocumentBuilder.MoveTo使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类DocumentBuilder
的用法示例。
在下文中一共展示了DocumentBuilder.MoveTo方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: AddImageToPage
/// <summary>
/// Adds an image to a page using the supplied paragraph.
/// </summary>
/// <param name="para">The paragraph to an an image to.</param>
/// <param name="page">The page number the paragraph appears on.</param>
public static void AddImageToPage(Paragraph para, int page)
{
Document doc = (Document)para.Document;
DocumentBuilder builder = new DocumentBuilder(doc);
builder.MoveTo(para);
// Add a logo to the top left of the page. The image is placed infront of all other text.
Shape shape = builder.InsertImage(gDataDir + "Aspose Logo.png", RelativeHorizontalPosition.Page, 60,
RelativeVerticalPosition.Page, 60, -1, -1, WrapType.None);
// Add a textbox next to the image which contains some text consisting of the page number.
Shape textBox = new Shape(doc, ShapeType.TextBox);
// We want a floating shape relative to the page.
textBox.WrapType = WrapType.None;
textBox.RelativeHorizontalPosition = RelativeHorizontalPosition.Page;
textBox.RelativeVerticalPosition = RelativeVerticalPosition.Page;
// Set the textbox position.
textBox.Height = 30;
textBox.Width = 200;
textBox.Left = 150;
textBox.Top = 80;
// Add the textbox and set text.
textBox.AppendChild(new Paragraph(doc));
builder.InsertNode(textBox);
builder.MoveTo(textBox.FirstChild);
builder.Writeln("This is a custom note for page " + page);
}
示例2: Main
public static void Main()
{
// The path to the documents directory.
string dataDir = Path.GetFullPath("../../../Data/");
//ExStart
//ExFor:DocumentBuilder.InsertField(string)
//ExId:DocumentBuilderInsertNestedFields
//ExSummary:Demonstrates how to insert fields nested within another field using DocumentBuilder.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Insert a few page breaks (just for testing)
for (int i = 0; i < 5; i++)
builder.InsertBreak(BreakType.PageBreak);
// Move the DocumentBuilder cursor into the primary footer.
builder.MoveToHeaderFooter(HeaderFooterType.FooterPrimary);
// We want to insert a field like this:
// { IF {PAGE} <> {NUMPAGES} "See Next Page" "Last Page" }
Field field = builder.InsertField(@"IF ");
builder.MoveTo(field.Separator);
builder.InsertField("PAGE");
builder.Write(" <> ");
builder.InsertField("NUMPAGES");
builder.Write(" \"See Next Page\" \"Last Page\" ");
// Finally update the outer field to recalcaluate the final value. Doing this will automatically update
// the inner fields at the same time.
field.Update();
doc.Save(dataDir + "InsertNestedFields Out.docx");
//ExEnd
}
示例3: Main
static void Main(string[] args)
{
// Check for license and apply if exists
string licenseFile = AppDomain.CurrentDomain.BaseDirectory + "Aspose.Words.lic";
if (File.Exists(licenseFile))
{
// Apply Aspose.Words API License
Aspose.Words.License license = new Aspose.Words.License();
// Place license file in Bin/Debug/ Folder
license.SetLicense("Aspose.Words.lic");
}
Document doc = new Document("../../data/document.doc");
DocumentBuilder builder = new DocumentBuilder(doc);
//Shows how to access the current node in a document builder.
Node curNode = builder.CurrentNode;
Paragraph curParagraph = builder.CurrentParagraph;
// Shows how to move a cursor position to a specified node.
builder.MoveTo(doc.FirstSection.Body.LastParagraph);
// Shows how to move a cursor position to the beginning or end of a document.
builder.MoveToDocumentEnd();
builder.Writeln("This is the end of the document.");
builder.MoveToDocumentStart();
builder.Writeln("This is the beginning of the document.");
doc.Save("outputDocument.doc");
}
示例4: Run
public static void Run()
{
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithFields();
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Insert a few page breaks (just for testing)
for (int i = 0; i < 5; i++)
builder.InsertBreak(BreakType.PageBreak);
// Move the DocumentBuilder cursor into the primary footer.
builder.MoveToHeaderFooter(HeaderFooterType.FooterPrimary);
// We want to insert a field like this:
// { IF {PAGE} <> {NUMPAGES} "See Next Page" "Last Page" }
Field field = builder.InsertField(@"IF ");
builder.MoveTo(field.Separator);
builder.InsertField("PAGE");
builder.Write(" <> ");
builder.InsertField("NUMPAGES");
builder.Write(" \"See Next Page\" \"Last Page\" ");
// Finally update the outer field to recalcaluate the final value. Doing this will automatically update
// the inner fields at the same time.
field.Update();
doc.Save(dataDir + "InsertNestedFields Out.docx");
Console.WriteLine("\nInserted nested fields in the document successfully.\nFile saved at " + dataDir + "InsertNestedFields Out.docx");
}
示例5: MoveToNode
public static void MoveToNode(string dataDir)
{
// ExStart:DocumentBuilderMoveToNode
Document doc = new Document(dataDir + "DocumentBuilder.doc");
DocumentBuilder builder = new DocumentBuilder(doc);
builder.MoveTo(doc.FirstSection.Body.LastParagraph);
// ExEnd:DocumentBuilderMoveToNode
Console.WriteLine("\nCursor move to required node.");
}
示例6: Replacing
public ReplaceAction Replacing(ReplacingArgs e)
{
//获取当前节点
var node = e.MatchNode;
//获取当前文档
Document doc = node.Document as Document;
DocumentBuilder builder = new DocumentBuilder(doc);
//将光标移动到指定节点
builder.MoveTo(node);
//插入图片
builder.InsertHtml(html);
return ReplaceAction.Replace;
}
示例7: Run
public static void Run()
{
// ExStart:InsertMergeFieldUsingDOM
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithFields();
Document doc = new Document(dataDir + "in.doc");
DocumentBuilder builder = new DocumentBuilder(doc);
// Get paragraph you want to append this merge field to
Paragraph para = (Paragraph)doc.GetChildNodes(NodeType.Paragraph, true)[1];
// Move cursor to this paragraph
builder.MoveTo(para);
// We want to insert a merge field like this:
// { " MERGEFIELD Test1 \\b Test2 \\f Test3 \\m \\v" }
// Create instance of FieldMergeField class and lets build the above field code
FieldMergeField field = (FieldMergeField)builder.InsertField(FieldType.FieldMergeField, false);
// { " MERGEFIELD Test1" }
field.FieldName = "Test1";
// { " MERGEFIELD Test1 \\b Test2" }
field.TextBefore = "Test2";
// { " MERGEFIELD Test1 \\b Test2 \\f Test3 }
field.TextAfter = "Test3";
// { " MERGEFIELD Test1 \\b Test2 \\f Test3 \\m" }
field.IsMapped = true;
// { " MERGEFIELD Test1 \\b Test2 \\f Test3 \\m \\v" }
field.IsVerticalFormatting = true;
// Finally update this merge field
field.Update();
dataDir = dataDir + "InsertMergeFieldUsingDOM_out.doc";
doc.Save(dataDir);
// ExEnd:InsertMergeFieldUsingDOM
Console.WriteLine("\nMerge field using DOM inserted successfully.\nFile saved at " + dataDir);
}
示例8: Run
public static void Run()
{
// ExStart:InsertMailMergeAddressBlockFieldUsingDOM
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithFields();
Document doc = new Document(dataDir + "in.doc");
DocumentBuilder builder = new DocumentBuilder(doc);
// Get paragraph you want to append this merge field to
Paragraph para = (Paragraph)doc.GetChildNodes(NodeType.Paragraph, true)[1];
// Move cursor to this paragraph
builder.MoveTo(para);
// We want to insert a mail merge address block like this:
// { ADDRESSBLOCK \\c 1 \\d \\e Test2 \\f Test3 \\l \"Test 4\" }
// Create instance of FieldAddressBlock class and lets build the above field code
FieldAddressBlock field = (FieldAddressBlock)builder.InsertField(FieldType.FieldAddressBlock, false);
// { ADDRESSBLOCK \\c 1" }
field.IncludeCountryOrRegionName = "1";
// { ADDRESSBLOCK \\c 1 \\d" }
field.FormatAddressOnCountryOrRegion = true;
// { ADDRESSBLOCK \\c 1 \\d \\e Test2 }
field.ExcludedCountryOrRegionName = "Test2";
// { ADDRESSBLOCK \\c 1 \\d \\e Test2 \\f Test3 }
field.NameAndAddressFormat = "Test3";
// { ADDRESSBLOCK \\c 1 \\d \\e Test2 \\f Test3 \\l \"Test 4\" }
field.LanguageId = "Test 4";
// Finally update this merge field
field.Update();
dataDir = dataDir + "InsertMailMergeAddressBlockFieldUsingDOM_out.doc";
doc.Save(dataDir);
// ExEnd:InsertMailMergeAddressBlockFieldUsingDOM
Console.WriteLine("\nMail Merge address block field using DOM inserted successfully.\nFile saved at " + dataDir);
}
开发者ID:aspose-words,项目名称:Aspose.Words-for-.NET,代码行数:44,代码来源:InsertMailMergeAddressBlockFieldUsingDOM.cs
示例9: Main
static void Main(string[] args)
{
Document doc = new Document("../../data/document.doc");
DocumentBuilder builder = new DocumentBuilder(doc);
//Shows how to access the current node in a document builder.
Node curNode = builder.CurrentNode;
Paragraph curParagraph = builder.CurrentParagraph;
// Shows how to move a cursor position to a specified node.
builder.MoveTo(doc.FirstSection.Body.LastParagraph);
// Shows how to move a cursor position to the beginning or end of a document.
builder.MoveToDocumentEnd();
builder.Writeln("This is the end of the document.");
builder.MoveToDocumentStart();
builder.Writeln("This is the beginning of the document.");
doc.Save("outputDocument.doc");
}
示例10: DocumentBuilder
ReplaceAction IReplacingCallback.Replacing(ReplacingArgs args)
{
// Create a builder to insert the field.
DocumentBuilder builder = new DocumentBuilder((Document)args.MatchNode.Document);
// Move to the first node of the match.
builder.MoveTo(args.MatchNode);
// If the user specified text to be used in the field as display text then use that, otherwise use the
// Match string as the display text.
string insertText;
if (!string.IsNullOrEmpty(mFieldText))
insertText = mFieldText;
else
insertText = args.Match.Value;
// Insert the TC field before this node using the specified string as the display text and user defined switches.
builder.InsertField(string.Format("TC \"{0}\" {1}", insertText, mFieldSwitches));
// We have done what we want so skip replacement.
return ReplaceAction.Skip;
}
示例11: Replacing
public ReplaceAction Replacing(ReplacingArgs args)
{
ArrayList runs = FindAndSplitMatchRuns(args);
// Create DocumentBuilder which is used to insert the field.
DocumentBuilder builder = new DocumentBuilder((Document)args.MatchNode.Document);
builder.MoveTo((Run)runs[runs.Count - 1]);
// Calculate the name of the field from the FieldType enumeration by removing the first instance of "Field" from the text.
// This works for almost all of the field types.
string fieldName = mFieldType.ToString().ToUpper().Substring(5);
// Insert the field into the document using the specified field type and the match text as the field name.
// If the fields you are inserting do not require this extra parameter then it can be removed from the string below.
builder.InsertField(string.Format("{0} {1}", fieldName, args.Match.Groups[0]));
// Now remove all runs in the sequence.
foreach (Run run in runs)
run.Remove();
// Signal to the replace engine to do nothing because we have already done all what we wanted.
return ReplaceAction.Skip;
}
示例12: SplitRun
/// <summary>
/// This method is called by the Aspose.Words find and replace engine for each match.
/// This method replaces the match string, even if it spans multiple runs.
/// </summary>
ReplaceAction IReplacingCallback.Replacing(ReplacingArgs e)
{
// This is a Run node that contains either the beginning or the complete match.
Node currentNode = e.MatchNode;
// The first (and may be the only) run can contain text before the match,
// in this case it is necessary to split the run.
if (e.MatchOffset > 0)
currentNode = SplitRun((Run)currentNode, e.MatchOffset);
// This array is used to store all nodes of the match for further removing.
ArrayList runs = new ArrayList();
// Find all runs that contain parts of the match string.
int remainingLength = e.Match.Value.Length;
while (
(remainingLength > 0) &&
(currentNode != null) &&
(currentNode.GetText().Length <= remainingLength))
{
runs.Add(currentNode);
remainingLength = remainingLength - currentNode.GetText().Length;
// Select the next Run node.
// Have to loop because there could be other nodes such as BookmarkStart etc.
do
{
currentNode = currentNode.NextSibling;
}
while ((currentNode != null) && (currentNode.NodeType != NodeType.Run));
}
// Split the last run that contains the match if there is any text left.
if ((currentNode != null) && (remainingLength > 0))
{
SplitRun((Run)currentNode, remainingLength);
runs.Add(currentNode);
}
// Create Document Buidler and insert text.
DocumentBuilder builder = new DocumentBuilder(e.MatchNode.Document as Document);
builder.MoveTo((Run)runs[runs.Count - 1]);
builder.Write(mText);
// Now remove all runs in the sequence.
foreach (Run run in runs)
run.Remove();
// Signal to the replace engine to do nothing because we have already done all what we wanted.
return ReplaceAction.Skip;
}
示例13: ConvertNumPageFieldsToPageRef
/// <summary>
/// Replaces all NUMPAGES fields in the document with PAGEREF fields. The replacement field displays the total number
/// of pages in the sub document instead of the total pages in the document.
/// </summary>
/// <param name="doc">The combined document to process</param>
public static void ConvertNumPageFieldsToPageRef(Document doc)
{
// This is the prefix for each bookmark which signals where page numbering restarts.
// The underscore "_" at the start inserts this bookmark as hidden in MS Word.
const string bookmarkPrefix = "_SubDocumentEnd";
// Field name of the NUMPAGES field.
const string numPagesFieldName = "NUMPAGES";
// Field name of the PAGEREF field.
const string pageRefFieldName = "PAGEREF";
// Create a new DocumentBuilder which is used to insert the bookmarks and replacement fields.
DocumentBuilder builder = new DocumentBuilder(doc);
// Defines the number of page restarts that have been encountered and therefore the number of "sub" documents
// found within this document.
int subDocumentCount = 0;
// Iterate through all sections in the document.
foreach (Section section in doc.Sections)
{
// This section has it's page numbering restarted so we will treat this as the start of a sub document.
// Any PAGENUM fields in this inner document must be converted to special PAGEREF fields to correct numbering.
if (section.PageSetup.RestartPageNumbering)
{
// Don't do anything if this is the first section in the document. This part of the code will insert the bookmark marking
// the end of the previous sub document so therefore it is not applicable for first section in the document.
if (!section.Equals(doc.FirstSection))
{
// Get the previous section and the last node within the body of that section.
Section prevSection = (Section)section.PreviousSibling;
Node lastNode = prevSection.Body.LastChild;
// Use the DocumentBuilder to move to this node and insert the bookmark there.
// This bookmark represents the end of the sub document.
builder.MoveTo(lastNode);
builder.StartBookmark(bookmarkPrefix + subDocumentCount);
builder.EndBookmark(bookmarkPrefix + subDocumentCount);
// Increase the subdocument count to insert the correct bookmarks.
subDocumentCount++;
}
}
// The last section simply needs the ending bookmark to signal that it is the end of the current sub document.
if (section.Equals(doc.LastSection))
{
// Insert the bookmark at the end of the body of the last section.
// Don't increase the count this time as we are just marking the end of the document.
Node lastNode = doc.LastSection.Body.LastChild;
builder.MoveTo(lastNode);
builder.StartBookmark(bookmarkPrefix + subDocumentCount);
builder.EndBookmark(bookmarkPrefix + subDocumentCount);
}
// Iterate through each NUMPAGES field in the section and replace the field with a PAGEREF field referring to the bookmark of the current subdocument
// This bookmark is positioned at the end of the sub document but does not exist yet. It is inserted when a section with restart page numbering or the last
// section is encountered.
Node[] nodes = section.GetChildNodes(NodeType.FieldStart, true).ToArray();
foreach (FieldStart fieldStart in nodes)
{
if (fieldStart.FieldType == FieldType.FieldNumPages)
{
// Get the field code.
string fieldCode = GetFieldCode(fieldStart);
// Since the NUMPAGES field does not take any additional parameters we can assume the remaining part of the field
// code after the fieldname are the switches. We will use these to help recreate the NUMPAGES field as a PAGEREF field.
string fieldSwitches = fieldCode.Replace(numPagesFieldName, "").Trim();
// Inserting the new field directly at the FieldStart node of the original field will cause the new field to
// not pick up the formatting of the original field. To counter this insert the field just before the original field
Node previousNode = fieldStart.PreviousSibling;
// If a previous run cannot be found then we are forced to use the FieldStart node.
if (previousNode == null)
previousNode = fieldStart;
// Insert a PAGEREF field at the same position as the field.
builder.MoveTo(previousNode);
// This will insert a new field with a code like " PAGEREF _SubDocumentEnd0 *\MERGEFORMAT ".
Field newField = builder.InsertField(string.Format(" {0} {1}{2} {3} ", pageRefFieldName, bookmarkPrefix, subDocumentCount, fieldSwitches));
// The field will be inserted before the referenced node. Move the node before the field instead.
previousNode.ParentNode.InsertBefore(previousNode, newField.Start);
// Remove the original NUMPAGES field from the document.
RemoveField(fieldStart);
}
}
}
}
示例14: DocumentBuilder
/// <summary>
/// NOTE: This is a simplistic method that will only work well when the match
/// starts at the beginning of a run.
/// </summary>
ReplaceAction IReplacingCallback.Replacing(ReplacingArgs e)
{
DocumentBuilder builder = new DocumentBuilder((Aspose.Words.Document)e.MatchNode.Document);
builder.MoveTo(e.MatchNode);
// Replace '<CustomerName>' text with a red bold name.
builder.InsertHtml("<b><font color='red'>James Bond</font></b>");
e.Replacement = "";
return ReplaceAction.Replace;
}
示例15: MailMerge_MergeField
//最好這程式有人能維護的了.......
private void MailMerge_MergeField(object sender, MergeFieldEventArgs e)
{
//不是 Fix 開頭的合併欄位不處理。
if (!e.FieldName.ToUpper().StartsWith("Fix".ToUpper())) return;
DocumentBuilder builder = new DocumentBuilder(e.Document);
ReportStudent student = e.FieldValue as ReportStudent;
//如果合併值不是 ReportStudent 就跳過...意思是有問題...。
if (student == null) return;
builder.MoveToField(e.Field, true);
e.Field.Remove();
if (e.FieldName == "Fix:年級學期")
{
#region 列印年級學期資訊(有點複雜)。
SemesterDataCollection semesters = student.SHistory.GetGradeYearSemester().GetSemesters(PrintSetting.PrintSemesters);
Row SemesterRow = builder.CurrentParagraph.ParentNode.ParentNode.NextSibling as Row; //下一個 Row。
Paragraph originParagraph = builder.CurrentParagraph;
int count = 0, offset = 1;
foreach (SemesterData each in semesters)
{
string currentGradeyear = Util.GetGradeyearString(each.GradeYear.ToString());
//如果沒有年級,就跳過。
if (string.IsNullOrEmpty(currentGradeyear)) continue;
builder.Write(currentGradeyear + "年級");
Paragraph nextPh = Util.NextCell(builder.CurrentParagraph);
if (nextPh == null) break; //沒有下一個 Cell ,就不印資料了。
builder.MoveTo(nextPh);
Paragraph resetParagraph = builder.CurrentParagraph;
SemesterRow.Cells[count + offset].Write(builder, GetSemesterString(each));
SemesterData semester = new SemesterData(0, each.SchoolYear, each.Semester);
if (!student.HeaderList.ContainsKey(semester))
student.HeaderList.AddRaw(each, count); //不要懷疑,這是對的。
builder.MoveTo(resetParagraph);
count++;
}
builder.MoveTo(originParagraph);
(originParagraph.ParentNode as Cell).CellFormat.HorizontalMerge = CellMerge.First;
Paragraph nextParagrap = originParagraph;
string previousGradeyear = GetText(originParagraph);
while ((nextParagrap = Util.NextCell(nextParagrap)) != null)
{
if (GetText(nextParagrap) == previousGradeyear && !string.IsNullOrEmpty(previousGradeyear))
{
(nextParagrap.ParentNode as Cell).CellFormat.HorizontalMerge = CellMerge.Previous;
(nextParagrap.ParentNode as Cell).Paragraphs[0].Runs.Clear();
}
else
(nextParagrap.ParentNode as Cell).CellFormat.HorizontalMerge = CellMerge.First;
previousGradeyear = GetText(nextParagrap);
}
#endregion
}
else if (e.FieldName == "Fix:科目資訊")
{
#region 列印科目資料(爆炸複雜)
Row template = builder.CurrentParagraph.ParentNode.ParentNode as Row;
Table table = template.ParentNode as Table;
if (PrintSetting.ListMethod == ListMethod.DomainOnly)
{
#region 列印領域
UniqueSet<RowHeader> RowIndexs = new UniqueSet<RowHeader>();
//Environment.OSVersion.Platform
#region 列印 RowHeader
foreach (SemesterData semester in student.SHistory.GetGradeYearSemester().GetSemesters(PrintSetting.PrintSemesters))
{
SemesterData sysems = new SemesterData(0, semester.SchoolYear, semester.Semester);
//如果不包含該學期成績資料,就跳過。
if (!student.SemestersScore.Contains(sysems)) continue;
SemesterScore semsscore = student.SemestersScore[sysems];
////準備彈性課程的科目(要詳列出來)。
//foreach (string strSubject in semsscore.Subject)
//{
// SemesterSubjectScore subject = semsscore.Subject[strSubject];
// if (DetailDomain.Contains(subject.Domain))
// {
// RefineDomain(subject);
// RowHeader header = new RowHeader(subject.Domain, strSubject);
// header.IsDomain = false;
//.........这里部分代码省略.........