请问最新的Aspose.Word for.net 怎么把文本替换成图片
@SalesDhorde, 以下是用图像替换单词 computer 的示例:
string image = "computer.png";
Document doc = new Document("in.docx");
FindReplaceOptions options = new FindReplaceOptions
{
MatchCase = false,
ReplacingCallback = new ReplaceTextWithImage(image)
};
doc.Range.Replace("computer", "", options);
doc.Save("out.docx");
public class ReplaceTextWithImage : IReplacingCallback
{
private string mImage;
public ReplaceTextWithImage(string image)
{
mImage = image;
}
public ReplaceAction Replacing(ReplacingArgs args)
{
Node currentNode = args.MatchNode;
Console.WriteLine("here");
// 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 (args.MatchOffset > 0)
currentNode = SplitRun((Run)currentNode, args.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 = args.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);
}
//// to insert new content
DocumentBuilder builder = new DocumentBuilder((Document)args.MatchNode.Document);
builder.MoveTo((Run)runs[runs.Count - 1]);
// Insert image
Shape img = builder.InsertImage(mImage);
img.WrapType = WrapType.Inline;
img.Width = 20;
img.Height = 20;
foreach (Run run in runs)
run.Remove();
return ReplaceAction.Skip;
}
private Run SplitRun(Run run, int position)
{
Run afterRun = (Run)run.Clone(true);
afterRun.Text = run.Text.Substring(position);
run.Text = run.Text.Substring((0), (0) + (position));
run.ParentNode.InsertAfter(afterRun, run);
return afterRun;
}
}
computer.png (18.9 KB)
in.docx (13.9 KB)
out.docx (31.2 KB)