NPOI word中插入图片

使用NPOI制作word数据模板,在插入图片时遇到的一些问题:

1,内联式插图(inline) (这种方式插入图片不好调整显示位置)

XWPFDocument m_Docx = new XWPFDocument();//创建word文档

FileStream gfs = null;
gfs = new FileStream("../../image/1.jpg", FileMode.Open, FileAccess.Read);
CT_P m_p = m_Docx.Document.body.AddNewP();

m_p.AddNewPPr().AddNewJc().val = ST_Jc.center;//段落水平居中
XWPFParagraph gp = new XWPFParagraph(m_p, m_Docx);//创建段落
XWPFRun gr = gp.CreateRun();//创建run
//在run中插入图片
gr.AddPicture(gfs, (int)NPOI.XWPF.UserModel.PictureType.JPEG, "1.jpg", 5300000,2500000);
gfs.Close();

//保存文件到磁盘WinForm  
string docPath = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "DocxWord");
if (!Directory.Exists(docPath)) { Directory.CreateDirectory(docPath); }
string fileName = string.Format("{0}.doc", DateTime.Now.ToString("yyyyMMddHHmmssfff"));
FileStream out1 = new FileStream(Path.Combine(docPath, fileName), FileMode.Create);
m_Docx.Write(out1);
out1.Close();

2,锚点插图(anchor)使用四周型的插入方式,可以确定图片坐标位置的方式,文后会放其他的NPOI整理文档连接

FileStream gfs = null;
//读取图片资源
gfs = new FileStream("../../image/1.jpg", FileMode.Open, FileAccess.Read);
CT_P m_p = m_Docx.Document.body.AddNewP();
m_p.AddNewPPr().AddNewJc().val = ST_Jc.center;
XWPFParagraph gp = new XWPFParagraph(m_p, m_Docx);//创建段落
XWPFRun gr = gp.CreateRun();//创建run

CT_Anchor an = new CT_Anchor();
//图片距正文上(distT)、下(distB)、左(distL)、右(distR)的距离。114300EMUS=3.1mm
an.distB = (uint)(0);
an.distL = 0;
an.distR = 0;
an.distT = 0;
an.relativeHeight = 251658240u;
an.behindDoc = false; //"0",图与文字的上下关系
an.locked = false;  //"0"
an.layoutInCell = true;  //"1"
an.allowOverlap = true;  //"1" 

CT_Positive2D simplePos = new CT_Positive2D();
simplePos.x = (long)0;
simplePos.y = (long)0;
CT_EffectExtent effectExtent = new CT_EffectExtent();
effectExtent.b = 0L;
effectExtent.l = 0L;
effectExtent.r = 0L;
effectExtent.t = 0L;
//图左上角坐标
CT_PosH posH = new CT_PosH();
posH.relativeFrom = ST_RelFromH.column;
posH.posOffset = 0;//单位:EMUS,1CM=360000EMUS
CT_PosV posV = new CT_PosV();
posV.relativeFrom = ST_RelFromV.paragraph;
posV.posOffset = 0;

//使用四周型
CT_WrapSquare wrapSquare = new CT_WrapSquare();
wrapSquare.wrapText = ST_WrapText.bothSides;
gr.AddPicture(gfs, (int)NPOI.XWPF.UserModel.PictureType.JPEG, "1.jpg", 5300000,2500000,
posH, posV, wrapSquare,anchor,simplePos,effectExtent);

//保存文件
string docPath = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "DocxWord");
if (!Directory.Exists(docPath)) { Directory.CreateDirectory(docPath); }
string fileName = string.Format("{0}.doc", DateTime.Now.ToString("yyyyMMddHHmmssfff"));
FileStream out1 = new FileStream(Path.Combine(docPath, fileName), FileMode.Create);
m_Docx.Write(out1);
out1.Close();

 收集的使用NPOI操作word的文档,还是比较适用的文档 https://download.csdn.net/download/dengxt/10823924

 NPOI版本: https://download.csdn.net/download/dengxt/10824550

©️2020 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客 返回首页