分享一个用C#写的Aspose.Pdf生成pdf的工具类

公共类

公共属性

标题级别 对应的标题样式 汉字与数字标题对应关系

using Aspose.Words;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using System.Text.RegularExpressions;namespace Common.Bo
{public class CommonStyle{#region 标题级别 如一级标题 三级标题protected const int oneTitileLevel = 1;protected const int twoTitileLevel = 2;protected const int threeTitileLevel = 3;protected const int fourTitileLevel = 4;protected const int fiveTitileLevel = 5;#endregion#region 只读的标题样式public static ReadOnlyDictionary<int, TitleStyle> titleDict = new ReadOnlyDictionary<int, TitleStyle>(new Dictionary<int, TitleStyle>{{ 0,new TitleStyle("h1",35,"margin-top:0px;")},{ 1,new TitleStyle("h1",35,"margin-top:0px;")},{ 2,new TitleStyle("h2",33,"margin-top:0px;")},{ 3,new TitleStyle("h3",32,"margin-top:0px;")},{ 4,new TitleStyle("h4",30,"margin-top:0px;")},{ 5,new TitleStyle("h5",28,"margin-top:0px;")},});#endregion#region 文件格式protected static ReadOnlyDictionary<string, string> imageFormatterDict = new ReadOnlyDictionary<string, string>(new Dictionary<string, string>{{ ".jpg",default},{ ".jpeg",default},{ ".png",default},{ ".emf",default},{ ".wmf",default},{ ".bmp",default},});protected static ReadOnlyDictionary<string, string> wordFormatterDict = new ReadOnlyDictionary<string, string>(new Dictionary<string, string>{{ ".doc",default},{ ".docx",default}});#endregion#region 数字与大小汉字对照标 最大可是999=》九百九十九protected static Dictionary<int, string> numberUpCaseDict = new Dictionary<int, string>(){{0,"零"},{1,"一"},{2,"二"},{3,"三"},{4,"四"},{5,"五"},{6,"六"},{7,"七"},{8,"八"},{9,"九"},{10,"十"}};#endregion#region 1-5级 标题格式规则校验与标题级别protected static ReadOnlyDictionary<Regex, int> titleRegexRule= new ReadOnlyDictionary<Regex, int>(new Dictionary<Regex, int>{{new Regex("^\\d{1,3}[\\.、]([^0-9]|s)"),1},{new Regex("^\\d{1,3}[\\.、]\\d{1,3}[\\.、]?([^0-9]|s)"),2},{new Regex("^\\d{1,3}[\\.、]\\d{1,3}[\\.、]\\d{1,3}[\\.、]?([^0-9]|s)"),3},{new Regex("^\\d{1,3}[\\.、]\\d{1,3}[\\.、]\\d{1,3}[\\.、]\\d{1,3}[\\.、]?([^0-9]|s)"),4},{new Regex("^\\d{1,3}[\\.、]\\d{1,3}[\\.、]\\d{1,3}[\\.、]\\d{1,3}[\\.、]\\d{1,3}[\\.、]?([^0-9]|s)"),5}});#endregionstatic CommonStyle(){int curV;StringBuilder sbf;for (int i = 11; i < 900; i++){sbf = new StringBuilder();if ((curV = i / 100) > 0){sbf.Append(numberUpCaseDict[curV] + "百");}if ((curV = i % 100 / 10) > 0){sbf.Append(i > 10 && i < 20 ? "十" : numberUpCaseDict[curV] + "十");}else if (i > 100 && curV > 0){sbf.Append("零");}if ((curV = i % 10) > 0){sbf.Append(numberUpCaseDict[curV]);}numberUpCaseDict.Add(i, sbf.ToString());}}}
}

核心代码

生成pdf里面相关部分 如段落(标题/文本) 表格 图片 目录 书签

using Aspose.Pdf;
using Aspose.Pdf.Annotations;
using Aspose.Pdf.Facades;
using Aspose.Pdf.Text;
using Common.Bo;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;namespace Common.Util
{/// <summary>/// Aspose.Pdf /// 生成table  /// 生成段落:标题/普通文本  /// 生成书签  /// 插入图片/// 合并pdf/// 生成目录/// </summary>public class AsposePdfUtil : CommonStyle{#region pdf里面标题级别与字体大小对照关系public static Dictionary<int, float> numberFontDict = new Dictionary<int, float>(){{1,25},{2,22},{3,19},{4,17},{5,15},{6,14.2f}};#endregion#region 标题对应的行展示最大字符数  标题越小 展示字符越多public static Dictionary<int, int> numberMaxShowNumsDict = new Dictionary<int, int>(){{1,18},{2,20},{3,22},{4,24},{5,26},{6,28}};#endregionpublic static ReadOnlyDictionary<string, string> pdfFormatterDict = new ReadOnlyDictionary<string, string>(new Dictionary<string, string>{{ ".pdf",default},});//默认字体 =》宋体public static Aspose.Pdf.Text.Font defaultFont = FontRepository.FindFont("SimSun");//pdf的宽度public const double pdfPageWidth = 610f;/// <summary>/// 创建document/// </summary>/// <param name="comPath"></param>/// <param name="comDoc"></param>/// <param name="comBuilder"></param>public static void CreateWordDocument(string comPath, out Document comDoc){comDoc = new Document(comPath);}/// <summary>/// 创建表格/// </summary>/// <typeparam name="T"></typeparam>/// <param name="document"></param>/// <param name="list"></param>/// <param name="columNames"></param>/// <param name="propNames"></param>/// <param name="customFunc"></param>/// <param name="serialNum"></param>/// <param name="projectInfo"></param>public static void CreateTable<T>(Document document, IList<T> list,string[] columNames, string[] propNames, Action<Document> customFunc = null, bool serialNum = false, string tableTitleRemark = null){Type tbc = typeof(T);Dictionary<string, Func<T, string>> titleColumsDict = new Dictionary<string, Func<T, string>>();for (int i = 0; i < columNames.Length; i++){System.Reflection.PropertyInfo propertyInfo = tbc.GetProperty(propNames[i]);titleColumsDict[columNames[i]] = ob => propertyInfo.GetValue(ob, null)?.ToString();}CreateTable(document, list, titleColumsDict, customFunc, serialNum, tableTitleRemark);}/// <summary>/// 创建表格/// </summary>/// <typeparam name="T"></typeparam>/// <param name="doc"></param>/// <param name="list"></param>/// <param name="titleColumsDict"></param>/// <param name="customFunc"></param>/// <param name="serialNum"></param>/// <param name="projectInfo"></param>public static void CreateTable<T>(Document doc, IList<T> list, Dictionary<string, Func<T, string>> titleColumsDict, Action<Document> customFunc = null, bool serialNum = false, string tableTitleRemark = null){//表格不存在if (!list.Any()){return;}string[] columNames = titleColumsDict.Select(p => p.Key).ToArray();Type tbc = typeof(T);Page page = doc.Pages.Add();page.SetPageSize(pdfPageWidth, page.PageInfo.Height);//设置每个页码的大小一致StringBuilder _columnWidthSbf = new StringBuilder(serialNum ? "30" : "");int colWidth = (int)((page.GetPageRect(true).Width - (serialNum ? 50 : 0)) / columNames.Length - 2);foreach (var item in columNames){_columnWidthSbf.Append($" {colWidth}");}//下面的int offsetTop = 30;//额外的信息if (!string.IsNullOrWhiteSpace(tableTitleRemark)){Aspose.Pdf.Table tab0 = new Aspose.Pdf.Table();Paragraphs paragraphs0 = page.Paragraphs;paragraphs0.Add(tab0);tab0.ColumnWidths = _columnWidthSbf.ToString();tab0.DefaultCellBorder = new Aspose.Pdf.BorderInfo(Aspose.Pdf.BorderSide.None, 0.1F);tab0.Border = new Aspose.Pdf.BorderInfo(Aspose.Pdf.BorderSide.None, 0.1F, Aspose.Pdf.Color.FromRgb(System.Drawing.Color.White));tab0.Margin = new Aspose.Pdf.MarginInfo(5, 2, 2, 5);tab0.DefaultCellPadding = new Aspose.Pdf.MarginInfo(5, 1, 1, 2);tab0.Top = offsetTop;//表格上边距tab0.Left = 5;//表格左边距Aspose.Pdf.Row row0 = tab0.Rows.Add();var cell = row0.Cells.Add();TextFragment fragment1 = CreateFragment(tableTitleRemark, 10);//fragment1.TextState.Underline = true;cell.Paragraphs.Add(fragment1);cell.ColSpan = serialNum ? 1 + columNames.Length : columNames.Length;offsetTop += 42;//让下面的主表格内容有点距离}Aspose.Pdf.Table tab1 = new Aspose.Pdf.Table();Paragraphs paragraphs = page.Paragraphs;paragraphs.Add(tab1);tab1.ColumnWidths = _columnWidthSbf.ToString();tab1.DefaultCellBorder = new Aspose.Pdf.BorderInfo(Aspose.Pdf.BorderSide.All, 0.1F);tab1.Border = new Aspose.Pdf.BorderInfo(Aspose.Pdf.BorderSide.All, 0.1F, Aspose.Pdf.Color.FromRgb(System.Drawing.Color.Black));tab1.Margin = new Aspose.Pdf.MarginInfo(5, 2, 2, 5);//Set the default cell padding to the MarginInfo objecttab1.DefaultCellPadding = new Aspose.Pdf.MarginInfo(5, 1, 1, 2);//不能这么设置不然整个页码都被内容挤垮了//tab1.ColumnAdjustment = ColumnAdjustment.AutoFitToContent;tab1.Top = offsetTop;//表格上边距tab1.Left = 5;//表格左边距//创建第一行(表头)Aspose.Pdf.Row row1 = tab1.Rows.Add();if (serialNum){TextFragment fragment1 = CreateFragment("序号", 11.2f);fragment1.TextState.FontStyle = FontStyles.Bold;Cell cell = row1.Cells.Add();cell.Paragraphs.Add(fragment1);}foreach (var item in columNames){TextFragment fragment1 = CreateFragment(item, 11.2f);fragment1.TextState.FontStyle = FontStyles.Bold;Cell cell = row1.Cells.Add();cell.Paragraphs.Add(fragment1);}//创建内容//添加每行数据  for (int i = 0; i < list.Count; i++){Aspose.Pdf.Row contentRow = tab1.Rows.Add();//操作序号列if (serialNum){//向此单元格中添加内容  TextFragment fragment1 = CreateFragment((i + 1).ToString(), 10.2f);//fragment1.TextState.HorizontalAlignment = HorizontalAlignment.Left;Cell cell = contentRow.Cells.Add();cell.Paragraphs.Add(fragment1);}foreach (var tcItem in titleColumsDict){//向此单元格中添加内容  TextFragment fragment1 = CreateFragment(tcItem.Value.Invoke(list[i]) ?? "", 10.2f);//fragment1.TextState.HorizontalAlignment = HorizontalAlignment.Center;Cell cell = contentRow.Cells.Add();cell.Paragraphs.Add(fragment1);}}customFunc?.Invoke(doc);}/// <summary>/// create a Fragment/// </summary>/// <param name="text"></param>/// <returns></returns>private static TextFragment CreateFragment(string text, float fontSize){TextFragment fragment1 = new TextFragment(text);fragment1.TextState.Font = defaultFont;fragment1.TextState.FontSize = fontSize;fragment1.TextState.FontStyle = FontStyles.Regular;return fragment1;}/// <summary>/// 当前的domBuiler操作 插入图片 ==》追加pdf内容/// </summary>/// <param name="doc"></param>/// <param name="filePath"></param>public static void AppendImageAndPdf(Document doc, string filePath){//文件资源不存在 ==》不插入图片if (!File.Exists(filePath)){return;}//如果是pdfif (filePath != null && filePath.EndsWith(".pdf", StringComparison.CurrentCultureIgnoreCase)){MergePdf(doc, new Document(filePath));}else{int imgWidth2 = 0;int imgHeight2 = 0;Page page = doc.Pages.Add();page.SetPageSize(pdfPageWidth, page.PageInfo.Height);//设置每个页码的大小一致using (System.Drawing.Image image = System.Drawing.Image.FromFile(filePath)){imgWidth2 = image.Width;imgHeight2 = image.Height;//适配宽高AdaptWh(page, ref imgWidth2, ref imgHeight2);//doc.InsertImage(image, RelativeHorizontalPosition.Page, 10.0, RelativeVerticalPosition.Page, 5.0, imgWidth2, imgHeight2, WrapType.None);*/}//按页面缩放 图片page.AddImage(filePath, new Aspose.Pdf.Rectangle(10, 5, imgWidth2 + 10, page.GetPageRect(true).Height - 5));}}/// <summary>/// 合并pdf/// </summary>/// <param name="mainDoc"></param>/// <param name="fullName"></param>public static void MergePdf(Document mainDoc, Document mergeDoc){#region 搜索页码  将页码信息置空TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber("[—第]\\s{0,4}[0-9\\u4e00-\\u9fa5]{1,6}\\s{0,4}[—页]");TextSearchOptions textSearchOptions = new TextSearchOptions(true);textFragmentAbsorber.TextSearchOptions = textSearchOptions;mergeDoc.Pages.Accept(textFragmentAbsorber);TextFragmentCollection textFragmentCollection = textFragmentAbsorber?.TextFragments;if (textFragmentCollection != null){foreach (TextFragment textFragment in textFragmentCollection){textFragment.Text = "";}}#endregionmainDoc.Pages.Add(mergeDoc.Pages);}/// <summary>/// 插入自定义标题 (实际是操作书签)/// </summary>/// <param name="comBuilder"></param>/// <param name="title"></param>/// <param name="titleLevel"></param>/// <param name="newPage">插入新的一页  一般为true是防止图片把文字覆盖了</param>/// <param name="otherCss">额外的样式</param>/// <param name="isTitle">是否是1-5级标题 如果 字体加粗</param>public static void InsertDefinedTitle(Document doc, string title, int titleLevel, bool newPage = true, bool isTitle = true){if (isTitle){//此处防止titleLevel设置错误 校验纠正foreach (var regRule in titleRegexRule){if (regRule.Key.IsMatch(title)){titleLevel = regRule.Value;break;}}}Page page;if (newPage || doc.Pages.Count == 0){page = doc.Pages.Add();page.SetPageSize(pdfPageWidth, page.PageInfo.Height);//设置每个页码的大小一致}else{page = doc.Pages[doc.Pages.Count];}//上边距140px 默认double marginTop = 140;TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber();page.Accept(textFragmentAbsorber);TextFragmentCollection textFragmentCollection = textFragmentAbsorber.TextFragments;if (textFragmentCollection?.Count > 0){//如果存在了段落 向下进行一定的偏移 防止重叠marginTop = page.PageInfo.Height - textFragmentCollection[textFragmentCollection.Count].Position.YIndent;}#region 创建段落文本TextBuilder builder = new TextBuilder(page);//Create text paragraphTextParagraph paragraph = new TextParagraph();paragraph.HorizontalAlignment = HorizontalAlignment.Center;paragraph.VerticalAlignment = VerticalAlignment.Top;paragraph.Margin.Left = 50;//左边距50pxparagraph.Margin.Top = marginTop;//paragraph.SubsequentLinesIndent = 20;//paragraph.Rectangle = new Aspose.Pdf.Rectangle(100, 300, 200, 700);// 指定换行模式paragraph.FormattingOptions.WrapMode = TextFormattingOptions.WordWrapMode.DiscretionaryHyphenation;//TextBuilderInfo textBuilderInfo = new TextBuilderInfo(builder, paragraph);#region  防止换行 中间多了间隔符int v = title.Length / numberMaxShowNumsDict[titleLevel];int rest = title.Length % numberMaxShowNumsDict[titleLevel];StringBuilder _sbf = new StringBuilder();//for (int i = 0; i < titleLevel - 1; i++){paragraph.SubsequentLinesIndent = i * 2;}for (int i = 0; i < v; i++){_sbf.Append(title.Substring(numberMaxShowNumsDict[titleLevel] * i, numberMaxShowNumsDict[titleLevel]));_sbf.Append("\r\n");}_sbf.Append(title.Substring(title.Length - rest, rest));#endregionTextFragment fragment1 = new TextFragment(_sbf.ToString());fragment1.TextState.Font = defaultFont;fragment1.TextState.FontSize = numberFontDict[titleLevel] - 1;fragment1.TextState.FontStyle = isTitle ? FontStyles.Bold : FontStyles.Regular;// 将片段添加到段落paragraph.AppendLine(fragment1);// 添加段落builder.AppendParagraph(paragraph);#endregion#region 创建书签if (isTitle){AddMarkBook(doc, title, page);}#endregion}public static void AddMarkBook(Document doc, string title, Page page){OutlineItemCollection pdfOutline = new OutlineItemCollection(doc.Outlines);pdfOutline.Title = title;pdfOutline.Italic = true;pdfOutline.Bold = true;// Set the destination page numberpdfOutline.Action = new GoToAction(doc.Pages[page.Number]);// Add bookmark in the document's outline collection.doc.Outlines.Add(pdfOutline);}/// <summary>/// 图片适配(页面宽高)/// </summary>/// <param name="imgWidth"></param>/// <param name="imgHeight"></param>public static void AdaptWh(Page curPage, ref int imgWidth, ref int imgHeight){int maxWidth = (int)(curPage.PageInfo.Width * 0.92);int maxHeight = (int)(curPage.PageInfo.Height * 0.92);//长宽比if (imgWidth > maxWidth){imgHeight = Convert.ToInt32(decimal.Multiply(decimal.Divide(maxWidth, (int)imgWidth), (int)imgHeight));imgWidth = maxWidth;}if (imgHeight > maxHeight){imgWidth = Convert.ToInt32(decimal.Multiply(decimal.Divide(maxHeight, (int)imgHeight), (int)imgWidth));imgHeight = maxHeight;}}/// <summary>/// 创建目录---生成完毕以后  使用书签进行生成对应目录/// </summary>/// <param name="positionPage ">定位的页面,如果addPage 为true则是在此位置插入一个新页 </param>/// <param name="addPage ">如果为true为新增一页并在里面创建目录(非必填)</param>/// <param name="firstBookMark">如果需要在最上方插入书签(非必填)</param>public static PdfBookmarkEditor CreateToc(Document doc, int positionPage = 1, bool addPage = true, string firstBookMark = null){//默认访问 PDF 文件的第一页Page tocPage;if (addPage){//在指定位置插入一页tocPage = doc.Pages.Insert(positionPage);}else{//在指定位置操作tocPage = doc.Pages[positionPage];}//创建对象来表示 TOC 信息TocInfo tocInfo = new TocInfo();TextFragment title = new TextFragment("目录");title.TextState.Font = defaultFont;title.TextState.FontSize = 24;title.TextState.FontStyle = FontStyles.Bold;//设置目录标题tocInfo.Title = title;tocPage.TocInfo = tocInfo;//创建将用作目录元素的字符串对象PdfBookmarkEditor bookmarkEditor = new PdfBookmarkEditor();bookmarkEditor.BindPdf(doc);Aspose.Pdf.Facades.Bookmarks bookmarks = bookmarkEditor.ExtractBookmarks();int index = 0;foreach (Aspose.Pdf.Facades.Bookmark bookmark in bookmarks){//创建标题对象  目录级别Aspose.Pdf.Heading heading2 = new Aspose.Pdf.Heading(1);heading2.TextState.Font = defaultFont;heading2.TextState.FontSize = 9.3f;heading2.TextState.LineSpacing = 5;heading2.TextState.WordSpacing = 2;heading2.TextState.FontStyle = FontStyles.Regular;heading2.IsAutoSequence = false;heading2.IsInLineParagraph = false;heading2.HorizontalAlignment = HorizontalAlignment.Left;//TextFragmentTextSegment segment2 = new TextSegment();heading2.TocPage = tocPage;#region 2-4级菜单 首行缩进foreach (var regRule in titleRegexRule){if (regRule.Key.IsMatch(bookmark.Title)){StringBuilder sb = new StringBuilder();for (int i = 1; i < regRule.Value; i++){sb.Append("  ");//首行缩进}segment2.Text = sb.ToString() + bookmark.Title;break;}}//没有匹配if (string.IsNullOrEmpty(bookmark.Title)){segment2.Text = bookmark.Title;}#endregion//进行换行操作if (segment2.Text?.Length > 50){segment2.Text = segment2.Text.Insert(50, "\r\n");}heading2.Segments.Add(segment2);//指定标题对象的目标页面heading2.DestinationPage = doc.Pages[bookmark.PageNumber];//目的地页面heading2.Top = doc.Pages[bookmark.PageNumber].Rect.Height;//将标题添加到包含目录的页面tocPage.Paragraphs.Add(heading2);}if (!string.IsNullOrEmpty(firstBookMark)){Aspose.Pdf.Facades.Bookmarks bookmarks2 = bookmarkEditor.ExtractBookmarks();List<Bookmark> bookMarkList = new List<Bookmark>() { new Bookmark { Action = "GoTo", Title = firstBookMark, PageNumber = 1 } };foreach (var item in bookmarks2){bookMarkList.Add(new Bookmark{Action = item.Action,Title = item.Title,PageDisplay = item.PageDisplay,PageNumber = item.PageNumber,});}bookmarkEditor.DeleteBookmarks();foreach (var item in bookMarkList){bookmarkEditor.CreateBookmarks(item);}}return bookmarkEditor;}/// <summary>/// 创建页码/// </summary>public static void CreatePageNumber(Document doc, int startingNumber = 1){// 创建页码PageNumberStamp pageNumberStamp = new PageNumberStamp();pageNumberStamp.Background = false;pageNumberStamp.Format = "第 # 页";pageNumberStamp.BottomMargin = 10;pageNumberStamp.HorizontalAlignment = HorizontalAlignment.Center;pageNumberStamp.StartingNumber = startingNumber;//默认起始页是第一页pageNumberStamp.TextState.Font = FontRepository.FindFont("SimSun");//宋体pageNumberStamp.TextState.FontSize = 10F;pageNumberStamp.TextState.FontStyle = FontStyles.Regular;pageNumberStamp.TextState.ForegroundColor = Aspose.Pdf.Color.Black;foreach (Aspose.Pdf.Page page in doc.Pages){//page.SetPageSize(pdfPageWidth, page.PageInfo.Height);//设置每个页码的大小一致page.AddStamp(pageNumberStamp);}}/// <summary>/// 转化成pdf并合并到主pdf结构里面/// </summary>/// <param name="doc"></param>/// <param name="temporaryFile"></param>/// <param name="comDoc"></param>public static void ConvertAndMergePdf(Document doc, Document mergePdfFile, Aspose.Words.Document comDoc,bool deleteMergeFile =false){//合并当前word转化的pdfMergePdf(doc, mergePdfFile);if (deleteMergeFile){File.Delete(mergePdfFile.FileName);}}}
}

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

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

相关文章

WordPress外贸站优化工具,WordPress外贸SEO优化方法

WordPress外贸站是跨国企业拓展市场、提升品牌知名度的理想选择。然而&#xff0c;如何通过SEO优化、原创文章生成以及留心站点优化的事项&#xff0c;成为众多站长关注的焦点。 SEO&#xff0c;即搜索引擎优化&#xff0c;是提高网站在搜索引擎结果中排名的关键。首先&#x…

云计算:数字时代的引擎

引言 云计算&#xff0c;作为现代信息技术领域的一项革命性创新&#xff0c;已经深刻改变了我们处理数据和应用的方式。它已经从仅仅是一个概念演变为一个全球范围内广泛应用的技术。云计算为个人、企业和政府机构提供了强大的计算能力、灵活性和可扩展性&#xff0c;同时降低…

JavaScript递归

前端面试大全JavaScript递归 &#x1f31f;经典真题 &#x1f31f;递归 &#x1f31f;真题解答 &#x1f31f;总结 &#x1f31f;经典真题 使用递归完成 1 到 100 的累加 &#x1f31f;递归 A recursive method is a method that calls itself. 递归调用是一种特殊的调…

数据集的标签文件【无标题】

这里写目录标题 读取数据集 .json是用来存储简单的数据结构和对象的文件。json是一种轻量级的数据交换格式 给了 数据集的标签文件&#xff0c; 读取数据集 .json的本质是字典 读取Json文件&#xff1a;json.load() import json with open(train.json,r,encodingutf-8) as f…

[最优化理论] 梯度下降法 + 精确线搜索(单峰区间搜索 + 黄金分割)C++ 代码

这是我的课程作业&#xff0c;用了 Eigen 库&#xff0c;最后的输出是 latex 的表格的一部分 具体内容就是 梯度下降法 精确线搜索&#xff08;单峰区间搜索 黄金分割&#xff09; 从书本的 Matlab 代码转译过来的其实&#xff0c;所以应该是一看就懂了 这里定义了两个测试…

使用pytorch从零开始实现迷你GPT

生成式建模知识回顾: [1] 生成式建模概述 [2] Transformer I&#xff0c;Transformer II [3] 变分自编码器 [4] 生成对抗网络&#xff0c;高级生成对抗网络 I&#xff0c;高级生成对抗网络 II [5] 自回归模型 [6] 归一化流模型 [7] 基于能量的模型 [8] 扩散模型 I, 扩散模型 II…

wordpress建站优化加速教程-Redis加速

这篇文章适合宝塔面板&#xff0c;在宝塔面板安装 Redis 实现网站加速&#xff08; Redis是一个高性能的key-value数据库(PHP连接redis&#xff0c;需PHP设置中安装redis扩展) &#xff09;。对在word press网站有着明显的加速效果。关于Redis具体说明请自己百度&#xff0c;…

编程中常见的技术难题有哪些?By AI

编程对于现代社会发展的重要性 编程&#xff0c;即按照特定的规则和逻辑&#xff0c;为计算机设计指令的过程&#xff0c;已经深深地融入现代社会的各个角落。它对人们的生活、工作和科技发展产生了深远的影响。 首先&#xff0c;编程改变了人们的生活方式。如今&#xff0c;…

Qt 如何操作SQLite3数据库?数据库创建和表格的增删改查?

# 前言 项目源码下载 https://gitcode.com/m0_45463480/QSQLite3/tree/main # 第一步 项目配置 平台:windows10 Qt版本:Qt 5.14.2 在.pro添加 QT += sql 需要的头文件 #include <QSqlDatabase>#include <QSqlError>#include <QSqlQuery>#include &…

SCAU:数字字符序列2

数字字符序列 Time Limit:1000MS Memory Limit:65535K 题型: 填空题 语言: G;GCC;VC 描述 有一个数字字符序列&#xff0c;它是由平方数1&#xff0c;4&#xff0c;9&#xff0c;16&#xff0c;25&#xff0c;36&#xff0c;49&#xff0c;64&#xff0c;81&#xff0c;…

Pandas进阶:拼接 concat 使用方法

1.处理索引和轴 假设我们有2个关于考试成绩的数据集。 df1 pd.DataFrame&#xff08;{ name&#xff1a;[A&#xff0c;B&#xff0c;C&#xff0c;D]&#xff0c;math&#xff1a;[60,89,82,70]&#xff0c;physics&#xff1a;[66&#xff0c; 95,83,66]&#xff0c;chemi…

SCAU:前一个和后一个字符

前一个和后一个字符 Time Limit:1000MS Memory Limit:65535K 题型: 编程题 语言: G;GCC;VC 描述 编写程序&#xff0c;输入一个数字字符&#xff0c;输出其前一个和后一个的数字字符&#xff0c;如果输入的是0前一个输出 “first”&#xff0c;9后一个则输出“last”&…

springBoot整合task

springBoot整合task 文章目录 springBoot整合task开开关设置任务&#xff0c;并设置执行周期定时任务的相关配置 开开关 设置任务&#xff0c;并设置执行周期 Component public class MyBean {Scheduled(cron "0/1 * * * * ?")public void print(){System.out.prin…

C++进阶篇6---C++11新语法

目录 目录 一、统一的列表初始化 二、声明 1.auto 2.decltype 3.nullptr 三、范围for 四、STL中的变化 五、右值引用和移动语义(重点) 一、统一的列表初始化 在c11之前&#xff0c;我们能用{}初始化数组和结构体 struct Point {int x;int y; }; int main() {int a[] …

机器学习 - 导论

简单了解 机器学习关于数据集的概念 、

堆排序算法

目录 1.基本原理2.例子3.代码实现 本文主要介绍堆排序的原理、例子以及代码实现。 1.基本原理 堆排序&#xff08;Heap Sort&#xff09;是一种基于比较的排序算法&#xff0c;它的工作原理是首先将待排序的序列构造成一个大顶堆或小顶堆&#xff0c;然后交换堆顶元素和最后一…

HCIP —— 双点重发布 + 路由策略 实验

目录 实验拓扑&#xff1a; 实验要求&#xff1a; 实验配置&#xff1a; 1.配置IP地址 2.配置动态路由协议 —— RIP 、 OSPF R1 RIP R4 OSPF R2 配置RIP、OSPF 双向重发布 R3配置RIP、OSPF 双向重发布 3.查询路由表学习情况 4.使用路由策略控制选路 R2 R3 5.检…

C/C++ 快速排序

个人主页&#xff1a;仍有未知等待探索_C语言疑难,数据结构,小项目-CSDN博客 专题分栏&#xff1a;算法_仍有未知等待探索的博客-CSDN博客 快速排序的思想——分治 目录 一、引言 二、讲解 1、步骤 2、代码 1.以左边界作为基准 2.以右边界作为基准 3.以中心点作为基准 …

Linux shell编程学习笔记32:declare 命令

0 前言 在 Linux shell编程学习笔记16&#xff1a;bash中的关联数组https://blog.csdn.net/Purpleendurer/article/details/134053506?spm1001.2014.3001.5501 中&#xff0c;我们在定义关联数组时使用了declare命令。 其实&#xff0c;declare命令的功能不只是定义定义关…

排序算法介绍(三)选择排序

0. 简介 选择排序&#xff08;Selection Sort&#xff09;是一种简单直观的排序算法。它的工作原理是每一次从待排序的数据元素中选出最小&#xff08;或最大&#xff09;的一个元素&#xff0c;存放在序列的起始位置&#xff0c;直到全部待排序的数据元素排完。选择排序是不稳…