Aspose.Words - 指定位置替换并插入

重载句柄类方法,通过传递匿名句柄对象,实现指哪打哪的编辑插入功能。

Aspose.Words - 指定位置替换并插入

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
using Aspose.Words;
using Aspose.Words.Replacing;
using System.Text.RegularExpressions;

namespace AppendTest
{

class Program
{
private class InsertAtReplaceHandler : IReplacingCallback
{
private string replaceStr;
private bool hasNext;

public InsertAtReplaceHandler(string replaceStr, bool hasNext)
{
this.replaceStr = replaceStr;
this.hasNext = hasNext;
}

ReplaceAction IReplacingCallback.Replacing(ReplacingArgs e)
{
// Insert a document after the paragraph, containing the match text.
Paragraph para = (Paragraph)e.MatchNode.ParentNode;
//InsertDocument(para, subDoc);

Document doc = (Document)e.MatchNode.Document;
DocumentBuilder docBuilder = new DocumentBuilder(doc);

// duplicate pattern for next replace use
if (this.hasNext)
{
Paragraph paraClone = (Paragraph)para.Clone(true);
para.ParentNode.InsertAfter(paraClone, para);
}

docBuilder.MoveTo(para);
para.RemoveAllChildren();
//docBuilder.MoveToParagraph(doc.IndexOf(para))
//docBuilder.Bold = true;
//docBuilder.Font.Size = 20.0;
docBuilder.Write(this.replaceStr);

// Remove the paragraph with the match text.
//para.Remove();

return ReplaceAction.Skip;
}
}


static void Main(string[] args)
{
Document doc = new Document("C:\\Dev\\Test\\AsposeTest\\MES dev quote.docx");
DocumentBuilder docBuilder = new DocumentBuilder(doc);

doc.Range.Replace(new Regex("__pattern__"), new InsertAtReplaceHandler("TEST20171214", true), false);
doc.Range.Replace(new Regex("__pattern__"), new InsertAtReplaceHandler("TEST20171215", false), false);

doc.Save("C:\\Dev\\Test\\AsposeTest\\MES dev quote.output.pdf");
}
}
}