NPOI生成word浮动图标

1、NPOI版本2.7.0, net框架4.8

2、安装OpenXMLSDKToolV25.msi

3、先创建一个word文档,并设置图片为浮于文字之上

4、OpenXML显示的结果

5、实际代码如下:

public class GenerateWordDemo
{public GenerateWordDemo(){}//https://blog.fileformat.com/zh/word-processing/npoi-api-for-processing-word-documents-in-net-an-overview///https://blog.csdn.net/sD7O95O/article/details/114108985//https://blog.csdn.net/qq_38544249/article/details/124923848private void SetPage(XWPFDocument doc){// 设置页面的大小CT_SectPr m_SectPr = new CT_SectPr();       //实例一个尺寸类的实例m_SectPr.pgSz.w = 11906;        //设置宽度(这里是一个ulong类型)m_SectPr.pgSz.h = 16838;        //设置高度(这里是一个ulong类型)                    //页面边距m_SectPr.pgMar.left = (ulong)80;//左边距m_SectPr.pgMar.right = (ulong)80;//右边距m_SectPr.pgMar.top = 80;//上边距m_SectPr.pgMar.bottom = 80;//下边距doc.Document.body.sectPr = m_SectPr;          //设置页面的尺寸}/// <summary>/// 加入内联二维码/// </summary>/// <param name="doc"></param>/// <param name="paragraphy"></param>private void AddInlineBarCode(XWPFDocument doc, XWPFParagraph paragraphy){string appPath = System.AppDomain.CurrentDomain.BaseDirectory;string imagePath = System.IO.Path.Combine(appPath, "Images");string imageFile = System.IO.Path.Combine(imagePath, "BarCode.jpg");// 二维码            XWPFRun run = paragraphy.CreateRun();using (FileStream picFile = new FileStream(imageFile, FileMode.Open, FileAccess.Read)){XWPFPicture pic = run.AddPicture(picFile, (int)PictureType.PNG, "barcode.png", 100 * 10857, 100 * 12857);}}private T LoadWordCT<T>(string xml, Func<XmlElement, T> act) where T : class{XmlDocument xmlDoc = new XmlDocument();try{xmlDoc.LoadXml(xml);var element = xmlDoc.DocumentElement;return act(element);                }catch (XmlException xe){return null;}}/// <summary>/// 加入二维码/// </summary>/// <param name="doc"></param>private void AddBarCode(XWPFDocument doc, XWPFParagraph paragraphy){String relationId;XWPFPictureData picData;string appPath = System.AppDomain.CurrentDomain.BaseDirectory;string imagePath = System.IO.Path.Combine(appPath, "Images");string imageFile = System.IO.Path.Combine(imagePath, "BarCode.jpg");using (FileStream picFile = new FileStream(imageFile, FileMode.Open, FileAccess.Read)){relationId = doc.AddPictureData(picFile, (int)PictureType.PNG);picData = (XWPFPictureData)doc.GetRelationById(relationId);}XWPFRun run = paragraphy.CreateRun();CT_RPr rpr = new CT_RPr();rpr.AddNewNoProof();run.GetCTR().rPr = rpr;CT_Drawing drawing = run.GetCTR().AddNewDrawing();drawing.anchor = new List<CT_Anchor>();CT_Anchor an = new CT_Anchor();            //图片距正文上(distT)、下(distB)、左(distL)、右(distR)的距离。114300EMUS=3.1mman.distT = 0;an.distB = 0;an.distL = (uint)114300;an.distR = (uint)114300;an.relativeHeight = 251658240u;an.behindDoc = false; //"0",图与文字的上下关系an.locked = false;  //"0"an.layoutInCell = true;  //"1"an.allowOverlap = true;  //"1" an.simplePos1 = false;an.simplePos1Specified = false;//CT_Point2D simplePos = new CT_Point2D();//simplePos.x = (long)0;//simplePos.y = (long)0;//an.simplePos = simplePos;// https://www.cnblogs.com/zhangliming/archive/2013/04/02/2995655.htmlstring xml = "<wp:simplePos x=\"0\" y=\"0\" xmlns:wp=\"http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing\" />";an.simplePos = LoadWordCT<CT_Point2D>(xml, x => CT_Point2D.Parse(x, null));//图左上角坐标CT_PosH posH = new CT_PosH();posH.relativeFrom = ST_RelFromH.column;posH.posOffset = -1292;   //单位:EMUS,1CM=360000EMUSan.positionH = posH;CT_PosV posV = new CT_PosV();posV.relativeFrom = ST_RelFromV.paragraph;posV.posOffset = 51661;an.positionV = posV;an.extent = new NPOI.OpenXmlFormats.Dml.WordProcessing.CT_PositiveSize2D();an.extent.cx = 1085700;an.extent.cy = 1285700;CT_EffectExtent effectExtent = new CT_EffectExtent();effectExtent.b = 0L;effectExtent.l = 0L;effectExtent.r = 0L;effectExtent.t = 0L;an.effectExtent = effectExtent;an.wrapNone = new CT_WrapNone();an.docPr = new NPOI.OpenXmlFormats.Dml.WordProcessing.CT_NonVisualDrawingProps();long id = run.Document.GetNextPicNameNumber((int)PictureType.PNG);an.docPr.id = (uint)(id);an.docPr.name = ("Drawing " + id);an.docPr.descr = "barcode.png";an.cNvGraphicFramePr = new NPOI.OpenXmlFormats.Dml.WordProcessing.CT_NonVisualGraphicFrameProperties();an.graphic = new CT_GraphicalObject();CT_GraphicalObjectData gd = new CT_GraphicalObjectData();gd.uri = "http://schemas.openxmlformats.org/drawingml/2006/picture";an.graphic.graphicData = gd;// Grab the picture objectNPOI.OpenXmlFormats.Dml.Picture.CT_Picture pic = new NPOI.OpenXmlFormats.Dml.Picture.CT_Picture();// Set it upNPOI.OpenXmlFormats.Dml.Picture.CT_PictureNonVisual nvPicPr = pic.AddNewNvPicPr();NPOI.OpenXmlFormats.Dml.CT_NonVisualDrawingProps cNvPr = nvPicPr.AddNewCNvPr();/* use "0" for the id. See ECM-576, 20.2.2.3 */cNvPr.id = (0);/* This name is not visible in Word 2010 anywhere */cNvPr.name = ("Picture " + id);cNvPr.descr = "barcode.png";CT_NonVisualPictureProperties cNvPicPr = nvPicPr.AddNewCNvPicPr();cNvPicPr.AddNewPicLocks().noChangeAspect = true;CT_BlipFillProperties blipFill = pic.AddNewBlipFill();CT_Blip blip = blipFill.AddNewBlip();blip.embed = run.Paragraph.Part.GetRelationId(picData);blipFill.AddNewStretch().AddNewFillRect();CT_ShapeProperties spPr = pic.AddNewSpPr();CT_Transform2D xfrm = spPr.AddNewXfrm();CT_Point2D off = xfrm.AddNewOff();off.x = (0);off.y = (0);NPOI.OpenXmlFormats.Dml.CT_PositiveSize2D ext = xfrm.AddNewExt();ext.cx = 100;ext.cy = 100;CT_PresetGeometry2D prstGeom = spPr.AddNewPrstGeom();prstGeom.prst = (ST_ShapeType.rect);prstGeom.AddNewAvLst();using (var ms = RecyclableMemory.GetStream()){StreamWriter sw = new StreamWriter(ms);pic.Write(sw, "pic:pic");sw.Flush();ms.Position = 0;var sr = new StreamReader(ms);var picXml = sr.ReadToEnd();gd.AddPicElement(picXml);}drawing.anchor.Add(an);}private XWPFParagraph AddParagraph(XWPFDocument doc){XWPFParagraph paragraphy = doc.CreateParagraph();CT_PPr ppr = new CT_PPr();CT_Spacing sp = ppr.AddNewSpacing();// w:spacing w:after="20" w:line="430" w:lineRule="auto" sp.after = 20;sp.line = "430";sp.lineRule = ST_LineSpacingRule.auto;CT_Ind ind = ppr.AddNewInd();ind.right = "10";CT_Jc jc = ppr.AddNewJc();// 左对齐jc.val = ST_Jc.left;CT_ParaRPr rpr = ppr.AddNewRPr();rpr.rFonts = new CT_Fonts();rpr.rFonts.ascii = "宋体";rpr.rFonts.hAnsi = "宋体";rpr.rFonts.eastAsia = "宋体";rpr.rFonts.cs = "宋体";rpr.b = new CT_OnOff();rpr.b.val = true;rpr.sz = new CT_HpsMeasure();rpr.sz.val = 32;paragraphy.GetCTP().pPr = ppr;return paragraphy;}private XWPFParagraph AddTextParagraph(XWPFDocument doc){XWPFParagraph paragraphy = doc.CreateParagraph();CT_PPr ppr = new CT_PPr();CT_Spacing sp = ppr.AddNewSpacing();sp.lineRule = ST_LineSpacingRule.auto;CT_Ind ind = ppr.AddNewInd();CT_Jc jc = ppr.AddNewJc();jc.val = ST_Jc.right;CT_ParaRPr rpr = ppr.AddNewRPr();rpr.rFonts = new CT_Fonts();rpr.rFonts.ascii = "宋体";rpr.rFonts.hAnsi = "宋体";rpr.rFonts.eastAsia = "宋体";rpr.rFonts.cs = "宋体";rpr.b = new CT_OnOff();rpr.b.val = true;rpr.sz = new CT_HpsMeasure();rpr.sz.val = 32;paragraphy.GetCTP().pPr = ppr;return paragraphy;}private XWPFRun AddTextRun(XWPFParagraph paragraphy, string text, ulong fontSize){XWPFRun run = paragraphy.CreateRun();run.IsBold = true;CT_RPr rpr = new CT_RPr();CT_Fonts ft = rpr.AddNewRFonts();ft.ascii = "宋体";ft.hAnsi = "宋体";ft.eastAsia = "宋体";ft.cs = "宋体";rpr.AddNewB();CT_HpsMeasure sz = rpr.AddNewSz();sz.val = fontSize;run.GetCTR().rPr = rpr;run.SetText(text);return run;}public bool CreateWordReport(string wordFile){try{string appPath = System.AppDomain.CurrentDomain.BaseDirectory;              string checkTime = DateTime.Now.ToString("yyyy年MM月dd日");//检查时间//TODO:使用FileStream文件流来写入数据(传入参数为:文件所在路径,对文件的操作方式,对文件内数据的操作)//通过使用文件流,创建文件流对象,向文件流中写入内容,并保存为Word文档格式using (var stream = new FileStream(wordFile, FileMode.Create, FileAccess.Write)){//创建document文档对象对象实例XWPFDocument doc = new XWPFDocument();XWPFParagraph paragraphy = AddParagraph(doc);AddBarCode(doc, paragraphy);paragraphy = AddTextParagraph(doc);AddTextRun(paragraphy, "TEST1", 32);paragraphy = AddTextParagraph(doc);AddTextRun(paragraphy, "TEST2", 32);paragraphy = AddTextParagraph(doc);AddTextRun(paragraphy, "TEST3", 32);//向文档流中写入内容,生成worddoc.Write(stream);return true;}}catch (Exception ex){return false;}}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/688804.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

官宣!MongoDB Atlas再添新功能!进一步简化构建现代应用程序

亮点前瞻 ● MongoDB Atlas Stream Processing全面可用&#xff0c;开发者能够更轻松地使用实时数据&#xff0c;在统一环境中构建事件驱动型应用程序 ●MongoDB Atlas Search Nodes上线 Microsoft Azure&#xff0c;组织能够隔离和扩展生成式AI工作负载&#xff0c;并将查询…

这8道接口测试面试题

接口测试常见的问题了。 大家乍一看&#xff01; 接口测试面试题 这几个问题&#xff0c;能答出来几个&#xff1f;有没有8个都能够完美的答出来的&#xff1f;在留言区打出你的数字。&#xff08;0~8&#xff09; 这些问题你回答起来&#xff0c;不要吞吞吐吐只说几个关键字…

使用高防IP是应对网络安全的重要措施

使用高防IP&#xff08;High Defense IP&#xff09;在现代网络环境中显得尤为重要&#xff0c;这主要源于以下几个方面的原因&#xff1a; 一、网络安全形势严峻 随着互联网的快速发展&#xff0c;网络安全问题日益突出。各种网络攻击手段层出不穷&#xff0c;如分布式拒绝服…

Vue路由拆分

1.在src下建立router&#xff0c;在router中建立文件index 2.将main.js中部分内容复制 App <template> <div><a href"#/friend">朋友</a><br><a href"#/info">信息</a><br><a href"#/music&quo…

windows设置软件开机自启动

winr 输入 shell:startup C:\Users\用户名\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup把要开机自动启动的程序的快捷方式放进来 输入快捷键 ctrlshiftesc 打开任务管理器 同时在任务管理器也可以看到

VBA信息获取与处理第四节:获取唯一非重复值返回数组的代码

《VBA信息获取与处理》教程(版权10178984)是我推出第六套教程&#xff0c;目前已经是第一版修订了。这套教程定位于最高级&#xff0c;是学完初级&#xff0c;中级后的教程。这部教程给大家讲解的内容有&#xff1a;跨应用程序信息获得、随机信息的利用、电子邮件的发送、VBA互…

java连锁美业收银系统源码-发布产品时选择【销售模式】是什么意思?

博弈美业管理系统源码 连锁多门店美业收银系统源码 多门店管理 / 会员管理 / 预约管理 / 排班管理 / 商品管理 / 促销活动 PC管理后台、手机APP、iPad APP、 发布总部实物商品或门店实物商品时&#xff0c;分“代销”和“买断”两种销售模式。&#xff08;参数名&#xff1a…

存储卡如何下载歌曲?

作为存储芯片及存储卡的原厂&#xff0c;我们了解客户关于如何在存储卡上下载歌曲的疑问。在这篇文章中&#xff0c;我们将详细解析存储卡的使用方法和歌曲下载步骤&#xff0c;帮助客户顺利完成歌曲下载并存储到存储卡中。 1. 选择合适的存储卡 首先&#xff0c;确保您选择的存…

PMP有效期三年后,还有必要续证吗?

通常情况下是必要的&#xff0c;续证条件是在3年内累积60个PDU和支付150美元。如果到期后没有进行续证&#xff0c;但仍希望保持证书&#xff0c;就需要重新参加PMP考试。重新参加考试的费用包括3900元的报名费和数千元的培训费。因此&#xff0c;与重新考试相比&#xff0c;续…

找不到msvcr120.dll无法执行代码?几种方法一键修复msvcr120.dll难题

电脑出现“找不到msvcr120.dll无法执行代码”是什么情况&#xff1f;msvcr120.dll文件是Microsoft Visual C Redistributable的一部分&#xff0c;它是应用程序在Windows操作系统上正常运行所必需的动态链接库文件之一。因此&#xff0c;缺少了msvcr120.dll文件&#xff0c;相应…

HDFS HA 修改nameservice

本例中修改将原来的hdfs-ha 修改为 hdfs-ns 停止HDFS, 防止新的业务操作 等待停止结束 KDE中需要调整的配置项如下图所示 a.搜索栏找到fs.defaultFS,将hdfs://hdfs-ha改为hdfs://hdfs-ns b.搜索栏找到dfs.nameservices,将hdfs-ha改为hdfs-ns c.搜索栏找到dfs.internal.name…

C++笔试强训day17

目录 1.小乐乐改数字 2.十字爆破 3.比那名居的桃子 1.小乐乐改数字 链接 简单把他当成字符串遍历即可。 详细代码&#xff1a; #include <iostream> #include <string> using namespace std; int main() {string s;cin >> s;for (int i 0; i < s.si…