/// <summary> /// 替换单个占位符(文本) /// </summary> /// <param name="paragraph"></param> /// <param name="replace"></param> private static void ReplaceTextInRun(XWPFParagraph paragraph, Models.Word.ReplacementBasic replace) { if (replace == null || replace.Type != Enums.PlaceholderTypeEnum.Text || string.IsNullOrWhiteSpace(paragraph.Text)) { return; } TextSegment split = paragraph.SearchText("{ }", new PositionInParagraph()); if (split != null) { paragraph.ReplaceText("{ }", ""); } TextSegment ts = paragraph.SearchText(replace.Placeholder, new PositionInParagraph()); if (ts == null || !(ts.BeginRun != ts.EndRun || ts.BeginChar != ts.EndChar)) { return; } paragraph.ReplaceText(replace.Placeholder, replace.Text); //利用递归处理同一个占位符 ReplaceTextInRun(paragraph, replace); }
/// <summary> /// 替换单个占位符(文本) /// </summary> /// <param name="paragraph"></param> /// <param name="replace"></param> private static void ReplaceTextInRun(XWPFParagraph paragraph, Models.Word.ReplacementBasic replace) { TextSegment ts = paragraph.SearchText(replace.Placeholder, new PositionInParagraph()); if (ts == null || ts.BeginRun == ts.EndRun) { return; } paragraph.ReplaceText(replace.Placeholder, replace.Text); //利用递归处理同一个占位符 ReplaceTextInRun(paragraph, replace); }
/// <summary> /// 替换单个占位符(图片) /// </summary> /// <param name="paragraph"></param> /// <param name="replace"></param> private static void ReplacePictureInRun(XWPFParagraph paragraph, Models.Word.ReplacementBasic replace) { if (replace == null) { return; } var picList = replace.Pictures; if (picList == null || picList.Count() == 0) { return; } TextSegment ts = paragraph.SearchText(replace.Placeholder, new PositionInParagraph()); if (ts == null) { return; } var beginIndex = ts.BeginRun; var endIndex = ts.EndRun; var runs = paragraph.Runs; var begin_run = runs[beginIndex]; //再beginrun的位置插入图片 foreach (var picture in picList) { var pictureData = picture.PictureData; if (pictureData == null || pictureData.Length == 0) { try { pictureData = File.OpenRead(picture.PictureUrl); } catch (Exception) { } } if (pictureData == null || pictureData.Length == 0) { continue; } int height = (int)(Math.Ceiling(picture.Height * NPOI_PICTURE_LENGTH_EVERY_CM)); int width = (int)(Math.Ceiling(picture.Width * NPOI_PICTURE_LENGTH_EVERY_CM)); begin_run.AddPicture(pictureData, picture.PictureType.GetHashCode(), picture.FileName, width, height); NPOI.OpenXmlFormats.Dml.WordProcessing.CT_Inline inline = begin_run.GetCTR().GetDrawingList()[0].inline[0]; inline.docPr.id = 1; pictureData.Dispose(); } //然后清空所有run for (int i = beginIndex; i <= endIndex; i++) { var run = runs[i]; if (run.Text.Contains(replace.Placeholder)) { var runText = run.Text.Replace(replace.Placeholder, ""); run.SetText(runText, 0); } else { run.SetText("", 0); } } //利用递归处理同一个占位符 ReplacePictureInRun(paragraph, replace); }