栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > .Net

c#Word模板转PDF,c#word模板生成新的word

.Net 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

c#Word模板转PDF,c#word模板生成新的word

c#根据word模板生成新的word/pdf

需要引用NuGet包

其中Aspose.Words需要安装的版本为19.2.0

C#根据word模板生成报告

		using System;
		using System.Collections.Generic;
		using System.IO;
		using System.Linq;
		using Aspose.Words;
		using NPOI.XWPF.UserModel;
		using Xceed.Words.NET;

		static void Main(string[] args)
		{
			string tempPath = @"C:UsersGoodCookingDesktopTempWord.docx";
			string outFilePath = @"C:UsersGoodCookingDesktopwuwuwu_1.docx";
			Dictionary dic = new Dictionary();
			dic.Add("Name", "wyh");
			dic.Add("Sex", "nan");
			dic.Add("Age", "22");
			dic.Add("hobby", "die");
			dic.Add("height", "173");
			WriteToPublicationOfResult(tempPath, outFilePath, dic);
			Console.ReadKey();
		}


        /// 
        /// 依照模板word生成word
        /// dic.add("string","newvalue");
        /// word 中的格式 [$string]
        /// 
        /// 模板路径.doc
        /// 保存路径.doc
        /// 关键字集合
        private static void WriteToPublicationOfResult(string templateFileName, string savePath, Dictionary keywords)
        {
            FileStream fs = new FileStream(templateFileName, FileMode.Open, FileAccess.Read);
            XWPFDocument document = new XWPFDocument(fs);

            // 替换表格中的关键字
            foreach (var table in document.Tables)
            {
                foreach (var row in table.Rows)
                {
                    foreach (var cell in row.GetTableCells())
                    {
                        ReplaceKeyWords(cell.Paragraphs, keywords);
                    }
                }
            }
            // 替换模板中非表格的关键字
            ReplaceKeyWords(document.Paragraphs, keywords);

            // 保存文件
            FileStream output = new FileStream(savePath, FileMode.Create);
            document.Write(output);
            fs.Close();
            fs.Dispose();
            output.Close();
            output.Dispose();
            Console.WriteLine("结束,报告生成完毕");
        }

        /// 
        /// 遍历关键字
        /// 
        /// 段落
        /// 关键字集合
        private static void ReplaceKeyWords(IList paragraphs, Dictionary keywords)
        {
            foreach (var item in keywords)
            {
                foreach (var para in paragraphs)
                {
                    string extol = para.ParagraphText;
                    if (extol == "") continue;
                    if (extol.Contains(item.Key))
                    {
                        //para.ReplaceText(item.Key, item.Value);
                        para.ReplaceText($"[${item.Key}]", item.Value);  // 替换段落中的文字
                    }
                }
            }
        }

C# 依照word模板生成PDF

		using System;
		using System.Collections.Generic;
		using System.IO;
		using System.Linq;
		using Aspose.Words;
		using NPOI.XWPF.UserModel;
		using Xceed.Words.NET;


		static void Main(string[] args)
		{
			string tempPath = @"C:UsersGoodCookingDesktopTempWord.docx";
	        string outFilePath = @"C:UsersGoodCookingDesktopwuwuwu_1.pdf";
	        Dictionary dic = new Dictionary();
	        dic.Add("Name", "wyh");
	        dic.Add("Sex", "nan");
	        dic.Add("Age", "22");
	        dic.Add("Hobby", "die");
	        dic.Add("Height", "173");
	        TempWord2PDF(tempPath, outFilePath, dic);
	        Console.ReadKey();
		}


        /// 
        /// 模板wrod转PDF
        /// dic.add("string","newstring");
        /// word 的内容  [$newstring]
        /// 
        /// 模板word路径.doc
        /// 生成之后的pdf路径.pdf
        /// 需要替换的dic
        public static void TempWord2PDF(string tempPath, string newWordPath, Dictionary textDic)
        {
            WriteToPublicationOfResult(tempPath, newWordPath, textDic);

            // 转pdf
            ToPdf(newWordPath, newWordPath);

            // 删除临时文件
            string[] c = newWordPath.Split('.');
            string middleware = c[0] + ".docx";
            if (File.Exists(middleware))
            {
                File.Delete(middleware);
            }
        }



        /// 
        /// 依照模板word生成word
        /// dic.add("string","newvalue");
        /// word 中的格式 [$string]
        /// 
        /// 模板路径.doc
        /// 保存路径.doc
        /// 关键字集合
        private static void WriteToPublicationOfResult(string templateFileName, string savePath, Dictionary keywords)
        {
            FileStream fs = new FileStream(templateFileName, FileMode.Open, FileAccess.Read);
            XWPFDocument document = new XWPFDocument(fs);

            // 替换表格中的关键字
            foreach (var table in document.Tables)
            {
                foreach (var row in table.Rows)
                {
                    foreach (var cell in row.GetTableCells())
                    {
                        ReplaceKeyWords(cell.Paragraphs, keywords);
                    }
                }
            }
            // 替换模板中非表格的关键字
            ReplaceKeyWords(document.Paragraphs, keywords);

            // 保存文件
            FileStream output = new FileStream(savePath, FileMode.Create);
            document.Write(output);
            fs.Close();
            fs.Dispose();
            output.Close();
            output.Dispose();
            Console.WriteLine("结束,报告生成完毕");
        }

        /// 
        /// 转换为pdf
        /// 
        /// 
        /// 
        private static void ToPdf(string src, string target)
        {
            new License().SetLicense(new MemoryStream(Convert.FromBase64String("PExpY2Vuc2U+CiAgPERhdGE+CiAgICA8TGljZW5zZWRUbz5TdXpob3UgQXVuYm94IFNvZnR3YXJlIENvLiwgTHRkLjwvTGljZW5zZWRUbz4KICAgIDxFbWFpbFRvPnNhbGVzQGF1bnRlYy5jb208L0VtYWlsVG8+CiAgICA8TGljZW5zZVR5cGU+RGV2ZWxvcGVyIE9FTTwvTGljZW5zZVR5cGU+CiAgICA8TGljZW5zZU5vdGU+TGltaXRlZCB0byAxIGRldmVsb3BlciwgdW5saW1pdGVkIHBoeXNpY2FsIGxvY2F0aW9uczwvTGljZW5zZU5vdGU+CiAgICA8T3JkZXJJRD4xOTA4MjYwODA3NTM8L09yZGVySUQ+CiAgICA8VXNlcklEPjEzNDk3NjAwNjwvVXNlcklEPgogICAgPE9FTT5UaGlzIGlzIGEgcmVkaXN0cmlidXRhYmxlIGxpY2Vuc2U8L09FTT4KICAgIDxQcm9kdWN0cz4KICAgICAgPFByb2R1Y3Q+QXNwb3NlLlRvdGFsIGZvciAuTkVUPC9Qcm9kdWN0PgogICAgPC9Qcm9kdWN0cz4KICAgIDxFZGl0aW9uVHlwZT5FbnRlcnByaXNlPC9FZGl0aW9uVHlwZT4KICAgIDxTZXJpYWxOdW1iZXI+M2U0NGRlMzAtZmNkMi00MTA2LWIzNWQtNDZjNmEzNzE1ZmMyPC9TZXJpYWxOdW1iZXI+CiAgICA8U3Vic2NyaXB0aW9uRXhwaXJ5PjIwMjAwODI3PC9TdWJzY3JpcHRpb25FeHBpcnk+CiAgICA8TGljZW5zZVZlcnNpb24+My4wPC9MaWNlbnNlVmVyc2lvbj4KICAgIDxMaWNlbnNlSW5zdHJ1Y3Rpb25zPmh0dHBzOi8vcHVyY2hhc2UuYXNwb3NlLmNvbS9wb2xpY2llcy91c2UtbGljZW5zZTwvTGljZW5zZUluc3RydWN0aW9ucz4KICA8L0RhdGE+CiAgPFNpZ25hdHVyZT53UGJtNUt3ZTYvRFZXWFNIY1o4d2FiVEFQQXlSR0pEOGI3L00zVkV4YWZpQnd5U2h3YWtrNGI5N2c2eGtnTjhtbUFGY3J0c0cwd1ZDcnp6MytVYk9iQjRYUndTZWxsTFdXeXNDL0haTDNpN01SMC9jZUFxaVZFOU0rWndOQkR4RnlRbE9uYTFQajhQMzhzR1grQ3ZsemJLZFZPZXk1S3A2dDN5c0dqYWtaL1E9PC9TaWduYXR1cmU+CjwvTGljZW5zZT4=")));
            Aspose.Words.Document doc = new Aspose.Words.Document(src);
            doc.Save(target);
        }


        /// 
        /// 遍历关键字
        /// 
        /// 段落
        /// 关键字集合
        private static void ReplaceKeyWords(IList paragraphs, Dictionary keywords)
        {
            foreach (var item in keywords)
            {
                foreach (var para in paragraphs)
                {
                    string extol = para.ParagraphText;
                    if (extol == "") continue;
                    if (extol.Contains(item.Key))
                    {
                        //para.ReplaceText(item.Key, item.Value);
                        para.ReplaceText($"[${item.Key}]", item.Value);  // 替换段落中的文字
                    }
                }
            }
        }

Enjoy

不懂私信。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/910958.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号