NPOI生成word浮动图标

news2024/10/5 22:47:17

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/124923848

	private 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.1mm
		an.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.html
		string 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=360000EMUS
		an.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 object
		NPOI.OpenXmlFormats.Dml.Picture.CT_Picture pic = new NPOI.OpenXmlFormats.Dml.Picture.CT_Picture();

		// Set it up
		NPOI.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);

				//向文档流中写入内容,生成word
				doc.Write(stream);

				return true;
			}
		}
		catch (Exception ex)
		{
			return false;
		}
	}
}

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

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

word-排版文本基本格式

1、文本的基本格式&#xff1a;字体格式、段落格式 2、段落&#xff1a;word排版的基本控制单位 3、每敲一次回车&#xff0c;为一个段落标记&#xff0c;注意区分换行符和段落标记&#xff0c;换行符为指向下的箭头&#xff0c;段落标记为带拐弯的箭头&#xff0c;换行符&…

C语言基础——循环语句

&#x1f33a;​&#x1f64f;&#x1f64f;&#x1f64f;欢迎大家观看&#xff0c;写的好的话希望三连感谢&#x1f64f;&#x1f64f;&#x1f64f;&#x1f33a; 文章目录 一、循环语句的介绍 二、不同循环语句的使用 1.while循环 1.1 while循环的使用方式 1.2 while循环的执…

Java | Leetcode Java题解之第84题柱状图中最大的矩形

题目&#xff1a; 题解&#xff1a; class Solution {public int largestRectangleArea(int[] heights) {int n heights.length;int[] left new int[n];int[] right new int[n];Arrays.fill(right, n);Deque<Integer> mono_stack new ArrayDeque<Integer>();f…

https免费证书获取

获取免费证书的网址&#xff1a; Certbot 1. 进入你的linux系统&#xff0c;先安装snapd&#xff0c; yum install snapd 2. 启动snapd service snapd start 3.安装 Certbot snap install --classic certbot 注意如下出现此错误时&#xff0c;需要先建立snap 软连接后&am…

MVCC 详解

介绍 MVCC&#xff0c;全称 Multi-Version Concurrency Control&#xff0c;即多版本并发控制 MVCC的目的主要是为了提高数据库并发性能&#xff0c;用更好的方式去处理读-写冲突&#xff0c;做到即使有读写冲突时&#xff0c;也能做到不加锁。 这里的多版本指的是数据库中同时…

Ubuntu 和 Windows之间无法复制粘贴问题解决方法

需要安装open-vm-tools&#xff0c;官方安装open-vm-tools的网址&#xff1a;安装 Open VM Tools (vmware.com)

vue 点击平滑到指定位置并绑定页面滑动效果

1.html元素 写出对应的数据块&#xff08;注意添加ref) 用于获取元素位置 <template><div class"index-page" ><div class"top-head" ref"index"><img src"logo.png" style"height: 40px;margin-right: 2…

代码+视频,R言语处理数据中的缺失值

在SCI论文中&#xff0c;我们不可避免和缺失数据打交道&#xff0c;特别是在回顾性研究&#xff0c;对于缺失的协变量&#xff08;就是混杂因素&#xff09;&#xff0c;我们可以使用插补补齐数据&#xff0c;但是对于结局变量和原因变量的缺失&#xff0c;我们不能这么做。部分…

网络端口占用问题的综合调研与解决方案

原创 Randy 拍码场 问题背景 去年底信息安全团队进行网络权限治理&#xff0c;要求所有应用实例使用静态IP&#xff0c;公网访问策略与静态IP绑定&#xff1b;之后实例重启时偶现“端口被占用”错误。通过分析总结应用日志&#xff0c;共有以下4种错误类型&#xff0c;实质都是…

WAAP全站防护理念,发现和保护敏感数据

数据是现代企业的新石油&#xff1a;正确使用它可以促进公司的发展并帮助企业在竞争中领先。就像石油一样&#xff0c;原始数据和未被发现的数据是毫无用处的&#xff0c;企业将无法从中受益&#xff1b;在最坏的情况下&#xff0c;它可能会导致安全事件。这也是企业投资敏感数…

MySQL数据库的初始化(创建库、创建表、向数据库添加测试数据)

MySQL数据库的初始化&#xff08;创建库、创建表、向数据库添加测试数据&#xff09; MySQL数据库简介MySQL创建一个新的数据库MySQL创建一张新的数据表简单&#xff08;设置&#xff09;表复杂&#xff08;设置&#xff09;表 填充测试数据SQL语句mysql>模式下输入的每句sq…

Spring Cloud | “微服务“ 架构 与 Spring Cloud

“微服务” 架构 与 Spring Cloud 目录: "微服务" 架构 与 Spring Cloud1. 认识架构"单体" 架构"SOA" 架构"微服务" 架构 2. "微服务架构" 的功能 :① 微服务架构的 "自动化部署"② 服务 "集中化管理"③…

PostgreSQL的学习心得和知识总结(一百四十三)|深入理解PostgreSQL数据库之Support event trigger for logoff

目录结构 注&#xff1a;提前言明 本文借鉴了以下博主、书籍或网站的内容&#xff0c;其列表如下&#xff1a; 1、参考书籍&#xff1a;《PostgreSQL数据库内核分析》 2、参考书籍&#xff1a;《数据库事务处理的艺术&#xff1a;事务管理与并发控制》 3、PostgreSQL数据库仓库…

转载:ubuntu18.04 安装wine以及添加mono和gecko打开简单.net应用的方法

https://www.cnblogs.com/jinanxiaolaohu/p/12191576.html 1. 今天突然想试试能不能用ubuntu跑一下公司的.net的智能客户端(SmartClient). 想到的办法就是 安装wine 但是过程略坑..这里简单说一下总结之后的过程. 2. 第一步安装wine相关内容 查了下有winehq和wine两种. …

凸优化理论学习二|凸函数及其相关概念

系列文章目录 凸优化理论学习一|最优化及凸集的基本概念 文章目录 系列文章目录一、凸函数&#xff08;一&#xff09;凸集&#xff08;二&#xff09;凸函数的定义及举例&#xff08;三&#xff09;凸函数的证明1、将凸函数限制在一条直线上2、判断函数是否为凸函数的一阶条件…

iphone进入恢复模式怎么退出?分享2种退出办法!

iPhone手机莫名其妙的进入到了恢复模式&#xff0c;或者是某些原因需要手机进入恢复模式&#xff0c;但是之后我们不知道如何退出恢复模式怎么办&#xff1f; 通常iPhone进入恢复模式的常见原因主要是软件问题、系统升级失败、误操作问题等导致。那iphone进入恢复模式怎么退出&…

【工具篇】-什么是.NET

“.NET"&#xff1a;.NET Core是由Microsoft开发&#xff0c;目前在.NET Foundation(一个非营利的开源组织)下进行管理。.NET Core是用C#和C编写的&#xff0c;并采用MIT协议作为开源协议。 简单来说&#xff1a;就是开发框架。 .NET 又称 .NET 平台或 .NET 框架&#xf…

Centos 7.9 安装 tigervnc-server

环境&#xff1a;当前使用的 Centos 7.9 的光盘作为的本地源。 1 检查是否已安装 tigervnc [rootlocalhost /]# rpm -q tigervnc tigervnc-server 未安装软件包 tigervnc tigervnc-server-1.8.0-21.el7.x86_64 如果安装过卸掉 卸载: rpm -e [rootlocalhost /]# rpm -e tige…

Django项目运行报错:ModuleNotFoundError: No module named ‘MySQLdb‘

解决方法&#xff1a; 在__init__.py文件下&#xff0c;新增下面这段代码 import pymysql pymysql.install_as_MySQLdb() 注意&#xff1a;确保你的 python 有下载 pymysql 库&#xff0c;没有的话可以使用 pip install pymysql安装 原理&#xff1a;用pymysql来代替mysqlL…

【Qt 学习笔记】Qt常用控件 | 容器类控件 | Group Box的使用及说明

博客主页&#xff1a;Duck Bro 博客主页系列专栏&#xff1a;Qt 专栏关注博主&#xff0c;后期持续更新系列文章如果有错误感谢请大家批评指出&#xff0c;及时修改感谢大家点赞&#x1f44d;收藏⭐评论✍ Qt常用控件 | 容器类控件 | Group Box的使用及说明 文章编号&#xff…