1、代码(NPOI v2.3.0)
/// <summary>
/// 生成带图片的word文档
/// </summary>
/// <param name="paragraphs">段落内容(图片是base64字符串)</param>
/// <param name="docPath"></param>
public void CreateDocx(List<string> paragraphs, string docPath = "")
{
FileStream fs = null;
try
{
fs = new FileStream(docPath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
//创建document对象
var doc = new XWPFDocument();
foreach (var item in paragraphs)
{
//创建段落对象1
var p1 = doc.CreateParagraph();
p1.Alignment = ParagraphAlignment.LEFT; //字体左对齐
var listItem = GetContainImgArr(item);
foreach (var itemTxt in listItem)
{
if (itemTxt.StartsWith("data:image/")) //处理图片
{
#region 提取 base64 并转为filestream
string base64Str = itemTxt.Substring(itemTxt.IndexOf(',') + 1);
string picExtension = itemTxt.Substring(itemTxt.IndexOf('/') + 1, itemTxt.IndexOf(';') - itemTxt.IndexOf('/') - 1);
byte[] buff = Convert.FromBase64String(base64Str);
MemoryStream mstream = new MemoryStream(buff);
#endregion
string picName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + "." + picExtension;
var runPic = p1.CreateRun();
runPic.AddPicture(mstream, GetPictureType(picExtension), picName, 200 * 9525, 200 * 9525);
CT_Inline inline = runPic.GetCTR().GetDrawingList()[0].inline[0];
inline.docPr.id = 1; //id必须从1开始 解决打开文档时 报错(NPOI v2.4 已修复)
mstream.Close();
}
else
{
//创建 run对象
var runTital = p1.CreateRun();
runTital.IsBold = true;
runTital.SetText(itemTxt);
runTital.FontSize = 16;
runTital.SetFontFamily("宋体", FontCharRange.None);
}
}
}
//保存文件
doc.Write(fs);
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (fs != null)
{
fs.Close();
fs.Dispose();
}
}
}
/// <summary>
///分隔图片
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public List<string> GetContainImgArr(string str)
{
List<string> list = new List<string>();
var matchArr = Regex.Split(str, "<img src='([^']+?)'>", RegexOptions.IgnoreCase);
if (matchArr.Length == 0)
{
list.Add(str);
return list;
}
else
{
list.AddRange(matchArr);
}
return list.Where(c => !string.IsNullOrEmpty(c)).ToList();
}
/// <summary>
///图片类型
/// </summary>
/// <param name="picExtension"></param>
/// <returns></returns>
public int GetPictureType(string picExtension)
{
switch (picExtension.ToUpper())
{
case "EMF":
return 2;
case "WMF":
return 3;
case "PICT":
return 4;
case "JPEG":
return 5;
case "PNG":
return 6;
case "DIB":
return 7;
case "GIF":
return 8;
case "TIFF":
return 9;
case "EPS":
return 10;
case "BMP":
return 11;
case "WPG":
return 12;
default:
return 5;
}
}
2、 NPOI V2.3.0 word添加图片,打开word文档时报错【v2.4已修复】,解决方法
来源https://github.com/svn2github/npoi/issues/24
3、处理图片
var matchArr = Regex.Split(str, "<img src='([^']+?)' >", RegexOptions.IgnoreCase);