
上一篇文章中介绍了关于设置Excel条件格式,包括基于单元格值、自定义公式等应用条件格式、应用数据条条件类型格式、删除条件格式等内容。在本篇文章中将继续介绍C# 设置条件格式的方法。 要点概述: 1. 应用条件格式用于高亮重复、唯一数值 2. 应用条件格式用于高亮峰值(最高、最低) 3. 应用条件格式用于高亮低于、高于平均值的数值 使用工具: Spire.XLS for .NET 注:在编辑代码时注意在程序中添加引用Spire.Xls.dll,dll文件可在安装路径下的Bin文件夹中获取。 C#代码示例(供参考) 【示例 1】应用条件格式用于高亮重复、唯一数值 C# using Spire.Xls; using System.Drawing; namespace HightDuplicateData_XLS { class Program { static void Main(string[] args) { //实例化Workbook类,加载测试文档 Workbook workbook = new Workbook(); workbook.LoadFromFile("test.xlsx"); //获取第一个工作表 Worksheet sheet = workbook.Worksheets[0]; //应用条件格式1到指定数据范围,高亮重复数值的单元格 ConditionalFormatWrapper format1 = sheet.Range["A3:A13"].ConditionalFormats.AddCondition(); format1.FormatType = ConditionalFormatType.DuplicateValues; format1.BackColor = Color.Cyan; //应用条件格式2到指定数据范围,高亮唯一值的单元格 ConditionalFormatWrapper format2 = sheet.Range["A3:A13"].ConditionalFormats.AddCondition(); format2.FormatType = ConditionalFormatType.UniqueValues; format2.BackColor = Color.Yellow; //保存文档并打开 workbook.SaveToFile("result.xlsx", ExcelVersion.Version2013); System.Diagnostics.Process.Start("result.xlsx"); } } } 完成代码后,调试运行程序,生成文档,如下图: 【示例2】应用条件格式用于高亮峰值(最高、最低) C# using Spire.Xls; using System.Drawing; namespace HighlightTopData_XLS { class Program { static void Main(string[] args) { //实例化workbook类 Workbook workbook = new Workbook(); //加载测试文档 workbook.LoadFromFile("test.xlsx"); //获取第一个工作表 Worksheet sheet = workbook.Worksheets[0]; //应用条件格式1到指定范围,并高亮最高(依次排序)的两个数值 ConditionalFormatWrapper format1 = sheet.Range["B17:B24"].ConditionalFormats.AddCondition(); format1.FormatType = ConditionalFormatType.TopBottom; format1.TopBottom.Type = TopBottomType.Top; format1.TopBottom.Rank = 2; format1.BackColor = Color.Green; //应用条件格式2到指定范围,并高亮最低(依次排序)的两个数值 ConditionalFormatWrapper format2 = sheet.Range["B17:B24"].ConditionalFormats.AddCondition(); format2.FormatType = ConditionalFormatType.TopBottom; format2.TopBottom.Type = TopBottomType.Bottom; format2.TopBottom.Rank = 2; format2.BackColor = Color.RosyBrown; //保存并打开文档 workbook.SaveToFile("output.xlsx", ExcelVersion.Version2013); System.Diagnostics.Process.Start("output.xlsx"); } } } 测试结果: 【示例3】应用条件格式用于高亮低于、高于平均值的数值 C# using System.Drawing; using Spire.Xls; using Spire.Xls.Core; using Spire.Xls.Core.Spreadsheet.Collections; namespace Average_Condition { class Program { static void Main(string[] args) { //实例化workbook类 Workbook workbook = new Workbook(); //加载文档 workbook.LoadFromFile("test.xlsx"); //获取第一个工作表 Worksheet sheet = workbook.Worksheets[0]; //添加条件格式1并应用到指定数据范围 XlsConditionalFormats format1 = sheet.ConditionalFormats.Add(); format1.AddRange(sheet.Range["B17:B24"]); //高亮低于平均数值的单元格 IConditionalFormat cf1 = format1.AddAverageCondition(AverageType.Below); cf1.BackColor = Color.SkyBlue; //添加条件格式2并应用到指定数据范围 XlsConditionalFormats format2 = sheet.ConditionalFormats.Add(); format2.AddRange(sheet.Range["B17:B24"]); //高亮高于平均数值的单元格 IConditionalFormat cf2 = format1.AddAverageCondition(AverageType.Above); cf2.BackColor = Color.Orange; //保存并打开文档 workbook.SaveToFile("result.xlsx", ExcelVersion.Version2013); System.Diagnostics.Process.Start("result.xlsx"); } } } 测试结果: 以上内容是本次关于设置Excel表格条件格式的补充介绍,如需转载,请注明出处。 (本文完)
简介 本篇文章将介绍C# 如何处理Excel图形相关的问题,包括以下内容要点: 1.绘制图形 1.1 绘制图形并添加文本到图形 1.2 添加图片到图形 1.3 设置图形阴影效果 2. 提取图形中的文本、图片 3. 设置图形的显示、隐藏 4. 删除图形 4.1删除指定图形 4.2 删除所有图形 所需工具 Free Spire.XLS for .NET 8.3 (社区版) PS: 下载安装该类库后,注意在项目程序中添加引用Spire.Xls.dll文件(dll文件可在安装路径下的Bin文件夹中获取) 注:Spire.xls能支持的图形种类很多,常见的Office Excel中的图形,这个类库也都能实现, 示例代码(供参考) 1. 绘制图形 【C#】 using System.Drawing; using Spire.Xls; using Spire.Xls.Core; namespace Add_shapes_to_Excel { class Program { static void Main(string[] args) { //创建实例 Workbook workbook = new Workbook(); //获取第一个工作表 Worksheet sheet = workbook.Worksheets[0]; //添加“太阳”形状的图形,并填充颜色 IPrstGeomShape Triangle = sheet.PrstGeomShapes.AddPrstGeomShape(2, 2, 170, 160, PrstGeomShapeType.Sun); Triangle.Fill.ForeColor = Color.Orange; Triangle.Fill.FillType = ShapeFillType.SolidColor; Triangle.Text = "IT'S A SUNNY DAY";//添加文本 //添加“禁止”标志的图形,并填充渐变颜色 IPrstGeomShape heart = sheet.PrstGeomShapes.AddPrstGeomShape(2, 7, 140, 140, PrstGeomShapeType.NoSmoking); heart.Fill.ForeColor = Color.Red; heart.Fill.FillType = ShapeFillType.Gradient; //添加云朵形状的图形 IPrstGeomShape Cloud = sheet.PrstGeomShapes.AddPrstGeomShape(15, 2, 160, 160, PrstGeomShapeType.Cloud); //设置图形阴影效果 Cloud.Shadow.Angle = 90; Cloud.Shadow.Distance = 10; Cloud.Shadow.Size = 100; Cloud.Shadow.Color = Color.SteelBlue; Cloud.Shadow.Blur = 30; Cloud.Shadow.Transparency = 1; Cloud.Shadow.HasCustomStyle = true; //添加五角星形状的图形,并加载图片来填充图形 IPrstGeomShape cloud = sheet.PrstGeomShapes.AddPrstGeomShape(15, 7, 160, 160, PrstGeomShapeType.Star5); cloud.Fill.CustomPicture(Image.FromFile("sm.png"), "sm.png"); cloud.Fill.FillType = ShapeFillType.Picture; //保存并打开文档 workbook.SaveToFile("AddShapes.xlsx", ExcelVersion.Version2013); System.Diagnostics.Process.Start("AddShapes.xlsx"); } } } 图形插入效果: 2.提取图形中的文本和图片 【C#】 using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Text; using Spire.Xls; using Spire.Xls.Core; namespace Extract_text_and_image_from_Excel_shape { class Program { static void Main(string[] args) { //创建实例,加载Excel工作表 Workbook workbook = new Workbook(); workbook.LoadFromFile("test.xlsx"); //获取第一个工作表 Worksheet sheet = workbook.Worksheets[0]; //提取指定形状中的文本内容,并将提取到的文本保存到指定文档 IPrstGeomShape shape1 = sheet.PrstGeomShapes[0]; string s = shape1.Text; StringBuilder sb = new StringBuilder(); sb.AppendLine(s); File.WriteAllText("ExtractText.txt", sb.ToString()); System.Diagnostics.Process.Start("ExtractText.txt"); //提取指定图形中的图片,并保存图片到指定文件 IPrstGeomShape shape2 = sheet.PrstGeomShapes[3]; Image image = shape2.Fill.Picture; image.Save("ShapeImage.png", ImageFormat.Png); System.Diagnostics.Process.Start("ShapeImage.png"); } } } 提取结果: 3. 设置图形的隐藏、显示 【C#】 using Spire.Xls; namespace HideShapes_XLS { class Program { static void Main(string[] args) { //创建实例,加载Excel文档 Workbook workbook = new Workbook(); workbook.LoadFromFile("test.xlsx"); //获取第一个工作表 Worksheet sheet = workbook.Worksheets[0]; //隐藏第3个图形 sheet.PrstGeomShapes[2].Visible = false; //显示图形 //sheet.PrstGeomShapes[1].Visible = true; //保存并打开文档 workbook.SaveToFile("HideShape.xlsx", ExcelVersion.Version2013); System.Diagnostics.Process.Start("HideShape.xlsx"); } } } 设置效果: 4. 删除Excel图形 【C#】 using Spire.Xls; namespace RemoveShapes_XLS { class Program { static void Main(string[] args) { //实例化Workbook类对象,加载Excel文件 Workbook workbook = new Workbook(); workbook.LoadFromFile("test.xlsx"); //获取第一个工作表 Worksheet sheet = workbook.Worksheets[0]; //删除第一个图形 sheet.PrstGeomShapes[0].Remove(); //删除所有图形 //for (int i = sheet.PrstGeomShapes.Count-1; i >= 0; i--) //{ // sheet.PrstGeomShapes[i].Remove(); //} //保存并打开文件 workbook.SaveToFile("DeleteShape.xlsx", ExcelVersion.Version2013); System.Diagnostics.Process.Start("DeleteShape.xlsx"); } } } 图形删除效果: 以上是关于“C#操作Excel中图形”的介绍,如需转载,请注明出处。
概述 OLE,Object Linking and Embedding,即对象连接与嵌入。我们在设计程序时,OLE可以用来创建复合文档,把文字、声音、图像、表格、应用程序等类型的信息组合在一起,在Word中,我们可以通过OLE来实现以上要素信息的组合。下面的示例中将介绍如何通过C# 来操作Word中的OLE,示例内容包含以下要点: 插入OLE到Word 编辑Word中的OLE 读取Word中的OLE 使用工具 Spire.Doc for .NET 注:下载安装该类库,在编辑代码时,注意在程序中添加引用Spire.Doc.dll(dll文件可在安装路径下的Bin文件夹中获取) 示例代码(供参考) 【示例1】插入OLE到Word 步骤 1 :添加using指令 using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; using System.Drawing; 步骤 2 :创建文档 //实例化一个Document类对象 Document doc = new Document(); //向文档中添加一个Section对象,并添加段落 Section sec = doc.AddSection(); Paragraph p = sec.AddParagraph(); 步骤 3 :加载图片 //实例化一个DocPicture类对象,加载图片 DocPicture picture = new DocPicture(doc); Image image = Image.FromFile(@"chart1.png"); picture.LoadImage(image); 步骤 4 :插入OLE //在文档中插入一个工作表, OleLinkType 枚举值控制该OLE是链接还是嵌入 DocOleObject obj = p.AppendOleObject(@"testfile.xlsx", picture, OleLinkType.Link); //DocOleObject obj = p.AppendOleObject(@"testfile.xlsx", picture, OleLinkType.Embed); 步骤 5 :保存文档 //保存并打开文档 doc.SaveToFile("添加OLE.docx"); System.Diagnostics.Process.Start("添加OLE.docx"); 完成代码后,调试运行程序,生成文档。 测试结果,如下图所示: 全部代码: using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; using System.Drawing; namespace InsertOLE_Doc { class Program { static void Main(string[] args) { //实例化一个Document类对象 Document doc = new Document(); //向文档中添加一个Section对象,并添加段落 Section sec = doc.AddSection(); Paragraph p = sec.AddParagraph(); //实例化一个DocPicture类对象,加载图片 DocPicture picture = new DocPicture(doc); Image image = Image.FromFile(@"chart1.png"); picture.LoadImage(image); //在文档中插入一个工作表, OleLinkType 枚举值控制该OLE是链接还是嵌入 DocOleObject obj = p.AppendOleObject(@"testfile.xlsx", picture, OleLinkType.Link); //DocOleObject obj = p.AppendOleObject(@"testfile.xlsx", picture, OleLinkType.Embed); //保存并打开文档 doc.SaveToFile("添加OLE.docx"); System.Diagnostics.Process.Start("添加OLE.docx"); } } } View Code 【示例2】编辑Word中的OLE (这里以上文中生成的文档为测试文件) 步骤 1 :添加using指令 using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; using System.Drawing; using System.IO; 步骤 2 :加载文档 //实例化一个Document对象,加载含有OLE的Word文档 Document doc = new Document(); doc.LoadFromFile("test.docx"); 步骤 3 :获取section中的所有OLE,根据需要来更改OLE的类型和链接对象 //获取第一个Section Section sec = doc.Sections[0]; //遍历这个Section中的所有子元素,找到段落下的OLE对象 foreach (DocumentObject obj in sec.Body.ChildObjects) { if (obj is Paragraph) { Paragraph par = obj as Paragraph; foreach (DocumentObject paraObj in par.ChildObjects) { //找到OLE对象,根据类型来进行更改操作 if (paraObj.DocumentObjectType == DocumentObjectType.OleObject) { DocOleObject Ole = paraObj as DocOleObject; //如果是链接, 修改对象的链接路径 if (Ole.LinkType == OleLinkType.Link) { //同时还要手动去更改OLE的图片 DocPicture pic = Ole.OlePicture; pic.LoadImage(Image.FromFile("Img.png")); Ole.LinkPath = @"sample.docx"; } //如果是嵌入,更改数据即可 byte[] bys = File.ReadAllBytes(@"sample.docx"); if (Ole.LinkType == OleLinkType.Embed) { DocPicture pic = new DocPicture(doc); pic.LoadImage(Image.FromFile(@"Img.png")); Ole.ObjectType = "Word.Document.12"; Ole.SetOlePicture(pic); Ole.SetNativeData(bys); } } } } } 步骤 4 :保存文档 //保存修改后的文档,并打开 doc.SaveToFile("修改OLE.docx", Spire.Doc.FileFormat.Docx2010); System.Diagnostics.Process.Start("修改OLE.docx"); 调试运行程序后,生成文档。打开文档时,生成的文档中原有的插入OLE的图片和链接的文档都已经更改了,如下所示: 全部代码: using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; using System.Drawing; using System.IO; namespace EditOLE_Doc { class Program { static void Main(string[] args) { //实例化一个Document对象,加载含有OLE的Word文档 Document doc = new Document(); doc.LoadFromFile("test.docx"); //获取第一个Section Section sec = doc.Sections[0]; //遍历这个Section中的所有子元素,找到段落下的OLE对象 foreach (DocumentObject obj in sec.Body.ChildObjects) { if (obj is Paragraph) { Paragraph par = obj as Paragraph; foreach (DocumentObject paraObj in par.ChildObjects) { //找到OLE对象,根据类型来进行更改操作 if (paraObj.DocumentObjectType == DocumentObjectType.OleObject) { DocOleObject Ole = paraObj as DocOleObject; //如果是链接, 修改对象的链接路径 if (Ole.LinkType == OleLinkType.Link) { //同时还要手动去更改OLE的图片 DocPicture pic = Ole.OlePicture; pic.LoadImage(Image.FromFile("Img.png")); Ole.LinkPath = @"sample.docx"; } //如果是嵌入,更改数据即可 byte[] bys = File.ReadAllBytes(@"sample.docx"); if (Ole.LinkType == OleLinkType.Embed) { DocPicture pic = new DocPicture(doc); pic.LoadImage(Image.FromFile(@"Img.png")); Ole.ObjectType = "Word.Document.12"; Ole.SetOlePicture(pic); Ole.SetNativeData(bys); } } } } } //保存修改后的文档,并打开 doc.SaveToFile("修改OLE.docx", Spire.Doc.FileFormat.Docx2010); System.Diagnostics.Process.Start("修改OLE.docx"); } } } View Code 【示例3】读取Word中的OLE 步骤 1 :添加using指令 using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; using System.IO; 步骤 2 :加载文件 //实例化一个Document对象,加载一个有OLE对象的文档 Document doc = new Document(); doc.LoadFromFile(@"test.docx"); 步骤 3 :遍历section,读取OLE //遍历文档所有Section foreach (Section sec in doc.Sections) { //遍历Section下面所有的子元素 foreach (DocumentObject obj in sec.Body.ChildObjects) { if (obj is Paragraph) { Paragraph par = obj as Paragraph; //遍历这个section下面的段落 foreach (DocumentObject o in par.ChildObjects) { //找到OLE对象,并根据类型提取 if (o.DocumentObjectType == DocumentObjectType.OleObject) { DocOleObject Ole = o as DocOleObject; /*ObjectType属性可以获取ole对象的具体类型。 注意,如果是用Spire.Doc添加的ole对象的话,需要在AppendOleObject 的时候先声明OleObjectType,不然这里得不到具体的类型,只会得到Package*/ string s = Ole.ObjectType; //"AcroExch.Document.11"是指PDF对象对应的ProgID if (s == "AcroExch.Document.11") { File.WriteAllBytes("Result.pdf", Ole.NativeData); } //"Excel.Sheet.12"是指 Excel03之后的工作表对应的ProgID else if (s == "Excel.Sheet.12") { File.WriteAllBytes("Result.xlsx", Ole.NativeData); } //"Word.Document.12"是指03之后的Word对应的ProgID else if (s == "Word.Document.12") { File.WriteAllBytes("Result.docx", Ole.NativeData); } } } } } } 调试运行程序,生成文档,如下: 全部代码: using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; using System.IO; namespace ReadOLE_Doc { class Program { static void Main(string[] args) { //实例化一个Document对象,加载一个有OLE对象的文档 Document doc = new Document(); doc.LoadFromFile(@"test.docx"); //遍历文档所有Section foreach (Section sec in doc.Sections) { //遍历Section下面所有的子元素 foreach (DocumentObject obj in sec.Body.ChildObjects) { if (obj is Paragraph) { Paragraph par = obj as Paragraph; //遍历这个section下面的段落 foreach (DocumentObject o in par.ChildObjects) { //找到OLE对象,并根据类型提取 if (o.DocumentObjectType == DocumentObjectType.OleObject) { DocOleObject Ole = o as DocOleObject; /*ObjectType属性可以获取ole对象的具体类型。 注意,如果是用Spire.Doc添加的ole对象的话,需要在AppendOleObject 的时候先声明OleObjectType,不然这里得不到具体的类型,只会得到Package*/ string s = Ole.ObjectType; //"AcroExch.Document.11"是指PDF对象对应的ProgID if (s == "AcroExch.Document.11") { File.WriteAllBytes("Result.pdf", Ole.NativeData); } //"Excel.Sheet.12"是指 Excel03之后的工作表对应的ProgID else if (s == "Excel.Sheet.12") { File.WriteAllBytes("Result.xlsx", Ole.NativeData); } //"Word.Document.12"是指03之后的Word对应的ProgID else if (s == "Word.Document.12") { File.WriteAllBytes("Result.docx", Ole.NativeData); } } } } } } } } } View Code 以上是本次关于C# 操作word中的OLE的全部内容。示例方法供参考。 本文完。 如需转载,请注明出处!
我们在创建Powerpoint文档时,系统默认的幻灯片是空白背景的,很多时候我们需要自定义幻灯片背景,以达到美观的文档效果。在下面的示例中将介绍给PowerPoint幻灯片设置背景的方法,主要包含以下三个部分: 添加纯色背景 添加渐变色背景 添加图片作为背景 所需工具 Free Spire.Presentation for .NET 版本3.3 (社区版) 示例代码(供参考) 步骤 1 :添加如下using指令 using Spire.Presentation; using Spire.Presentation.Drawing; using System.Drawing; 步骤 2 :创建文档 Presentation ppt = new Presentation(); ppt.LoadFromFile("test.pptx"); 步骤 3 :添加纯色背景 //设置文档的背景填充模式为纯色填充 ppt.Slides[0].SlideBackground.Type = BackgroundType.Custom; ppt.Slides[0].SlideBackground.Fill.FillType = FillFormatType.Solid; ppt.Slides[0].SlideBackground.Fill.SolidColor.Color = Color.Pink; 步骤 4 :添加渐变背景色 //设置文档的背景填充模式为渐变色填充 ppt.Slides[1].SlideBackground.Type = BackgroundType.Custom; ppt.Slides[1].SlideBackground.Fill.FillType = FillFormatType.Gradient; ppt.Slides[1].SlideBackground.Fill.Gradient.GradientStops.Append(0f, KnownColors.Yellow); ppt.Slides[1].SlideBackground.Fill.Gradient.GradientStops.Append(1f, KnownColors.Orange); 步骤 5 :添加图片作为背景 //设置幻灯片背景色为图片背景 ppt.Slides[2].SlideBackground.Type = Spire.Presentation.Drawing.BackgroundType.Custom; ppt.Slides[2].SlideBackground.Fill.FillType = FillFormatType.Picture; ppt.Slides[2].SlideBackground.Fill.PictureFill.FillType = PictureFillType.Stretch; //加载图片作为幻灯片背景 Image img = Image.FromFile("green.png"); IImageData image = ppt.Images.Append(img); ppt.Slides[2].SlideBackground.Fill.PictureFill.Picture.EmbedImage = image; 步骤6 :保存文件 ppt.SaveToFile("result.pptx", FileFormat.Pptx2010); System.Diagnostics.Process.Start("result.pptx"); 完成代码后,调试运行程序,生成文件,如下: 全部代码: using Spire.Presentation; using Spire.Presentation.Drawing; using System.Drawing; namespace AddBackground_PPT { class Program { static void Main(string[] args) { //实例化Presentation类,加载PowerPoint文档 Presentation ppt = new Presentation(); ppt.LoadFromFile("test.pptx"); //设置文档的背景填充模式为纯色填充 ppt.Slides[0].SlideBackground.Type = BackgroundType.Custom; ppt.Slides[0].SlideBackground.Fill.FillType = FillFormatType.Solid; ppt.Slides[0].SlideBackground.Fill.SolidColor.Color = Color.Pink; //设置文档的背景填充模式为渐变色填充 ppt.Slides[1].SlideBackground.Type = BackgroundType.Custom; ppt.Slides[1].SlideBackground.Fill.FillType = FillFormatType.Gradient; ppt.Slides[1].SlideBackground.Fill.Gradient.GradientStops.Append(0f, KnownColors.Yellow); ppt.Slides[1].SlideBackground.Fill.Gradient.GradientStops.Append(1f, KnownColors.Orange); //设置幻灯片背景色为图片背景 ppt.Slides[2].SlideBackground.Type = Spire.Presentation.Drawing.BackgroundType.Custom; ppt.Slides[2].SlideBackground.Fill.FillType = FillFormatType.Picture; ppt.Slides[2].SlideBackground.Fill.PictureFill.FillType = PictureFillType.Stretch; //加载图片作为幻灯片背景 Image img = Image.FromFile("green.png"); IImageData image = ppt.Images.Append(img); ppt.Slides[2].SlideBackground.Fill.PictureFill.Picture.EmbedImage = image; //保存并打开文档 ppt.SaveToFile("result.pptx", FileFormat.Pptx2010); System.Diagnostics.Process.Start("result.pptx"); } } } View Code 本文完。 如需转载,请注明出处!!
概要 书签的设置可以帮助我们快速的定位某段文字,使用起来很方便,也很节省时间。在前一篇文章“C# 如何添加/删除Word书签”中介绍了插入、删除书签的方法,本篇文章将对C# 操作Word书签的功能做进一步介绍。示例内容将包含以下要点: 在现有书签位置插入图片 在现有书签位置插入表格 读取书签位置的文档内容 替换现有书签位置内容 使用工具 Spire.Doc for .NET 6.1 Visual Studio ps:下载安装该类库后,注意添加引用Spire.Doc.dl到项目程序,dll文件可在安装路径的Bin文件夹中获取。 示例代码(供参考) 测试文档如下: 【示例1】 在现有书签位置插入图片 步骤 1: 添加using指令 using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; using System.Drawing; 步骤 2 :主要代码段 //创建实例,加载文档 Document document = new Document(); document.LoadFromFile("test.docx"); //实例化BookmarksNavigator类,指定需要添加图片的书签“Bookmark1” BookmarksNavigator bn = new BookmarksNavigator(document); bn.MoveToBookmark("Bookmark1", true, true); //添加段落,加载图片并插入到段落 Section section0 = document.AddSection(); Paragraph paragraph = section0.AddParagraph(); Image image = Image.FromFile("img.png"); DocPicture picture = paragraph.AppendPicture(image); bn.InsertParagraph(paragraph); document.Sections.Remove(section0); //保存文档并打开 string output = "result.docx"; document.SaveToFile(output, FileFormat.Docx); System.Diagnostics.Process.Start(output); 图片插入效果: 全部代码: using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; using System.Drawing; namespace InsertImgToBookmark_Doc { class Program { static void Main(string[] args) { //创建实例,加载文档 Document document = new Document(); document.LoadFromFile("test.docx"); //实例化BookmarksNavigator类,指定需要添加图片的书签“Bookmark1” BookmarksNavigator bn = new BookmarksNavigator(document); bn.MoveToBookmark("Bookmark1", true, true); //添加段落,加载图片并插入到段落 Section section0 = document.AddSection(); Paragraph paragraph = section0.AddParagraph(); Image image = Image.FromFile("img.png"); DocPicture picture = paragraph.AppendPicture(image); bn.InsertParagraph(paragraph); document.Sections.Remove(section0); //保存文档并打开 string output = "result.docx"; document.SaveToFile(output, FileFormat.Docx); System.Diagnostics.Process.Start(output); } } } View Code 【示例 2】在现有书签位置插入表格 步骤 1:添加using指令 using Spire.Doc; using Spire.Doc.Documents; using System.Data; 步骤 2 :创建文档,加载文件 Document doc = new Document(); doc.LoadFromFile("test.docx"); 步骤 3 :创建表格 //创建Table对象 Table table = new Table(doc, true); //创建模拟数据 DataTable dt = new DataTable(); dt.Columns.Add("PI", typeof(string)); dt.Columns.Add("Type", typeof(string)); dt.Columns.Add("Nov.", typeof(string)); dt.Columns.Add("YTD", typeof(string)); dt.Rows.Add(new string[] { "PI","Type", "Nov.", "YTD" }); dt.Rows.Add(new string[] { "1", "BAIC EC-Series", "15.719", "64.910" }); dt.Rows.Add(new string[] { "2", "Tesla Model S", "3.889", "46.951" }); dt.Rows.Add(new string[] { "3", "Nissan Leaf", "2.817", "46.423" }); //将数据填充至表格 table.ResetCells(dt.Rows.Count, dt.Columns.Count); for (int i = 0; i < dt.Rows.Count; i++) { for (int j = 0; j < dt.Columns.Count; j++) { table.Rows[i].Cells[j].AddParagraph().AppendText(dt.Rows[i][j].ToString()); } } 步骤 4 :插入表格到书签位置 //获取指定书签位置 BookmarksNavigator navigator = new BookmarksNavigator(doc); navigator.MoveToBookmark("origin2"); //将表格添加至TextBodyPart TextBodyPart part = navigator.GetBookmarkContent(); part.BodyItems.Add(table); //替换原有书签内容 navigator.ReplaceBookmarkContent(part); 步骤 5 :保存文件 //保存并打开文件 doc.SaveToFile("output.docx", FileFormat.Docx2013); System.Diagnostics.Process.Start("output.docx"); 表格插入效果: 全部代码: using Spire.Doc; using Spire.Doc.Documents; using System.Data; namespace InsertTableToBookmark_Doc { class Program { static void Main(string[] args) { //创建文档,加载文件 Document doc = new Document(); doc.LoadFromFile("test.docx"); //创建Table对象 Table table = new Table(doc, true); //创建模拟数据 DataTable dt = new DataTable(); dt.Columns.Add("PI", typeof(string)); dt.Columns.Add("Type", typeof(string)); dt.Columns.Add("Nov.", typeof(string)); dt.Columns.Add("YTD", typeof(string)); dt.Rows.Add(new string[] { "PI","Type", "Nov.", "YTD" }); dt.Rows.Add(new string[] { "1", "BAIC EC-Series", "15.719", "64.910" }); dt.Rows.Add(new string[] { "2", "Tesla Model S", "3.889", "46.951" }); dt.Rows.Add(new string[] { "3", "Nissan Leaf", "2.817", "46.423" }); //将数据填充至表格 table.ResetCells(dt.Rows.Count, dt.Columns.Count); for (int i = 0; i < dt.Rows.Count; i++) { for (int j = 0; j < dt.Columns.Count; j++) { table.Rows[i].Cells[j].AddParagraph().AppendText(dt.Rows[i][j].ToString()); } } //获取指定书签位置 BookmarksNavigator navigator = new BookmarksNavigator(doc); navigator.MoveToBookmark("origin2"); //将表格添加至TextBodyPart TextBodyPart part = navigator.GetBookmarkContent(); part.BodyItems.Add(table); //替换书签内容 navigator.ReplaceBookmarkContent(part); //保存并打开文件 doc.SaveToFile("output.docx", FileFormat.Docx2013); System.Diagnostics.Process.Start("output.docx"); } } } View Code 【示例3】读取书签位置的内容 步骤 1 :添加using指令 using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; using System; 步骤 2 :获取书签位置的内容 //初始化BookmarkNavigator类对象 BookmarksNavigator navigator = new BookmarksNavigator(doc); //定位到指定书签位置,获取书签位置的文档内容 navigator.MoveToBookmark("bookmark1"); TextBodyPart textBodyPart = navigator.GetBookmarkContent(); 步骤 3 :读取书签内容 //遍历书签内容中的子项目,并将文本信息提取至string类型变量中 string text = null; foreach (var item in textBodyPart.BodyItems) { if (item is Paragraph) { foreach (var childObject in (item as Paragraph).ChildObjects) { if (childObject is TextRange) { text += (childObject as TextRange).Text; } } } } //控制台输出文本 Console.WriteLine(text); Console.ReadLine(); 读取结果: 全部代码: using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; using System; namespace GetTextOfBookmark_Doc { class Program { static void Main(string[] args) { //实例化Document类,加载测试文档 Document doc = new Document(); doc.LoadFromFile("test.docx"); //初始化BookmarkNavigator类对象 BookmarksNavigator navigator = new BookmarksNavigator(doc); //定位到指定书签位置,获取书签位置的文档内容 navigator.MoveToBookmark("bookmark1"); TextBodyPart textBodyPart = navigator.GetBookmarkContent(); //遍历书签内容中的子项目,并将文本信息提取至string类型变量中 string text = null; foreach (var item in textBodyPart.BodyItems) { if (item is Paragraph) { foreach (var childObject in (item as Paragraph).ChildObjects) { if (childObject is TextRange) { text += (childObject as TextRange).Text; } } } } //控制台输出文本 Console.WriteLine(text); Console.ReadLine(); } } } View Code 【示例4】替换现有书签内容 步骤 1 :添加using指令 using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; 步骤 2 :加载文档 Document document = new Document(); document.LoadFromFile("test.docx"); 步骤 3 :添加段落及文字 Section sec = document.AddSection();//添加section sec.AddParagraph().AppendText("Welcome Back, \n My Friend!"); //添加段落到section,并添加字符串内容 步骤 4 :获取段落 //获取段落内容 ParagraphBase firstReplacementParagraph = sec.Paragraphs[0].Items.FirstItem as ParagraphBase; ParagraphBase lastReplacementParagraph = sec.Paragraphs[sec.Paragraphs.Count - 1].Items.LastItem as ParagraphBase; //实例化类TextBodySelection和TextBodyPart TextBodySelection selection = new TextBodySelection(firstReplacementParagraph, lastReplacementParagraph); TextBodyPart part = new TextBodyPart(selection); 步骤 5 :替换书签内容 BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(document);//实例化BookmarksNavigator类 bookmarkNavigator.MoveToBookmark("bookmark1", true, true);//定位到书签“bookmark1”所在段落的位置 bookmarkNavigator.DeleteBookmarkContent(true);//删除原有书签位置的内容 bookmarkNavigator.ReplaceBookmarkContent(part, true, true);//用新添加段落的内容替换掉原书签的内容并保留格式 document.Sections.Remove(sec); //移除section 步骤 6 :保存文档 //保存文档并打开 document.SaveToFile("替换书签.docx"); System.Diagnostics.Process.Start("替换书签.docx"); 替换效果: 全部代码: using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; namespace EditOrReplaceBookmark_Doc { class Program { static void Main(string[] args) { //创建Document类实例,加载文档 Document document = new Document(); document.LoadFromFile("test.docx"); Section sec = document.AddSection();//添加section sec.AddParagraph().AppendText("Welcome Back, \n My Friend!"); //添加段落到section,并添加字符串内容 //获取段落内容 ParagraphBase firstReplacementParagraph = sec.Paragraphs[0].Items.FirstItem as ParagraphBase; ParagraphBase lastReplacementParagraph = sec.Paragraphs[sec.Paragraphs.Count - 1].Items.LastItem as ParagraphBase; //实例化类TextBodySelection和TextBodyPart TextBodySelection selection = new TextBodySelection(firstReplacementParagraph, lastReplacementParagraph); TextBodyPart part = new TextBodyPart(selection); BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(document);//实例化BookmarksNavigator类 bookmarkNavigator.MoveToBookmark("bookmark1", true, true);//定位到书签“bookmark1”所在段落的位置 bookmarkNavigator.DeleteBookmarkContent(true);//删除原有书签位置的内容 bookmarkNavigator.ReplaceBookmarkContent(part, true, true);//用新添加段落的内容替换掉原书签的内容并保留格式 document.Sections.Remove(sec); //移除section //保存文档并打开 document.SaveToFile("替换书签.docx"); System.Diagnostics.Process.Start("替换书签.docx"); } } } View Code 以上是本次关于C# 操作Word书签功能的补充介绍,如需转载,请注明出处。 (本文完)
序 在前面的文章C# 如何插入、修改、删除Word批注一文中介绍了如何操作Word批注的一些方法,在本篇文章中继续介绍操作Word批注的方法。分以下三种情况来介绍: 1. 插入图片到Word批注 2. 读取Word批注 3. 回复Word批注 所需工具 Free Spire.Doc for .NET 6.3(社区版) Visual Studio PS:下载安装Free Spire.Doc 后,注意在你的程序中添加引用Spire.Doc.dll(dll文件可以在安装路径下的Bin文件夹中获取) 示例代码 1. 插入图片到Word批注 步骤 1:添加using指令 using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; using System.Drawing; 步骤 2:创建文档,加载测试文件 Document doc = new Document(); doc.LoadFromFile("testfile.docx"); 步骤 3 :获取段落 Paragraph paragraph = doc.Sections[0].Paragraphs[2]; 步骤 4 :添加文本、图片到批注 Comment comment = paragraph.AppendComment("探索黑科技,小米为发烧而生!");comment.Format.Author = "Administor"; DocPicture docPicture = new DocPicture(doc); Image img = Image.FromFile("mi.png"); docPicture.LoadImage(img); //插入图片到批注 comment.Body.AddParagraph().ChildObjects.Add(docPicture); 步骤 5 :保存文件 doc.SaveToFile("result.docx", FileFormat.Docx2013); System.Diagnostics.Process.Start("result.docx"); 测试结果: C#全部代码: using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; using System.Drawing; namespace InsertImgToComment_Doc { class Program { static void Main(string[] args) { //实例化Document类,加载文档 Document doc = new Document(); doc.LoadFromFile("testfile.docx"); //获取需要添加批注的段落 Paragraph paragraph = doc.Sections[0].Paragraphs[2]; //添加文本批注内容、批注作者 Comment comment = paragraph.AppendComment("探索黑科技,小米为发烧而生!"); comment.Format.Author = "Administor"; //实例化DocPicture类,加载图片 DocPicture docPicture = new DocPicture(doc); Image img = Image.FromFile("mi.png"); docPicture.LoadImage(img); //插入图片到批注 comment.Body.AddParagraph().ChildObjects.Add(docPicture); //保存文件并打开文档 doc.SaveToFile("result.docx", FileFormat.Docx2013); System.Diagnostics.Process.Start("result.docx"); } } } View Code VB.NET代码: Imports Spire.Doc Imports Spire.Doc.Documents Imports Spire.Doc.Fields Imports System.Drawing Namespace InsertImgToComment_Doc Class Program Private Shared Sub Main(ByVal args As String()) Dim doc As Document = New Document() doc.LoadFromFile("testfile.docx") Dim paragraph As Paragraph = doc.Sections(0).Paragraphs(2) Dim comment As Comment = paragraph.AppendComment("探索黑科技,小米为发烧而生!") comment.Format.Author = "Administor" Dim docPicture As DocPicture = New DocPicture(doc) Dim img As Image = Image.FromFile("mi.png") docPicture.LoadImage(img) comment.Body.AddParagraph().ChildObjects.Add(docPicture) doc.SaveToFile("result.docx", FileFormat.Docx2013) System.Diagnostics.Process.Start("result.docx") End Sub End Class End Namespace View Code 2.读取Word批注 步骤 1 :添加using指令 using System.Text; using System.IO; using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; 步骤 2 :创建实例,加载文档 Document doc = new Document(); doc.LoadFromFile("test.docx"); 步骤 3 :将批注内容写入Txt文档 //实例化StringBuilder类 StringBuilder SB = new StringBuilder(); //遍历所有word批注,将批注内容写入Txt文档 foreach (Comment comment in doc.Comments) { foreach (Paragraph p in comment.Body.Paragraphs) { SB.AppendLine(p.Text); } } File.WriteAllText("CommentExtraction.txt", SB.ToString()); System.Diagnostics.Process.Start("CommentExtraction.txt"); C# 全部代码: using System.Text; using System.IO; using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; namespace ExtractComments { class Program { static void Main(string[] args) { //创建实例,加载文档 Document doc = new Document(); doc.LoadFromFile("test.docx"); //实例化StringBuilder类 StringBuilder SB = new StringBuilder(); //遍历所有word批注,将批注内容写入Txt文档 foreach (Comment comment in doc.Comments) { foreach (Paragraph p in comment.Body.Paragraphs) { SB.AppendLine(p.Text); } } File.WriteAllText("CommentExtraction.txt", SB.ToString()); System.Diagnostics.Process.Start("CommentExtraction.txt"); } } } View Code VB.NET 代码 Imports System.Text Imports System.IO Imports Spire.Doc Imports Spire.Doc.Documents Imports Spire.Doc.Fields Namespace ExtractComments Class Program Private Shared Sub Main(ByVal args As String()) Dim doc As Document = New Document() doc.LoadFromFile("test.docx") Dim SB As StringBuilder = New StringBuilder() For Each comment As Comment In doc.Comments For Each p As Paragraph In comment.Body.Paragraphs SB.AppendLine(p.Text) Next Next File.WriteAllText("CommentExtraction.txt", SB.ToString()) System.Diagnostics.Process.Start("CommentExtraction.txt") End Sub End Class End Namespace View Code 3. 回复Word批注内容 步骤 1 :添加using指令 using Spire.Doc; using Spire.Doc.Fields; 步骤 2 :创建实例 Document doc = new Document(); doc.LoadFromFile("test.docx"); 步骤 3 :获取批注 Comment comment = doc.Comments[0]; 步骤 4 :回复批注 Comment replyComment = new Comment(doc); replyComment.Format.Author = "Adam"; replyComment.Body.AddParagraph().AppendText("这条批注内容请再丰富一下,内容有些单调"); comment.ReplyToComment(replyComment); 步骤 5 :保存文件 doc.SaveToFile("ReplyToComment.docx", FileFormat.Docx2013); System.Diagnostics.Process.Start("ReplyToComment.docx"); 测试结果: C# 全部代码: using Spire.Doc; using Spire.Doc.Fields; namespace ReplyComment_Doc { class Program { static void Main(string[] args) { //实例化Document类,加载文件 Document doc = new Document(); doc.LoadFromFile("test.docx"); //获取第一个批注 Comment comment = doc.Comments[0]; //实例化Comment类,添加批注回复作者以及回复内容 Comment replyComment = new Comment(doc); replyComment.Format.Author = "Adam"; replyComment.Body.AddParagraph().AppendText("这条批注内容请再丰富一下,内容有些单调"); comment.ReplyToComment(replyComment); //保存文件并打开 doc.SaveToFile("ReplyToComment.docx", FileFormat.Docx2013); System.Diagnostics.Process.Start("ReplyToComment.docx"); } } } View Code VB.NET 代码: Imports Spire.Doc Imports Spire.Doc.Fields Namespace ReplyComment_Doc Class Program Private Shared Sub Main(ByVal args As String()) Dim doc As Document = New Document() doc.LoadFromFile("test.docx") Dim comment As Comment = doc.Comments(0) Dim replyComment As Comment = New Comment(doc) replyComment.Format.Author = "Adam" replyComment.Body.AddParagraph().AppendText("这条批注内容请再丰富一下,内容有些单调") comment.ReplyToComment(replyComment) doc.SaveToFile("ReplyToComment.docx", FileFormat.Docx2013) System.Diagnostics.Process.Start("ReplyToComment.docx") End Sub End Class End Namespace View Code 以上为本次关于操作Word批注的全部内容。 (本文完) 如需转载,请注明出处。
简介 我们可以通过代码编程来对Excel工作表实现很多操作,在下面的示例中,将介绍如何来添加Excel页眉、页脚。在页眉处,我们可以添加文字,如公司名称、页码、工作表名、日期等,也可以添加图片,如LOGO、标记等,页脚同理。另外,对于一些个性化的需求,我们也可以设置奇偶页页眉页脚不同、文字格式化(如,设置字体、字号、字体颜色、字体加粗等)操作。 示例所用工具: Free Spire.XLS for .NET 8.3 (社区版) Visual Studio PS:Spire.XLS提供了以下特殊脚本语言来动态地显示内容,如当前页码、总页数、日期、工作表名等,同时也可以用对文本进行格式化操作。 脚本 描述 &P The current page number 当前页数 &N The total number of pages 总页数 &D The current data 当前数据 &T The current time 当前日期 &G A picture 图片 &A The worksheet name 工作表名 &F The file name 文件名 &B Make text bold 文本加粗 &I Italicize text 文本倾斜 &U Underline text 文本下划线 &"font name" Represents a font name, for example, &"Aril" 字体名称 &font size Represents font size, for example, &12 字体大小 &K<HEX color> Represents font color, for example, &KFF0000 字体颜色 示例代码(供参考) 1. 插入页眉页脚 C# 步骤1:创建一个Workbook,加载文档 Workbook wb = new Workbook(); wb.LoadFromFile("test.xlsx"); 步骤2:获取第一个工作表 Worksheet sheet = wb.Worksheets[0]; 步骤3:添加文本到页眉页脚 //设置文本在页眉页脚处的位置 string text1 = sheet.PageSetup.RightHeader; string text2 = sheet.PageSetup.CenterFooter; //设置文本字体、字号、颜色等 text1 = "&\"华文琥珀\"&15 & @天府文化传媒 "; text2 = "&\"Arial Unicode MS\"&9 &KFF0000 注:资料解释权归本公司版权所有 "; 步骤4:应用文本到页眉页脚 sheet.PageSetup.LeftHeader = text1; sheet.PageSetup.RightFooter = text2; 步骤5: 添加图片到页眉页脚 //加载图片,并设置图片大小 Image image = Image.FromFile("logo.png"); Bitmap bitmap = new Bitmap(image, new Size(image.Width / 6, image.Height / 6)); //添加图片到页眉右边的单元格 sheet.PageSetup.RightHeaderImage = bitmap; sheet.PageSetup.RightHeader = "&G"; 步骤6: 保存文档 wb.SaveToFile("页眉页脚.xlsx", ExcelVersion.Version2013); System.Diagnostics.Process.Start("页眉页脚.xlsx"); 添加效果: 页眉: 页脚: 全部代码: using Spire.Xls; using System.Drawing; using System.IO; namespace InsertHeader_XLS { class Program { static void Main(string[] args) { //创建一个Workbook,加载文档 Workbook wb = new Workbook(); wb.LoadFromFile("test.xlsx"); //获取第一个工作表 Worksheet sheet = wb.Worksheets[0]; //添加文本到页眉、页脚 string text1 = sheet.PageSetup.RightHeader; string text2 = sheet.PageSetup.CenterFooter; //设置文本字体、字号、颜色等 text1 = "&\"华文琥珀\"&15 & @天府文化传媒 "; text2 = "&\"Arial Unicode MS\"&9 &KFF0000 注:资料解释权归本公司版权所有 "; //应用文本到页眉、页脚 sheet.PageSetup.LeftHeader = text1; sheet.PageSetup.RightFooter = text2; //加载图片,并设置图片大小 Image image = Image.FromFile("logo.png"); Bitmap bitmap = new Bitmap(image, new Size(image.Width / 6, image.Height / 6)); //添加图片到页眉右边的单元格 sheet.PageSetup.RightHeaderImage = bitmap; sheet.PageSetup.RightHeader = "&G"; //保存并打开文档 wb.SaveToFile("页眉页脚.xlsx", ExcelVersion.Version2013); System.Diagnostics.Process.Start("页眉页脚.xlsx"); } } } View Code 2. 设置奇偶页不同页眉页脚 步骤1:创建工作簿,获取工作表 Workbook wb = new Workbook(); Worksheet sheet = wb.Worksheets[0]; 步骤2:添加文本到指定单元格,生成文档 sheet.Range["A1"].Text = "第一页"; sheet.Range["K1"].Text = "第二页"; 步骤3:设置属性值 //将DifferentOddEven的值设为1, 表示奇数页和偶数页可以分别设置页眉页脚 sheet.PageSetup.DifferentOddEven = 1; 步骤4:添加页眉页脚 //设置奇数页页眉页脚,并设置文本格式 sheet.PageSetup.OddHeaderString = "&\"Arial\"&12 &B &K000000奇数_页眉"; sheet.PageSetup.OddFooterString = "&\"Arial\"&12 &B &K000000奇数_页脚"; //设置偶数页页眉页脚,并设置文本格式 sheet.PageSetup.EvenHeaderString = "&\"Arial\"&12 &B &K000000偶数_页眉"; sheet.PageSetup.EvenFooterString = "&\"Arial\"&12 &B &K000000偶数_页脚"; 步骤5: 保存文件 wb.SaveToFile("奇偶页眉页脚.xlsx", ExcelVersion.Version2013); System.Diagnostics.Process.Start("奇偶页眉页脚.xlsx"); 添加效果: 页眉 页脚效果: 全部代码: using Spire.Xls; namespace InsertHeaderFooter2_XLS { class Program { static void Main(string[] args) { //创建一个Workbook Workbook wb = new Workbook(); //获取第一个工作表 Worksheet sheet = wb.Worksheets[0]; //添加文本到A1(生成第一页) sheet.Range["A1"].Text = "第一页"; //添加文本到K1(生成第二页) sheet.Range["K1"].Text = "第二页"; //将DifferentOddEven的值设为1, 表示奇数页和偶数页可以分别设置页眉页脚 sheet.PageSetup.DifferentOddEven = 1; //设置奇数页页眉页脚,并设置文本格式 sheet.PageSetup.OddHeaderString = "&\"Arial\"&12 &B &K000000奇数_页眉"; sheet.PageSetup.OddFooterString = "&\"Arial\"&12 &B &K000000奇数_页脚"; //设置偶数页页眉页脚,并设置文本格式 sheet.PageSetup.EvenHeaderString = "&\"Arial\"&12 &B &K000000偶数_页眉"; sheet.PageSetup.EvenFooterString = "&\"Arial\"&12 &B &K000000偶数_页脚"; //保存并打开文档 wb.SaveToFile("奇偶页眉页脚.xlsx", ExcelVersion.Version2013); System.Diagnostics.Process.Start("奇偶页眉页脚.xlsx"); } } } View Code 注意:Excel页眉或页脚在普通浏览模式下不可见,它们仅仅在页面布局模式或者打印预览模式才可见。 以上全部为本次关于C#添加Excel页眉、页脚的内容。 感谢阅读! (如需转载,请注明出处!)
通过对控件Spire.PDF的测试,我们可以创建PDF文件并向文档中绘制文本、图片、表格、图形等内容,其中,对于绘制文本这一部分,Spire.PDF提供了三种字体类型来绘制文本,即: Standard fonts TrueType fonts Chinese, Japanese and Korean (CJK) fonts 从以上类中我们可以发现,是可以支持中、日、韩、英等字体类的,这为我们在操作PDF文件上提供了更多可能。在这篇文章中,“利用private font改变PDF文件的字体”中讲述了如何应用字体,在接下来的文章中,将介绍如何运用Spire.PDF提供的字体类来绘制不同风格类型的文本。 使用工具:Spire.PDF for .NET 4.0 PS: 安装该类库后,注意在程序中引用Spire.PDF.dll后在进行代码编辑,dll文件可在安装路径下的Bin文件夹中获取。 【示例1】绘制倾斜样式的文本 步骤1:创建实例 PdfDocument doc = new PdfDocument(); PdfPageBase page = doc.Pages.Add(); 步骤2:保存画布状态 PdfGraphicsState state = page.Canvas.Save(); 步骤3:实例化字体,创建格式刷 PdfFont font = new PdfFont(PdfFontFamily.Helvetica, 18f); PdfSolidBrush brush1 = new PdfSolidBrush(Color.DeepSkyBlue); PdfSolidBrush brush2 = new PdfSolidBrush(Color.CadetBlue); PdfSolidBrush brush3 = new PdfSolidBrush(Color.LightPink); 步骤4:指定文本在画布上的坐标,并指定文本的横向、纵向的拉伸度 page.Canvas.TranslateTransform(10, 100); page.Canvas.ScaleTransform(1f, 0.6f); 步骤5:绘制文本 //绘制倾斜样式的文本 page.Canvas.SkewTransform(-10, 0); page.Canvas.DrawString("THERE IS NO ROYAL ROAD TO LEARNING. ", font, brush1, 0, 0); page.Canvas.SkewTransform(10, 10); page.Canvas.DrawString("Books, like friends, should be few and well chosen. ", font, brush2, 10, 50); //绘制缩放类型的文本 page.Canvas.ScaleTransform(1f, -1f); page.Canvas.DrawString("Books, like friends, should be few and well chosen.", font, brush3, 10, -2 * 50); 步骤6:再次保存画布 page.Canvas.Restore(state); 步骤7:保存文件 doc.SaveToFile("DrawText.pdf"); System.Diagnostics.Process.Start("DrawText.pdf"); 测试效果: 全部代码: using Spire.Pdf; using Spire.Pdf.Graphics; using System.Drawing; namespace DrawTextOfDifferentStyles_PDF { class Program { static void Main(string[] args) { PdfDocument doc = new PdfDocument(); //创建一个PDF文档 PdfPageBase page = doc.Pages.Add(); //添加页 PdfGraphicsState state = page.Canvas.Save(); //实例化字体,创建格式刷 PdfFont font = new PdfFont(PdfFontFamily.Helvetica, 18f); PdfSolidBrush brush1 = new PdfSolidBrush(Color.DeepSkyBlue); PdfSolidBrush brush2 = new PdfSolidBrush(Color.CadetBlue); PdfSolidBrush brush3 = new PdfSolidBrush(Color.LightPink); page.Canvas.TranslateTransform(10, 100);//指定文本在画布上的坐标位置 page.Canvas.ScaleTransform(1f, 0.6f);//指定文本的横向、纵向的拉伸度 //绘制倾斜样式的文本 page.Canvas.SkewTransform(-10, 0); page.Canvas.DrawString("THERE IS NO ROYAL ROAD TO LEARNING. ", font, brush1, 0, 0); page.Canvas.SkewTransform(10, 10); page.Canvas.DrawString("Books, like friends, should be few and well chosen. ", font, brush2, 10, 50); //绘制缩放类型的文本 page.Canvas.ScaleTransform(1f, -1f); page.Canvas.DrawString("Books, like friends, should be few and well chosen.", font, brush3, 10, -2 * 50); //再次保存画布 page.Canvas.Restore(state); //保存并打开文档 doc.SaveToFile("DrawText.pdf"); System.Diagnostics.Process.Start("DrawText.pdf"); } } } View Code 【示例2】绘制中心旋转图形 步骤1:创建实例 PdfDocument doc = new PdfDocument(); PdfPageBase page = doc.Pages.Add(); 步骤2:保存画布 PdfGraphicsState state = page.Canvas.Save(); 步骤3:实例化字体类,创建格式刷 PdfFont font = new PdfFont(PdfFontFamily.Helvetica, 10f); PdfSolidBrush brush = new PdfSolidBrush(Color.BlueViolet); 步骤4:设定字符串布局格式,并指定文本在画布中的位置 PdfStringFormat centerAlignment = new PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Middle); float x = 400; float y = 600;page.Canvas.TranslateTransform(x, y); 步骤5:绘制文本,应用格式 //指定文本绘制数量 for (int i = 0; i < 12; i++) { //设置文本按顺时针方向旋转排列(文本偏移间隔30度) page.Canvas.RotateTransform(30); //绘制文本并应用格式 page.Canvas.DrawString("Every tide has its ebb.", font, brush, 10, 0, centerAlignment); } 步骤6:再次保存画布 page.Canvas.Restore(state); 步骤7:保存文档 doc.SaveToFile("DrawText.pdf"); System.Diagnostics.Process.Start("DrawText.pdf"); 测试结果: (这里做了几个不同样式的demo,可以对比看下效果) 全部代码: using Spire.Pdf; using Spire.Pdf.Graphics; using System.Drawing; namespace _3 { class Program { static void Main(string[] args) { PdfDocument doc = new PdfDocument(); //创建一个PDF文档 PdfPageBase page = doc.Pages.Add(); //添加页 PdfGraphicsState state = page.Canvas.Save(); //实例化字体,创建格式刷 PdfFont font = new PdfFont(PdfFontFamily.Helvetica, 10f); PdfSolidBrush brush = new PdfSolidBrush(Color.BlueViolet); //设定字符串布局格式,并指定文本在画布中的位置 PdfStringFormat centerAlignment = new PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Middle); float x = 400; float y = 600; //绘制文本并应用格式 page.Canvas.TranslateTransform(x, y); //指定文本绘制数量 for (int i = 0; i < 12; i++) { //设置文本按顺时针方向旋转排列(文本偏移间隔30度) page.Canvas.RotateTransform(30); //绘制文本并应用格式 page.Canvas.DrawString("Every tide has its ebb.", font, brush, 10, 0, centerAlignment); } //再次保存画布 page.Canvas.Restore(state); //保存并打开文档 doc.SaveToFile("DrawText.pdf"); System.Diagnostics.Process.Start("DrawText.pdf"); } } } View Code 以上是本次关于绘制不同风格类型文本的全部内容,如需转载,请注明出处。 (本文完)
简介 超链接能够快速地将当前文本或图片链接到指定目标地址,在日常办公中给我们提供了极大的便利。本文将介绍在C#语言中如何通过免费版组件对Excel表格添加超链接,示例中将包含以下要点: 1.添加链接到网页(文本、图片) 1.1 链接到文本 1.2 链接到图片 2.添加链接到指定文档 3.添加链接到指定单元格 使用工具 Free Spire.XLS for .NET 8.3(社区版) Visual Studio PS:下载安装该组件,并添加引用该组件Spire.Xls.dll到项目程序即可(如下图),dll文件可在安装路径下的Bin文件夹中获取。 示例代码操作 1.添加链接到网页 (这里分两种情况,添加文本链接和图片链接。) 1.1添加超链接到文本字符串 步骤1:创建Excel,获取工作表 Workbook wb = new Workbook(); Worksheet sheet = wb.Worksheets[0]; 步骤2:获取单元格,添加文本并设置对齐方式 sheet.Range["A1"].Text = "绿色交通(Green Transpotation)"; sheet.Range["A1"].Style.VerticalAlignment = VerticalAlignType.Bottom; 步骤3:设置超链接到指定单元格 HyperLink UrlLink = sheet.HyperLinks.Add(sheet.Range["A1"]); UrlLink.TextToDisplay = sheet.Range["A1"].Text; UrlLink.Type = HyperLinkType.Url; UrlLink.Address = "https://baike.baidu.com/item"; 1.2 链接到图片 步骤1:初始化一个string类,加载图片 string picPath = @"C:\Users\Administrator\Desktop\images\th.jpg"; 步骤2:将图片添加到A1单元格,并设置超链接 ExcelPicture picture = sheet.Pictures.Add(1, 1, picPath); picture.SetHyperLink("https://en.wikipedia.org/wiki/Sustainable_transport", true); 步骤3:调整图片在单元格中的位置 sheet.Columns[0].ColumnWidth = 28; sheet.Rows[0].RowHeight = 100; picture.TopRowOffset = 30; 最后,保存文档 wb.SaveToFile("Hyperlink.xlsx", ExcelVersion.Version2013); System.Diagnostics.Process.Start("Hyperlink.xlsx"); 调试运行该项目程序后,生成文档,如下图所示: 全部代码: using Spire.Xls; namespace TextHyperlink_XLS { class Program { static void Main(string[] args) { //添加文本超链接 //创建一个Workbook类对象,获取第一个工作表 Workbook wb = new Workbook(); Worksheet sheet = wb.Worksheets[0]; //获取第一个单元格添加文本并设置文本对齐方式 sheet.Range["A1"].Text = "绿色交通(Green Transpotation)"; sheet.Range["A1"].Style.VerticalAlignment = VerticalAlignType.Bottom; //创建一个超链接类对象,在A1单元格设置文本超链接 HyperLink UrlLink = sheet.HyperLinks.Add(sheet.Range["A1"]); UrlLink.TextToDisplay = sheet.Range["A1"].Text; UrlLink.Type = HyperLinkType.Url; UrlLink.Address = "https://baike.baidu.com/item"; //添加图片超链接。 //初始化一个string类,加载图片 string picPath = @"C:\Users\Administrator\Desktop\images\th.jpg"; //将图片添加到A1单元格,并设置超链接 ExcelPicture picture = sheet.Pictures.Add(1, 1, picPath); picture.SetHyperLink("https://en.wikipedia.org/wiki/Sustainable_transport", true); //设置图片在单元格中的位置 sheet.Columns[0].ColumnWidth = 28; sheet.Rows[0].RowHeight = 100; picture.TopRowOffset = 30; //保存并打开文件 wb.SaveToFile("Hyperlink.xlsx", ExcelVersion.Version2013); System.Diagnostics.Process.Start("Hyperlink.xlsx"); } } } View Code 2.添加链接到文档 【C#】 //实例化一个Workbook类并加载Excel文档 Workbook workbook = new Workbook(); workbook.LoadFromFile(@"C:\Users\Administrator\Desktop\Sample.xlsx"); //获取第一个工作表 Worksheet sheet = workbook.Worksheets[0]; //设置超链接到指定单元格 CellRange range = sheet.Range["E2"]; HyperLink FileLink = sheet.HyperLinks.Add(range); FileLink.Type = HyperLinkType.File; FileLink.TextToDisplay = sheet.Range["E2"].Text; FileLink.Address = @"C:\Users\Administrator\Desktop\test.docx"; //保存并打开文档 workbook.SaveToFile("FileLink.xlsx"); System.Diagnostics.Process.Start("FileLink.xlsx"); 效果示例: 3.添加链接到指定单元格 【C#】 //新建一个Excel类对象,加载Excel文档,获取第一个工作表 Workbook workbook = new Workbook(); workbook.LoadFromFile(@"C:\Users\Administrator\Desktop\Sample.xlsx"); Worksheet sheet = workbook.Worksheets[0]; //获取指定单元格,链接至指定文档中的特定单元格 CellRange range = sheet.Range["E2"]; HyperLink WbLink = sheet.HyperLinks.Add(range); WbLink.Type = HyperLinkType.Workbook; WbLink.TextToDisplay = "已清算"; WbLink.Address = "A账目明细!A1"; //保存并打开文档 workbook.SaveToFile("LinktoCell.xlsx", ExcelVersion.Version2013); System.Diagnostics.Process.Start("LinktoCell.xlsx"); 效果展示: 4.添加链接Unc路径 【C#】 //创建一个Workbook类对象,加载Excel文档,获取第二个工作表 Workbook workbook = new Workbook(); workbook.LoadFromFile(@"C:\Users\Administrator\Desktop\Sample.xlsx"); Worksheet sheet = workbook.Worksheets[1]; //添加Unc链接至A1单元格,设置连接类型为Unc,添加显示文本及链接路径 CellRange range = sheet.Range["A1"]; HyperLink UncLink = sheet.HyperLinks.Add(range); UncLink.Type = HyperLinkType.Unc; UncLink.TextToDisplay = "地址"; UncLink.Address = "\\192.168.1.118"; //保存文档 workbook.SaveToFile("LinktoUnc.xls"); 效果示例: 以上是关于添加Excel超链接的全部内容。 <本文完> 如需转载,请注明出处。
概述 为文档添加必要的批注可以给文档使用者提供重要的提示信息,下面的示例中,将介绍通过C#编程语言来给Excel表格中的指定单元格内容添加批注,此外,对于已有的批注,如果需要修改,我们也可以进行编辑或者删除批注。示例内容将包含以下主要内容: 1.插入批注 1.1 插入文本 1.2 插入图片 2.编辑批注 2.1 修改批注内容 2.1 设置批注可见性 3.删除批注 工具 Spire.XLS for .NET 8.0 提示:在进行代码操作之前,需下载安装Spire.Xls,并添加引用dll文件,添加如下using指令 using System; using Spire.Xls; using System.Drawing; 代码示例(供参考) 1.插入Excel批注 【C#】 步骤1:实例化一个Workbook类实例并加载Excel文档 Workbook workbook = new Workbook(); workbook.LoadFromFile("test.xlsx"); 步骤2:获取第一个工作表 Worksheet sheet = workbook.Worksheets[0]; 步骤3:插入文本批注 string comment = "注意:\n 责任人兼设备维护人";//设置批注文本 ExcelFont font = workbook.CreateFont();//设置批注字体格式 font.FontName = "Calibri"; font.Color = Color.Black; font.IsBold = true; CellRange range = sheet.Range["I3"];//添加批注到指定单元格 range.Comment.RichText.Text = comment; range.Comment.Width = 200; range.Comment.Height = 50; range.Comment.RichText.SetFont(10, 10, font); 步骤4:插入图片批注 //加载图片,将图片插入到指定单元格的批注 Image image = Image.FromFile("logo.png"); sheet.Range["B2"].Comment.Fill.CustomPicture(image, "logo.png"); sheet.Range["B2"].Comment.Height = image.Height; sheet.Range["B2"].Comment.Width = image.Width; 步骤5:保存文档 workbook.SaveToFile("AddComment.xlsx", ExcelVersion.Version2013); System.Diagnostics.Process.Start("AddComment.xlsx"); 批注插入效果(如下图): 全部代码: using System; using Spire.Xls; using System.Drawing; namespace ModifyComment_XLS { class Program { static void Main(string[] args) { //实例化一个Workbook类实例并加载Excel文档 Workbook workbook = new Workbook(); workbook.LoadFromFile("test.xlsx"); //获取第一个工作表 Worksheet sheet = workbook.Worksheets[0]; //设置批注文本 string comment = "注意:\n 责任人兼设备维护人"; //设置批注字体 ExcelFont font = workbook.CreateFont(); font.FontName = "Calibri"; font.Color = Color.Black; font.IsBold = true; //添加批注到指定单元格 CellRange range = sheet.Range["I3"]; range.Comment.RichText.Text = comment; range.Comment.Width = 200; range.Comment.Height = 50; range.Comment.RichText.SetFont(10, 10, font); //加载图片,将图片插入到指定单元格的批注 Image image = Image.FromFile("logo.png"); sheet.Range["B2"].Comment.Fill.CustomPicture(image, "logo.png"); sheet.Range["B2"].Comment.Height = image.Height; sheet.Range["B2"].Comment.Width = image.Width; //保存并打开文档 workbook.SaveToFile("AddComment.xlsx", ExcelVersion.Version2013); System.Diagnostics.Process.Start("AddComment.xlsx"); } } } View Code 2. 修改、隐藏Excel批注 【C#】 步骤1:创建一个Workbook类对象,并加载Excel文档 Workbook workbook = new Workbook(); workbook.LoadFromFile("AddComment.xlsx"); 步骤2:获取第一个工作表 Worksheet sheet = workbook.Worksheets[0]; 步骤3:修改工作表中的第一个批注 ExcelComment comment0 = workbook.Worksheets[0].Comments[0]; sheet.Comments[0].Text = "This is a new comment"; 步骤4:设置批注可见性(隐藏、显示) //设置指定批注可见(显示) sheet.Comments[0].IsVisible = true; //设置指定批注不可见(隐藏) sheet.Comments[1].IsVisible = false; 步骤5:保存文档 workbook.SaveToFile("ModifyComment.xlsx", ExcelVersion.Version2013); System.Diagnostics.Process.Start("ModifyComment.xlsx"); 效果图: 全部代码: using System; using Spire.Xls; using System.Drawing; namespace ModifyComment_XLS { class Program { static void Main(string[] args) { //创建一个Workbook类对象,并加载Excel文档 Workbook workbook = new Workbook(); workbook.LoadFromFile("AddComment.xlsx"); //获取第一个工作表 Worksheet sheet = workbook.Worksheets[0]; //修改工作表中的第一个批注 ExcelComment comment0 = workbook.Worksheets[0].Comments[0]; sheet.Comments[0].Text = "This is a new comment"; //设置指定批注不可见(隐藏) sheet.Comments[0].IsVisible = true; //设置指定批注可见(显示) sheet.Comments[1].IsVisible = false; //保存并打开文档 workbook.SaveToFile("ModifyComment.xlsx", ExcelVersion.Version2013); System.Diagnostics.Process.Start("ModifyComment.xlsx"); } } } View Code 3.删除Excel批注 【C#】 //实例化Wordbook类实例并加载Excel文档 Workbook workbook = new Workbook(); workbook.LoadFromFile("Comments.xlsx"); //获取第一个工作表 Worksheet sheet = workbook.Worksheets[0]; //删除工作表中的第2个批注 sheet.Comments[1].Remove(); //保存并打开文档 workbook.SaveToFile("RemoveComment.xlsx", ExcelVersion.Version2013); System.Diagnostics.Process.Start("RemoveComment.xlsx"); 以上全部为本篇文章的全部内容。 如需转载请注明出处。 <本文完>
一、序言 在Office Word中,支持在Word文档中插入类型非常丰富的形状,包括线条、矩形、基本形状(诸如圆形、多边形、星形、括号、笑脸等等图形)、箭头形状、公式形状、流程图、旗帜图形、标注图形等等,我们在编程过程中,想要在Word中绘制不同类型的图形,可以通过类库来操作。控件Spire.Doc for .NET 6.0及以上版本开始支持Office Word中的所有图形,可以通过代码操作某个单一的形状,也可以通过将单一形状进行组合来获得想要的图形或形状效果,当然,也支持自己自定义图形,通过编程绘制也是可以的。下面将介绍向Word绘制形状和组合形状的方法,方法中的代码供参考。 PS: Spire.Doc for .NET获取地址 安装后,dll文件可在安装路径下的Bin文件夹中获取 Dll引用 二、代码示例 (一)绘制单一形状 步骤1:添加如下using指定 using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; using System.Drawing; 步骤2:创建示例,添加section、paragraph //创建一个Document实例 Document doc = new Document(); //添加一个section paragraph Section sec = doc.AddSection(); Paragraph para1 = sec.AddParagraph(); 步骤3:在文档指定位置插入形状,并设置形状类型、大小、填充颜色、线条样式等 (这里简单列举几个形状的添加方法,方法比较简单,不做赘述,效果图中列举了部分形状样式,需要其他样式的形状可自行设置添加) //插入一个矩形 ShapeObject shape1 = para1.AppendShape(50, 50, ShapeType.Rectangle); shape1.FillColor = Color.Blue; shape1.StrokeColor = Color.LightSkyBlue; shape1.HorizontalPosition = 20; shape1.VerticalPosition = 20; //插入一个圆形 ShapeObject shape2 = para1.AppendShape(50, 50, ShapeType.Ellipse); shape2.FillColor = Color.Purple; shape2.StrokeColor = Color.LightPink; shape2.LineStyle = ShapeLineStyle.Single; shape2.StrokeWeight = 1; shape2.HorizontalPosition = 80; shape2.VerticalPosition = 20; //插入一个公式符号 + ShapeObject shape3 = para1.AppendShape(50, 50, ShapeType.Plus); shape3.FillColor = Color.DarkCyan; shape3.StrokeColor = Color.LightGreen; shape3.LineStyle = ShapeLineStyle.Single; shape3.StrokeWeight = 1; shape3.HorizontalPosition = 140; shape3.VerticalPosition = 20; //插入一颗星形 ShapeObject shape4 = para1.AppendShape(50, 50, ShapeType.Star); shape4.FillColor = Color.Red; shape4.StrokeColor = Color.Gold; shape4.LineStyle = ShapeLineStyle.Single; shape4.HorizontalPosition = 200; shape4.VerticalPosition = 20; 步骤4:保存文档 //保存并打开文档 doc.SaveToFile("InsertShapes.docx", FileFormat.Docx2010); System.Diagnostics.Process.Start("InsertShapes.docx"); 形状添加效果: 全部代码: 1 using Spire.Doc; 2 using Spire.Doc.Documents; 3 using Spire.Doc.Fields; 4 using System.Drawing; 5 6 namespace AddShapes_Doc 7 { 8 class Program 9 { 10 static void Main(string[] args) 11 { 12 //创建一个Document实例 13 Document doc = new Document(); 14 15 //添加一个section paragraph 16 Section sec = doc.AddSection(); 17 Paragraph para1 = sec.AddParagraph(); 18 19 //插入一个矩形 20 ShapeObject shape1 = para1.AppendShape(50, 50, ShapeType.Rectangle); 21 shape1.FillColor = Color.Blue; 22 shape1.StrokeColor = Color.LightSkyBlue; 23 shape1.HorizontalPosition = 20; 24 shape1.VerticalPosition = 20; 25 26 //插入一个圆形 27 ShapeObject shape2 = para1.AppendShape(50, 50, ShapeType.Ellipse); 28 shape2.FillColor = Color.Purple; 29 shape2.StrokeColor = Color.LightPink; 30 shape2.LineStyle = ShapeLineStyle.Single; 31 shape2.StrokeWeight = 1; 32 shape2.HorizontalPosition = 80; 33 shape2.VerticalPosition = 20; 34 35 //插入一个公式符号 + 36 ShapeObject shape3 = para1.AppendShape(50, 50, ShapeType.Plus); 37 shape3.FillColor = Color.DarkCyan; 38 shape3.StrokeColor = Color.LightGreen; 39 shape3.LineStyle = ShapeLineStyle.Single; 40 shape3.StrokeWeight = 1; 41 shape3.HorizontalPosition = 140; 42 shape3.VerticalPosition = 20; 43 44 //插入一颗星形 45 ShapeObject shape4 = para1.AppendShape(50, 50, ShapeType.Star); 46 shape4.FillColor = Color.Red; 47 shape4.StrokeColor = Color.Gold; 48 shape4.LineStyle = ShapeLineStyle.Single; 49 shape4.HorizontalPosition = 200; 50 shape4.VerticalPosition = 20; 51 52 //插入一个立方体 53 ShapeObject shape5 = para1.AppendShape(50, 50, ShapeType.Cube); 54 shape5.FillColor = Color.OrangeRed; 55 shape5.StrokeColor = Color.Orange; 56 shape5.LineStyle = ShapeLineStyle.Single; 57 shape5.HorizontalPosition = 260; 58 shape5.VerticalPosition = 20; 59 60 //插入一个圆柱体 61 ShapeObject shape6 = para1.AppendShape(50, 50, ShapeType.Can); 62 shape6.FillColor = Color.Goldenrod; 63 shape6.StrokeColor = Color.Gold; 64 shape6.LineStyle = ShapeLineStyle.Single; 65 shape6.HorizontalPosition = 320; 66 shape6.VerticalPosition = 20; 67 68 //插入一个箭头 69 ShapeObject shape7 = para1.AppendShape(50, 50, ShapeType.Arrow); 70 shape7.FillColor = Color.Yellow; 71 shape7.StrokeColor = Color.Yellow; 72 shape7.LineStyle = ShapeLineStyle.Single; 73 shape7.HorizontalPosition = 20; 74 shape7.VerticalPosition = 80; 75 76 //插入一个v形臂章图形 77 ShapeObject shape8 = para1.AppendShape(50, 50, ShapeType.Chevron); 78 shape8.FillColor = Color.YellowGreen; 79 shape8.StrokeColor = Color.Yellow; 80 shape8.LineStyle = ShapeLineStyle.Single; 81 shape8.HorizontalPosition = 80; 82 shape8.VerticalPosition = 80; 83 84 //插入一个循环箭头图形 85 ShapeObject shape9 = para1.AppendShape(50, 50, ShapeType.CircularArrow); 86 shape9.FillColor = Color.Green; 87 shape9.StrokeColor = Color.Yellow; 88 shape9.LineStyle = ShapeLineStyle.Single; 89 shape9.HorizontalPosition = 140; 90 shape9.VerticalPosition = 80; 91 92 //插入一个云图形 93 ShapeObject shape10 = para1.AppendShape(50, 50, ShapeType.CloudCallout); 94 shape10.FillColor = Color.LightSkyBlue; 95 shape10.StrokeColor = Color.White; 96 shape10.LineStyle = ShapeLineStyle.Single; 97 shape10.HorizontalPosition = 200; 98 shape10.VerticalPosition = 80; 99 100 //插入一个环形图 101 ShapeObject shape11 = para1.AppendShape(50, 50, ShapeType.Donut); 102 shape11.FillColor = Color.Pink; 103 shape11.StrokeColor = Color.White; 104 shape11.LineStyle = ShapeLineStyle.Single; 105 shape11.HorizontalPosition = 260; 106 shape11.VerticalPosition = 80; 107 108 //插入一个波浪形状图 109 ShapeObject shape12 = para1.AppendShape(50, 50, ShapeType.DoubleWave); 110 shape12.FillColor = Color.Plum; 111 shape12.StrokeColor = Color.White; 112 shape12.LineStyle = ShapeLineStyle.Single; 113 shape12.HorizontalPosition = 320; 114 shape12.VerticalPosition = 80; 115 116 //插入一个礼结状图形 117 ShapeObject shape13 = para1.AppendShape(50, 50, ShapeType.EllipseRibbon); 118 shape13.FillColor = Color.RosyBrown; 119 shape13.StrokeColor = Color.White; 120 shape13.LineStyle = ShapeLineStyle.Single; 121 shape13.HorizontalPosition = 20; 122 shape13.VerticalPosition = 140; 123 124 //插入一个心形图 125 ShapeObject shape14 = para1.AppendShape(50, 50, ShapeType.Heart); 126 shape14.FillColor = Color.Red; 127 shape14.StrokeColor = Color.White; 128 shape14.LineStyle = ShapeLineStyle.Single; 129 shape14.HorizontalPosition = 80; 130 shape14.VerticalPosition = 140; 131 132 //插入一个六边形图形 133 ShapeObject shape15 = para1.AppendShape(50, 50, ShapeType.Hexagon); 134 shape15.FillColor = Color.DarkCyan; 135 shape15.StrokeColor = Color.White; 136 shape15.LineStyle = ShapeLineStyle.Single; 137 shape15.HorizontalPosition = 140; 138 shape15.VerticalPosition = 140; 139 140 //插入一个不规则图形 141 ShapeObject shape16 = para1.AppendShape(50, 50, ShapeType.IrregularSeal1); 142 shape16.FillColor = Color.DeepPink; 143 shape16.StrokeColor = Color.White; 144 shape16.LineStyle = ShapeLineStyle.Single; 145 shape16.HorizontalPosition = 200; 146 shape16.VerticalPosition = 140; 147 148 //插入一个月亮形状 149 ShapeObject shape17 = para1.AppendShape(50, 50, ShapeType.Moon); 150 shape17.FillColor = Color.Violet; 151 shape17.StrokeColor = Color.White; 152 shape17.LineStyle = ShapeLineStyle.Single; 153 shape17.HorizontalPosition = 260; 154 shape17.VerticalPosition = 140; 155 156 //插入一个"禁止"形状 157 ShapeObject shape18 = para1.AppendShape(50, 50, ShapeType.NoSmoking); 158 shape18.FillColor = Color.Yellow; 159 shape18.StrokeColor = Color.Goldenrod; 160 shape18.LineStyle = ShapeLineStyle.Single; 161 shape18.HorizontalPosition = 320; 162 shape18.VerticalPosition = 140; 163 164 //保存并打开文档 165 doc.SaveToFile("InsertShapes.docx", FileFormat.Docx2010); 166 System.Diagnostics.Process.Start("InsertShapes.docx"); 167 } 168 } 169 } View Code (二)添加组合形状 步骤1:添加如下using指令 using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; using System.Drawing; 步骤2:创建文档,添加section、paragraph Document doc = new Document(); Section sec = doc.AddSection(); Paragraph para1 = sec.AddParagraph(); 步骤3:添加文字,并应用格式到文字 para1.AppendText("中日文化交流"); ParagraphStyle style1 = new ParagraphStyle(doc); style1.Name = "titleStyle"; style1.CharacterFormat.Bold = true; style1.CharacterFormat.FontName = "隶书"; style1.CharacterFormat.FontSize = 30f; doc.Styles.Add(style1); para1.ApplyStyle("titleStyle"); para1.Format.HorizontalAlignment = HorizontalAlignment.Center; 步骤4:实例化段落2,并创建一个形状组合,并设置大小 //实例化段落2 Paragraph para2 = sec.AddParagraph(); //创建一个形状组合并设置大小 ShapeGroup shapegr = para2.AppendShapeGroup(300, 300); 步骤5:绘制一个中国国旗,这里需要组合形状矩形和五角星形,并填充相应的颜色 //添加一个矩形到形状组合 shapegr.ChildObjects.Add(new ShapeObject(doc, ShapeType.Rectangle) { Width = 900, Height = 500, LineStyle = ShapeLineStyle.Single, FillColor = Color.Red, StrokeColor = Color.Red, StrokeWeight = 1, }); //添加第一个五角星到形状组合 shapegr.ChildObjects.Add(new ShapeObject(doc, ShapeType.Star) { Width = 100, Height = 100, VerticalPosition = 90, HorizontalPosition = 90, LineStyle = ShapeLineStyle.Single, FillColor = Color.Yellow, StrokeColor = Color.Yellow, StrokeWeight = 1, }); //添加第二个五角星到形状组合 shapegr.ChildObjects.Add(new ShapeObject(doc, ShapeType.Star) { Width = 50, Height = 50, VerticalPosition = 40, HorizontalPosition = 210, LineStyle = ShapeLineStyle.Single, FillColor = Color.Yellow, StrokeColor = Color.Yellow, StrokeWeight = 1, }); //添加第三个五角星到形状组合 shapegr.ChildObjects.Add(new ShapeObject(doc, ShapeType.Star) { Width = 50, Height = 50, VerticalPosition = 80, HorizontalPosition = 280, LineStyle = ShapeLineStyle.Single, FillColor = Color.Yellow, StrokeColor = Color.Yellow, StrokeWeight = 1, }); //添加第四个五角星到形状组合 shapegr.ChildObjects.Add(new ShapeObject(doc, ShapeType.Star) { Width = 50, Height = 50, VerticalPosition = 160, HorizontalPosition = 280, LineStyle = ShapeLineStyle.Single, FillColor = Color.Yellow, StrokeColor = Color.Yellow, StrokeWeight = 1, }); //添加第五个五角星到形状组合 shapegr.ChildObjects.Add(new ShapeObject(doc, ShapeType.Star) { Width = 50, Height = 50, VerticalPosition = 220, HorizontalPosition = 210, LineStyle = ShapeLineStyle.Single, FillColor = Color.Yellow, StrokeColor = Color.Yellow, StrokeWeight = 1, }); 步骤6:绘制一个日本国旗,需要组合形状矩形和圆形,并填充颜色 //绘制一个矩形并添加到形状组合 shapegr.ChildObjects.Add(new ShapeObject(doc, ShapeType.Rectangle) { Width = 900, Height = 500, VerticalPosition = 700, HorizontalPosition = 600, LineStyle = ShapeLineStyle.Single, FillColor = Color.WhiteSmoke, StrokeColor = Color.WhiteSmoke, StrokeWeight = 1, }); //绘制一个圆形并添加到形状组合 shapegr.ChildObjects.Add(new ShapeObject(doc, ShapeType.Ellipse) { Width = 250, Height = 250, VerticalPosition = 800, HorizontalPosition = 900, LineStyle = ShapeLineStyle.Single, FillColor = Color.Red, StrokeColor = Color.Red, StrokeWeight = 1, }); 步骤7:保存文档 //保存并打开文档 doc.SaveToFile("InsertShapegroups.docx", FileFormat.Docx2010); System.Diagnostics.Process.Start("InsertShapegroups.docx"); 添加效果: (此时的图形是组合后的效果,任意拖动图形不会出现各个形状分离、错位的情况。) 全部代码: 1 using Spire.Doc; 2 using Spire.Doc.Documents; 3 using Spire.Doc.Fields; 4 using System.Drawing; 5 6 namespace InsertShapesGroup_Doc 7 { 8 class Program 9 { 10 static void Main(string[] args) 11 { 12 //创建一个Document实例并添加section及paragraph 13 Document doc = new Document(); 14 Section sec = doc.AddSection(); 15 Paragraph para1 = sec.AddParagraph(); 16 //添加文字,并应用格式到文字 17 para1.AppendText("中日文化交流"); 18 ParagraphStyle style1 = new ParagraphStyle(doc); 19 style1.Name = "titleStyle"; 20 style1.CharacterFormat.Bold = true; 21 style1.CharacterFormat.FontName = "隶书"; 22 style1.CharacterFormat.FontSize = 30f; 23 doc.Styles.Add(style1); 24 para1.ApplyStyle("titleStyle"); 25 para1.Format.HorizontalAlignment = HorizontalAlignment.Center; 26 27 //实例化段落2 28 Paragraph para2 = sec.AddParagraph(); 29 //创建一个形状组合并设置大小 30 ShapeGroup shapegr = para2.AppendShapeGroup(300, 300); 31 32 //添加一个矩形到形状组合 33 shapegr.ChildObjects.Add(new ShapeObject(doc, ShapeType.Rectangle) 34 { 35 Width = 900, 36 Height = 500, 37 LineStyle = ShapeLineStyle.Single, 38 FillColor = Color.Red, 39 StrokeColor = Color.Red, 40 StrokeWeight = 1, 41 }); 42 43 //添加第一个五角星到形状组合 44 shapegr.ChildObjects.Add(new ShapeObject(doc, ShapeType.Star) 45 { 46 Width = 100, 47 Height = 100, 48 VerticalPosition = 90, 49 HorizontalPosition = 90, 50 LineStyle = ShapeLineStyle.Single, 51 FillColor = Color.Yellow, 52 StrokeColor = Color.Yellow, 53 StrokeWeight = 1, 54 }); 55 //添加第二个五角星到形状组合 56 shapegr.ChildObjects.Add(new ShapeObject(doc, ShapeType.Star) 57 { 58 Width = 50, 59 Height = 50, 60 VerticalPosition = 40, 61 HorizontalPosition = 210, 62 LineStyle = ShapeLineStyle.Single, 63 FillColor = Color.Yellow, 64 StrokeColor = Color.Yellow, 65 StrokeWeight = 1, 66 }); 67 //添加第三个五角星到形状组合 68 shapegr.ChildObjects.Add(new ShapeObject(doc, ShapeType.Star) 69 { 70 Width = 50, 71 Height = 50, 72 VerticalPosition = 80, 73 HorizontalPosition = 280, 74 LineStyle = ShapeLineStyle.Single, 75 FillColor = Color.Yellow, 76 StrokeColor = Color.Yellow, 77 StrokeWeight = 1, 78 }); 79 //添加第四个五角星到形状组合 80 shapegr.ChildObjects.Add(new ShapeObject(doc, ShapeType.Star) 81 { 82 Width = 50, 83 Height = 50, 84 VerticalPosition = 160, 85 HorizontalPosition = 280, 86 LineStyle = ShapeLineStyle.Single, 87 FillColor = Color.Yellow, 88 StrokeColor = Color.Yellow, 89 StrokeWeight = 1, 90 }); 91 //添加第五个五角星到形状组合 92 shapegr.ChildObjects.Add(new ShapeObject(doc, ShapeType.Star) 93 { 94 Width = 50, 95 Height = 50, 96 VerticalPosition = 220, 97 HorizontalPosition = 210, 98 LineStyle = ShapeLineStyle.Single, 99 FillColor = Color.Yellow, 100 StrokeColor = Color.Yellow, 101 StrokeWeight = 1, 102 }); 103 104 //绘制一个矩形并添加到形状组合 105 shapegr.ChildObjects.Add(new ShapeObject(doc, ShapeType.Rectangle) 106 { 107 Width = 900, 108 Height = 500, 109 VerticalPosition = 700, 110 HorizontalPosition = 600, 111 LineStyle = ShapeLineStyle.Single, 112 FillColor = Color.WhiteSmoke, 113 StrokeColor = Color.Wheat, 114 StrokeWeight = 1, 115 }); 116 //绘制一个圆形并添加到形状组合 117 shapegr.ChildObjects.Add(new ShapeObject(doc, ShapeType.Ellipse) 118 { 119 Width = 250, 120 Height = 250, 121 VerticalPosition = 800, 122 HorizontalPosition = 900, 123 LineStyle = ShapeLineStyle.Single, 124 FillColor = Color.Red, 125 StrokeColor = Color.Red, 126 StrokeWeight = 1, 127 }); 128 129 //保存并打开文档 130 doc.SaveToFile("InsertShapegroups.docx", FileFormat.Docx2010); 131 System.Diagnostics.Process.Start("InsertShapegroups.docx"); 132 } 133 } 134 } View Code 以上全部是关于Word中绘制图形形状的内容。如需转载,请注明出处! 感谢阅读!
引言 在PDF中我们可以通过C#程序代码来添加非常丰富的元素来呈现我们想要表达的内容,如绘制表格、文字,添加图形、图像等等。在本篇文章中,我将介绍如何在PDF中绘制图形,并设置图形属性的操作。 文章中将分以下要点进行介绍: 1. 绘制基本图形(线条、椭圆、圆形、矩形、三角形) 2. 绘制自定义图形 3. 绘制图形并设置图形透明度 所需工具:Spire.PDF for .NET 4.0 提示:安装后,直接引用安装路径下Bin文件夹中的dll文件到项目程序中即可。 【示例1】绘制基本图形 C# 步骤1:新建一个PDF文档,添加页,添加画笔、画刷 //新建一个PDF文档,添加页 PdfDocument doc = new PdfDocument(); PdfPageBase page = doc.Pages.Add(); //设置画笔和画刷 PdfPen pen = new PdfPen(PdfBrushes.Black, 1f); PdfBrush brush1 = PdfBrushes.RosyBrown; PdfBrush brush2 = PdfBrushes.Goldenrod; 步骤2:绘制圆形、矩形、线段、三角形 //绘入矩形(此处通过设置值来绘制成正方形) page.Canvas.DrawRectangle(pen, brush1, new Rectangle(new Point(50, 50), new Size(60, 60))); //绘入椭圆(此处通过设置值来绘制成圆形) page.Canvas.DrawEllipse(pen, brush2, 210, 50, 60, 60); //绘入线段 page.Canvas.DrawLine(pen, new PointF(50, 115), new PointF(270, 115)); //绘入多边形(此处绘制成三角形) PointF p1 = new PointF(130, 172); PointF p2 = new PointF(160, 120); PointF p3 = new PointF(190, 172); PointF[] points = new PointF[] { p1, p2, p3 }; page.Canvas.DrawPolygon(pen, points); 步骤3:保存文档 //保存并打开文档 doc.SaveToFile("基本图形.pdf"); System.Diagnostics.Process.Start("基本图形.pdf"); 全部代码 using Spire.Pdf; using Spire.Pdf.Graphics; using System.Drawing; namespace DrawRectangle_PDF { class Program { static void Main(string[] args) { //新建一个PDF文档,添加页 PdfDocument doc = new PdfDocument(); PdfPageBase page = doc.Pages.Add(); //设置画笔和画刷 PdfPen pen = new PdfPen(PdfBrushes.Black, 1f); PdfBrush brush1 = PdfBrushes.RosyBrown; PdfBrush brush2 = PdfBrushes.Goldenrod; //绘入矩形(此处通过设置值来绘制成正方形) page.Canvas.DrawRectangle(pen, brush1, new Rectangle(new Point(50, 50), new Size(60, 60))); //绘入椭圆(此处通过设置值来绘制成圆形) page.Canvas.DrawEllipse(pen, brush2, 210, 50, 60, 60); //绘入线段 page.Canvas.DrawLine(pen, new PointF(50, 115), new PointF(270, 115)); //绘入多边形(此处绘制成三角形) PointF p1 = new PointF(130, 172); PointF p2 = new PointF(160, 120); PointF p3 = new PointF(190, 172); PointF[] points = new PointF[] { p1, p2, p3 }; page.Canvas.DrawPolygon(pen, points); //保存并打开文档 doc.SaveToFile("基本图形.pdf"); System.Diagnostics.Process.Start("基本图形.pdf"); } } } View Code 效果图: 【示例2】绘制自定义图形 步骤1:创建pdf文档,调用方法DrawStar()绘制自定义图形,并保存 //新建一个PDF文档,添加页 PdfDocument doc = new PdfDocument(); PdfPageBase page = doc.Pages.Add(); //调用DrawStar()方法绘入五角星图形 DrawStar(page); //保存并打开文档 doc.SaveToFile("自定义图形.pdf"); System.Diagnostics.Process.Start("自定义图形.pdf"); 步骤2:自定义DrawStar()方法绘制几个不同样式的五角星 private static void DrawStar(PdfPageBase page) { //设置五角星的5个顶点坐标 PointF[] points = new PointF[5]; for (int i = 0; i < points.Length; i++) { float x = (float)Math.Cos(i * 2 * Math.PI / 5); float y = (float)Math.Sin(i * 2 * Math.PI / 5); points[i] = new PointF(x, y); } //创建PdfPath类,在顶点之间添加线段组成五角星 PdfPath path = new PdfPath(); path.AddLine(points[2], points[0]); path.AddLine(points[0], points[3]); path.AddLine(points[3], points[1]); path.AddLine(points[1], points[4]); path.AddLine(points[4], points[2]); //保存画布状态 PdfGraphicsState state = page.Canvas.Save(); //实例化画笔和画刷1、画刷2 PdfPen pen = new PdfPen(Color.DeepSkyBlue, 0.02f); PdfBrush brush1 = new PdfSolidBrush(Color.PaleGreen); PdfBrush brush2 = new PdfSolidBrush(Color.Bisque); //将坐标放大40倍 page.Canvas.ScaleTransform(40f, 40f); //平移坐标 page.Canvas.TranslateTransform(1f, 1.5f); //绘入第一个五角星 page.Canvas.DrawPath(pen, path); //平移坐标并在新的位置绘入第二个五角星 page.Canvas.TranslateTransform(2f, 0f); path.FillMode = PdfFillMode.Alternate; page.Canvas.DrawPath(pen, brush1, path); //平移坐标并在新的位置绘入第三个五角星 page.Canvas.TranslateTransform(2f, 0f); path.FillMode = PdfFillMode.Winding; page.Canvas.DrawPath(pen, brush2, path); //实例化画刷3,平移坐标并在新的位置绘入第四个五角星 PdfLinearGradientBrush brush3 = new PdfLinearGradientBrush(new PointF(-2, 0), new PointF(2, 0), Color.OrangeRed, Color.Yellow); page.Canvas.TranslateTransform(-4f, 2f); path.FillMode = PdfFillMode.Alternate; page.Canvas.DrawPath(pen, brush3, path); //实例化画刷4,平移坐标并在新的位置绘入第五个五角星 PdfRadialGradientBrush brush4 = new PdfRadialGradientBrush(new PointF(0f, 0f), 0f, new PointF(0f, 0f), 1f, Color.Orchid, Color.LightBlue); page.Canvas.TranslateTransform(2f, 0f); path.FillMode = PdfFillMode.Winding; page.Canvas.DrawPath(pen, brush4, path); //实例化画刷5,平移坐标并在新的位置绘入第六个五角星 PdfTilingBrush brush5 = new PdfTilingBrush(new RectangleF(0, 0, 4f, 4f)); brush5.Graphics.DrawRectangle(brush3, 0, 0, 4f, 4f); page.Canvas.TranslateTransform(2f, 0f); path.FillMode = PdfFillMode.Winding; page.Canvas.DrawPath(pen, brush5, path); //再次保存画布状态 page.Canvas.Restore(state); } 全部代码: using Spire.Pdf; using Spire.Pdf.Graphics; using System; using System.Drawing; namespace DrawCustomGraphics_PDF { class Program { static void Main(string[] args) { //新建一个PDF文档,添加页 PdfDocument doc = new PdfDocument(); PdfPageBase page = doc.Pages.Add(); //调用DrawStar()方法绘入五角星图形 DrawStar(page); //保存并打开文档 doc.SaveToFile("自定义图形.pdf"); System.Diagnostics.Process.Start("自定义图形.pdf"); } //自定义DrawStar方法绘制几个不同样式的五角星 private static void DrawStar(PdfPageBase page) { //设置五角星的5个顶点坐标 PointF[] points = new PointF[5]; for (int i = 0; i < points.Length; i++) { float x = (float)Math.Cos(i * 2 * Math.PI / 5); float y = (float)Math.Sin(i * 2 * Math.PI / 5); points[i] = new PointF(x, y); } //创建PdfPath类,在顶点之间添加线段组成五角星 PdfPath path = new PdfPath(); path.AddLine(points[2], points[0]); path.AddLine(points[0], points[3]); path.AddLine(points[3], points[1]); path.AddLine(points[1], points[4]); path.AddLine(points[4], points[2]); //保存画布状态 PdfGraphicsState state = page.Canvas.Save(); //实例化画笔和画刷1、画刷2 PdfPen pen = new PdfPen(Color.DeepSkyBlue, 0.02f); PdfBrush brush1 = new PdfSolidBrush(Color.PaleGreen); PdfBrush brush2 = new PdfSolidBrush(Color.Bisque); //将坐标放大40倍 page.Canvas.ScaleTransform(40f, 40f); //平移坐标 page.Canvas.TranslateTransform(1f, 1.5f); //绘入第一个五角星 page.Canvas.DrawPath(pen, path); //平移坐标并在新的位置绘入第二个五角星 page.Canvas.TranslateTransform(2f, 0f); path.FillMode = PdfFillMode.Alternate; page.Canvas.DrawPath(pen, brush1, path); //平移坐标并在新的位置绘入第三个五角星 page.Canvas.TranslateTransform(2f, 0f); path.FillMode = PdfFillMode.Winding; page.Canvas.DrawPath(pen, brush2, path); //实例化画刷3,平移坐标并在新的位置绘入第四个五角星 PdfLinearGradientBrush brush3 = new PdfLinearGradientBrush(new PointF(-2, 0), new PointF(2, 0), Color.OrangeRed, Color.Yellow); page.Canvas.TranslateTransform(-4f, 2f); path.FillMode = PdfFillMode.Alternate; page.Canvas.DrawPath(pen, brush3, path); //实例化画刷4,平移坐标并在新的位置绘入第五个五角星 PdfRadialGradientBrush brush4 = new PdfRadialGradientBrush(new PointF(0f, 0f), 0f, new PointF(0f, 0f), 1f, Color.Orchid, Color.LightBlue); page.Canvas.TranslateTransform(2f, 0f); path.FillMode = PdfFillMode.Winding; page.Canvas.DrawPath(pen, brush4, path); //实例化画刷5,平移坐标并在新的位置绘入第六个五角星 PdfTilingBrush brush5 = new PdfTilingBrush(new RectangleF(0, 0, 4f, 4f)); brush5.Graphics.DrawRectangle(brush3, 0, 0, 4f, 4f); page.Canvas.TranslateTransform(2f, 0f); path.FillMode = PdfFillMode.Winding; page.Canvas.DrawPath(pen, brush5, path); //再次保存画布状态 page.Canvas.Restore(state); } } } View Code 效果图: 【示例3】设置色彩透明度 步骤1:新建一个PDF文档,添加页 PdfDocument doc = new PdfDocument(); PdfPageBase page = doc.Pages.Add(); 步骤2:初始化一个PdfSeparationColorSpace的对象,用于创建基本色,并将基本色透明度设置为1 PdfSeparationColorSpace cs1 = new PdfSeparationColorSpace("MySpotColor", Color.DarkGreen); PdfSeparationColorSpace cs2 = new PdfSeparationColorSpace("MySpotColor", Color.Yellow); PdfSeparationColorSpace cs3 = new PdfSeparationColorSpace("MySpotColor", Color.DeepPink); PdfSeparationColor color1 = new PdfSeparationColor(cs1, 1f); PdfSeparationColor color2 = new PdfSeparationColor(cs2, 1f); PdfSeparationColor color3 = new PdfSeparationColor(cs3, 1f); 步骤3:根据颜色创建画刷 PdfSolidBrush brush1 = new PdfSolidBrush(color1); PdfSolidBrush brush2 = new PdfSolidBrush(color2); PdfSolidBrush brush3 = new PdfSolidBrush(color3); 步骤4:绘入图形及文字,应用色彩透明度到图形 //绘入图形及文字并着色 page.Canvas.DrawPie(brush1, 10, 30, 60, 60, 360, 360); page.Canvas.DrawPie(brush2, 10, 120, 60, 60, 360, 360); page.Canvas.DrawPie(brush3, 10, 210, 60, 60, 360, 360); page.Canvas.DrawString("透明度=1.0", new PdfTrueTypeFont(new Font("Arial Unicode MS", 10f), true), brush1, new PointF(16, 100)); //将基本色透明度设置为0.5,并绘入图形及文字 color1 = new PdfSeparationColor(cs1, 0.5f); brush1 = new PdfSolidBrush(color1); page.Canvas.DrawPie(brush1, 80, 30, 60, 60, 360, 360); color2 = new PdfSeparationColor(cs2, 0.5f); brush2 = new PdfSolidBrush(color2); page.Canvas.DrawPie(brush2, 80, 120, 60, 60, 360, 360); color3 = new PdfSeparationColor(cs3, 0.5f); brush3 = new PdfSolidBrush(color3); page.Canvas.DrawPie(brush3, 80, 210, 60, 60, 360, 360); page.Canvas.DrawString("透明度=0.5", new PdfTrueTypeFont(new Font("Arial Unicode MS", 10f), true), brush1, new PointF(86, 100)); //将基本色透明度设置为0.25,并绘入图形及文字 color1 = new PdfSeparationColor(cs1, 0.25f); brush1 = new PdfSolidBrush(color1); page.Canvas.DrawPie(brush1, 150, 30, 60, 60, 360, 360); color2 = new PdfSeparationColor(cs2, 0.25f); brush2 = new PdfSolidBrush(color2); page.Canvas.DrawPie(brush2, 150, 120, 60, 60, 360, 360); color3 = new PdfSeparationColor(cs3, 0.25f); brush3 = new PdfSolidBrush(color3); page.Canvas.DrawPie(brush3, 150, 210, 60, 60, 360, 360); page.Canvas.DrawString("透明度=0.25", new PdfTrueTypeFont(new Font("Arial Unicode MS", 10f), true), brush1, new PointF(156, 100)); 步骤5:保存文档 doc.SaveToFile("设置透明度.pdf"); System.Diagnostics.Process.Start("设置透明度.pdf"); 全部代码: using Spire.Pdf; using Spire.Pdf.ColorSpace; using Spire.Pdf.Graphics; using System.Drawing; namespace CrearteSpotColor_PDF { class Program { static void Main(string[] args) { //新建一个PDF文档,添加页 PdfDocument doc = new PdfDocument(); PdfPageBase page = doc.Pages.Add(); //初始化一个PdfSeparationColorSpace的对象,用于创建基本色 PdfSeparationColorSpace cs1 = new PdfSeparationColorSpace("MySpotColor", Color.DarkGreen); PdfSeparationColorSpace cs2 = new PdfSeparationColorSpace("MySpotColor", Color.Yellow); PdfSeparationColorSpace cs3 = new PdfSeparationColorSpace("MySpotColor", Color.DeepPink); //将基本色透明度设置为1 PdfSeparationColor color1 = new PdfSeparationColor(cs1, 1f); PdfSeparationColor color2 = new PdfSeparationColor(cs2, 1f); PdfSeparationColor color3 = new PdfSeparationColor(cs3, 1f); //根据颜色创建画刷 PdfSolidBrush brush1 = new PdfSolidBrush(color1); PdfSolidBrush brush2 = new PdfSolidBrush(color2); PdfSolidBrush brush3 = new PdfSolidBrush(color3); //绘入图形及文字并着色 page.Canvas.DrawPie(brush1, 10, 30, 60, 60, 360, 360); page.Canvas.DrawPie(brush2, 10, 120, 60, 60, 360, 360); page.Canvas.DrawPie(brush3, 10, 210, 60, 60, 360, 360); page.Canvas.DrawString("透明度=1.0", new PdfTrueTypeFont(new Font("Arial Unicode MS", 10f), true), brush1, new PointF(16, 100)); //将基本色透明度设置为0.5,并绘入图片及文字 color1 = new PdfSeparationColor(cs1, 0.5f); brush1 = new PdfSolidBrush(color1); page.Canvas.DrawPie(brush1, 80, 30, 60, 60, 360, 360); color2 = new PdfSeparationColor(cs2, 0.5f); brush2 = new PdfSolidBrush(color2); page.Canvas.DrawPie(brush2, 80, 120, 60, 60, 360, 360); color3 = new PdfSeparationColor(cs3, 0.5f); brush3 = new PdfSolidBrush(color3); page.Canvas.DrawPie(brush3, 80, 210, 60, 60, 360, 360); page.Canvas.DrawString("透明度=0.5", new PdfTrueTypeFont(new Font("Arial Unicode MS", 10f), true), brush1, new PointF(86, 100)); //将基本色透明度设置为0.25,并绘入图片及文字 color1 = new PdfSeparationColor(cs1, 0.25f); brush1 = new PdfSolidBrush(color1); page.Canvas.DrawPie(brush1, 150, 30, 60, 60, 360, 360); color2 = new PdfSeparationColor(cs2, 0.25f); brush2 = new PdfSolidBrush(color2); page.Canvas.DrawPie(brush2, 150, 120, 60, 60, 360, 360); color3 = new PdfSeparationColor(cs3, 0.25f); brush3 = new PdfSolidBrush(color3); page.Canvas.DrawPie(brush3, 150, 210, 60, 60, 360, 360); page.Canvas.DrawString("透明度=0.25", new PdfTrueTypeFont(new Font("Arial Unicode MS", 10f), true), brush1, new PointF(156, 100)); //保存并打开文档 doc.SaveToFile("设置透明度.pdf"); System.Diagnostics.Process.Start("设置透明度.pdf"); } } } View Code 效果图: 以上是关于C#绘制PDF图形的全部内容,如需转载,请注明出处! (本文完)
在文本框中,我们可以操作很多元素,如文本、图片、表格等,在本篇文章中将着重介绍如何插入表格到文本框,插入的表格我们可以对表格进行格式化操作来丰富表格内容。此外,对于文本框中的表格内容,我们也可以根据需要来读取表格或者删除表格。 使用工具 Free Spire.Doc for .NET 6.3(免费版) 示例代码 【示例1】插入表格到文本框 C# using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; namespace InsertTableToTextbox_Doc { class Program { static void Main(string[] args) { //创建一个Document类对象 Document document = new Document(); //添加section到文档 Section section = document.AddSection(); //添加段落section Paragraph paragraph = section.AddParagraph(); //添加指定大小的文本框到段落 TextBox textbox = paragraph.AppendTextBox(300, 100); //添加文本到文本,设置文本格式 Paragraph textboxParagraph = textbox.Body.AddParagraph(); TextRange textboxRange = textboxParagraph.AppendText("Sample Report 1"); textboxRange.CharacterFormat.FontName = "Arial"; //插入表格到文本框 Table table = textbox.Body.AddTable(true); //指定表格行数、列数 table.ResetCells(4, 4); //实例化数组内容 string[,] data = new string[,] { {"Name","Age","Gender","ID" }, {"John","28","Male","0023" }, {"Steve","30","Male","0024" }, {"Lucy","26","female","0025" } }; //将数组内容添加到表格 for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { TextRange tableRange = table[i, j].AddParagraph().AppendText(data[i, j]); tableRange.CharacterFormat.FontName = "Arial"; } } //应用表格样式 table.ApplyStyle(DefaultTableStyle.MediumGrid3Accent1); //保存并打开文档 document.SaveToFile("Output.docx", FileFormat.Docx2013); System.Diagnostics.Process.Start("Output.docx"); } } } 这里应用表格格式,Spire.Doc 支持多种不同的表格类型,可根据需要自行选择。 表格添加效果: 【示例2】读取文本框中的表格 C# using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; using System.IO; using System.Text; namespace GetTableFromTextbox_Doc { class Program { static void Main(string[] args) { //载入Word文档 Document document = new Document("Output.docx"); //获取第一个文本框 TextBox textbox = document.TextBoxes[0]; //获取文本框中第一个表格 Table table = textbox.Body.Tables[0] as Table; //实例化StringBuilder类 StringBuilder sb = new StringBuilder(); //遍历表格中的段落并提取文本 foreach (TableRow row in table.Rows) { foreach (TableCell cell in row.Cells) { foreach (Paragraph paragraph in cell.Paragraphs) { sb.AppendLine(paragraph.Text); } } } File.WriteAllText("text.txt", sb.ToString()); } } } 读取结果: 【示例3】删除Word文本框中的表格 C# using Spire.Doc; using Spire.Doc.Fields; namespace RemoveTableFormTextbox_Doc { class Program { static void Main(string[] args) { //创建Document实例 Document document = new Document("Output.docx"); //获取第一个文本框 TextBox textbox = document.TextBoxes[0]; //删除文本框中第一个表格 textbox.Body.Tables.RemoveAt(0); //保存文档 document.SaveToFile("RemoveTable.docx", FileFormat.Docx2013); System.Diagnostics.Process.Start("RemoveTable.docx"); } } } 删除效果: 附: 除了添加在文本框汇中操作表格以外,我们向文本框中添加图文混排的内容也是比较常见的,不仅仅只是添加简单文本或者图片,一些复杂的格式化的操作也是可以的,具体可以参阅博客“C# 插入排版精良的Word文本框” 以上是本次关于“C# 操作Word 文本框中的表格”的全部内容。如需转载,请注明出处! 感谢阅读!
引言 对Excel表格设置分页对我们预览、打印文档时是很方便的,特别是一些包含很多复杂数据的、不规则的表格,为保证打印时每一页的排版美观性或者数据的前后连接的完整性,此时的分页符就发挥了极大的作用。因此,本文将介绍C#设置Excel分页的方法。当然,对于Excel表格中已有的分页符,如果我们也可以根据需要自行删除分页。 示例要点梳理 1. 插入分页 1.1 插入横向分页 1.2 插入纵向分页 2. 删除分页 2.1 删除全部分页 2.2 删除指定分页 代码操作及效果 1.插入Excel分页 C# using Spire.Xls; namespace ExcelPageBreak_XLS { class Program { static void Main(string[] args) { //实例化一个Wordbook类对象,并加载需要设置分页的Excel文档 Workbook workbook = new Workbook(); workbook.LoadFromFile("Sample.xlsx"); //获取第一个工作表 Worksheet sheet = workbook.Worksheets[0]; //插入两个横向分页符(指定单元格上方插入分页) sheet.HPageBreaks.Add(sheet.Range["A11"]); sheet.HPageBreaks.Add(sheet.Range["A20"]); //插入一个纵向分页符(指定单元格左侧插入分页) //sheet.VPageBreaks.Add(sheet.Range["E1"]); //将视图设置为分页预览模式查看效果 sheet.ViewMode = ViewMode.Preview; //保存并打开文档 workbook.SaveToFile("AddPageBreak.xlsx", FileFormat.Version2010); System.Diagnostics.Process.Start("AddPageBreak.xlsx"); } } } 添加分页效果图 1.横向分页效果 2.纵向分页效果 2.删除分页 C# using Spire.Xls; namespace DeletePageBreak_XLS { class Program { static void Main(string[] args) { //创建一个Workbook类对象,并加载Excel文档 Workbook workbook = new Workbook(); workbook.LoadFromFile("sample.xlsx"); //获取第一个worksheet Worksheet sheet = workbook.Worksheets[0]; //删除所有横向分页 sheet.HPageBreaks.Clear(); //删除第一个横向分页 //sheet.HPageBreaks.RemoveAt(0); //设置分页预览模式查看分页效果 sheet.ViewMode = ViewMode.Preview; //保存并打开文档 workbook.SaveToFile("删除分页1.xlsx",FileFormat.Version2010); System.Diagnostics.Process.Start("删除分页1.xlsx"); } } } 删除分页效果: 1.删除全部分页 2.删除指定分页 这里使用了最新免费版控件Free Spire.XLS for .NET 8.3,可以自行上官网或者Nuget下载安装,注意在进行代码编辑时,不要忘了引用Spire.Xls.dll文件,dll文件可在安装路径下的Bin文件夹中获取。 以上全部内容为本次关于“C#插入、删除Excel分页符的方法”的全部内容,代码供参考。 如需转载,请注明出处! 感谢阅读!
前言 通过添加图层,我们可以将文本、图片、表格、图形等元素精确定位于页面指定位置,将这些元素进行叠放、组合形成页面的最终效果。此外,对于页面中已有的图层我们也可以进行设置图层可见性、删除图层等操作。因此,在本篇文章中,将介绍如何在C#中进行PDF图层的操作。 要点概括 1.添加图层 线条 图形 图像 字符串 2.设置图层隐藏、显示 指定单个图层可见性 设置所有图层可见性 3.删除图层 工具使用 Spire.PDF for .NET 4.0 代码操作 一、添加图层 我们通过使用Spire.PDF添加图层,支持添加线条、图像、字符串、饼图、椭圆形、矩形和多边形等多种类型的图层。 【C#】 using Spire.Pdf; using Spire.Pdf.Graphics; using System.Drawing; namespace AddLayers_PDF { class Program { static void Main(string[] args) { //新建PDF文档,添加一页 PdfDocument pdf = new PdfDocument(); PdfPageBase page = pdf.Pages.Add(); //添加一个线条图层,设置为可见 PdfPageLayer layer = page.PageLayers.Add("Line", true); //在页面指定位置添加指定长度的线条,并设置线条颜色、粗细等格式 layer.Graphics.DrawLine(new PdfPen(PdfBrushes.Blue, 1), new PointF(0, 0), new PointF(0, 200)); //这里可根据需要添加多条线条 //向页面添加一个名为“椭圆”的图层,设置图层为可见 layer = page.PageLayers.Add("椭圆", true); //设置图形颜色、线条粗细 PdfPen pen = new PdfPen(Color.Yellow, 2.5f); //填充图形内部颜色,并在页面指定位置添加指定大小的椭圆形图形 PdfBrush brush = new PdfSolidBrush(Color.White); layer.Graphics.DrawEllipse(pen, brush, 240, 200, 60,20); //添加一个图片图层,并命名图层为“Image Layer” layer = page.PageLayers.Add("Image Layer"); //加载图片,在页面指定位置添加该图片作为图层并设置图像的大小 layer.Graphics.DrawImage(PdfImage.FromFile("image.png"), 200, 230, 150, 185); //添加字符串类型的图层,并命名为“String Layer” layer = page.PageLayers.Add("String Layer"); //向页面指定位置绘如文本,并设置字体、字号、颜色等格式 layer.Graphics.DrawString("OH~IT'S SO GOOD! RIGHT? \n LET'S GET STARTED!\n COME ON, GUYS!", new PdfFont(PdfFontFamily.TimesRoman, 12), new PdfPen(PdfBrushes.MediumVioletRed, 1), 45, 250); //保存并打开文档 pdf.SaveToFile("AddLayers.pdf", FileFormat.PDF); System.Diagnostics.Process.Start("AddLayers.pdf"); } } } 添加效果: 二、设置图层隐藏、显示 (一)设置单个图层的隐藏、显示 【C#】 using Spire.Pdf; using Spire.Pdf.Graphics.Layer; namespace HideOrShowLayer_PDF { class Program { static void Main(string[] args) { //实例化PdfDocument类,加载文档 PdfDocument doc = new PdfDocument("AddLayers.pdf"); //设置图层可见属性为Off,通过索引值来隐藏第3个图层 //doc.Layers[2].Visibility = PdfVisibility.Off; //设置图层可见属性为Off,通过图层名称来隐藏图层 doc.Layers["String Layer"].Visibility = PdfVisibility.Off; //保存并打开文档 doc.SaveToFile("HideLayer0.pdf"); System.Diagnostics.Process.Start("HideLayer0.pdf"); } } } 测试结果: 1.通过“索引值”来隐藏图层的效果 2.通过图层名称来隐藏图层的效果 (二)设置全部图层的隐藏、显示 【C#】 using System; using Spire.Pdf; using Spire.Pdf.Graphics.Layer; namespace ShowLayer_PDF { class Program { static void Main(string[] args) { //创建PdfDocument类对象,加载pdf测试文档 PdfDocument doc = new PdfDocument("AddLayers.pdf"); //遍历文档中的所有图层, for (int i = 0; i < doc.Layers.Count; i++) { //显示所有图层 //doc.Layers[i].Visibility = PdfVisibility.On; //隐藏所有图层 doc.Layers[i].Visibility = PdfVisibility.Off; } //保存并打开文档 doc.SaveToFile("HideAllLayers.pdf"); System.Diagnostics.Process.Start("HideAllLayers.pdf"); } } } 测试结果: 三、删除图层 【C#】 using Spire.Pdf; namespace DeleteLayer_PDF { class Program { static void Main(string[] args) { //创建一个PdfDocument类对象,加载包含多个图层的PDF文档 PdfDocument doc = new PdfDocument(); doc.LoadFromFile("AddLayers.pdf"); //调用方法RemoveLayer()删除名为“Line”的图层 doc.Layers.RemoveLayer(("Line")); //保存并打开文档 doc.SaveToFile("DeleteLayer.pdf", FileFormat.PDF); System.Diagnostics.Process.Start("DeleteLayer.pdf"); } } } 测试结果: 阅读结束! 如需转载,请注明出处!
概述 在以下示例中,将介绍在PDF文档页面设置页面切换按钮的方法。示例中将页面切换按钮的添加分为了两种情况,一种是设置按钮跳转到首页、下页、上页或者最后一页,另一种是设置按钮跳转到指定页面。两种方法适应不同的程序设计需要,可自行选择合适的添加方法。 说明 这里的代码示例需要使用类库Spire.PDF for .NET,版本4.0 。在使用该类库时,在项目程序中引用Spire.Pdf.dll即可(dll文件在安装路径下的Bin文件中获取)。 如: 代码操作示例(供参考) 1.跳转至特定页(首页、下一页、上一页、最后一页) 【C#】 using Spire.Pdf; using Spire.Pdf.Actions; using Spire.Pdf.Fields; using Spire.Pdf.Graphics; using System.Drawing; namespace ButtonToAppointedPage_PDF { class Program { static void Main(string[] args) { //实例化PdfDocument类,加载PDF测试F文档 PdfDocument doc = new PdfDocument(); doc.LoadFromFile("sample.pdf"); //允许添加Form doc.AllowCreateForm = true; //获取文档最后一页 PdfPageBase lastPage = doc.Pages[doc.Pages.Count - 1]; //在页面指定位置添加指定大小的按钮 PdfButtonField button = new PdfButtonField(lastPage, "Click To Back "); button.Bounds = new RectangleF(lastPage.ActualSize.Width - 150, lastPage.ActualSize.Height - 400, 60, 20); //设置按钮边框颜色 button.BorderStyle = PdfBorderStyle.Solid; button.BorderColor = new PdfRGBColor(Color.White); //设置按钮背景色 button.BackColor = Color.Azure; //设置按钮提示语 button.ToolTip = "To the first page"; //设置按钮文字字体和颜色 PdfTrueTypeFont trueTypeFont = new PdfTrueTypeFont(new Font("Avant Garde", 9f), true); button.Font = trueTypeFont; button.ForeColor = Color.Black; //创建PdfNamedAction实例,在传入的参数中选择上一页、下一页、首页或最后一页 PdfNamedAction namedAction = new PdfNamedAction(PdfActionDestination.FirstPage); //应用动作 button.Actions.MouseDown = namedAction; //添加按钮到文档 doc.Form.Fields.Add(button); //保存并打开PDF文档 doc.SaveToFile("result.pdf", FileFormat.PDF); System.Diagnostics.Process.Start("result.pdf"); } } } PS:这里的PdfNameAction类支持四种按钮跳转动作 添加效果(截图): 点击文中的按钮时,即可跳转至按钮指向的页面。 2.跳转至指定页面 【C#】 using Spire.Pdf; using Spire.Pdf.Actions; using Spire.Pdf.Fields; using Spire.Pdf.General; using Spire.Pdf.Graphics; using System.Drawing; namespace Buttom2 { class Program { static void Main(string[] args) { //实例化PdfDocument类,加载PDF文档 PdfDocument doc = new PdfDocument(); doc.LoadFromFile("sample.pdf"); //允许添加Form doc.AllowCreateForm = true; //获取最后一页 PdfPageBase lastPage = doc.Pages[doc.Pages.Count - 1]; //在页面指定位置添加按钮 PdfButtonField button = new PdfButtonField(lastPage, "Back"); button.Bounds = new RectangleF(lastPage.ActualSize.Width - 150, lastPage.ActualSize.Height - 700, 50, 20); //设置按钮边框颜色 button.BorderStyle = PdfBorderStyle.Solid; button.BorderColor = new PdfRGBColor(Color.Transparent); //设置按钮背景色 button.BackColor = Color.WhiteSmoke; //设置按钮提示语 button.ToolTip = "Click and back to the third page"; //设置按钮文字字体和颜色 PdfTrueTypeFont trueTypeFont = new PdfTrueTypeFont(new Font("Avant Garde", 9f), true); button.Font = trueTypeFont; button.ForeColor = Color.Black; //实例化PdfDestination对象,传入指定页码到第3页 PdfDestination destination = new PdfDestination(doc.Pages[2]); //创建go to动作 PdfGoToAction goToAction = new PdfGoToAction(destination); //应用动作 button.Actions.MouseDown = goToAction; //添加按钮到文档 doc.Form.Fields.Add(button); //保存并打开PDF文档 doc.SaveToFile("result.pdf", FileFormat.PDF); System.Diagnostics.Process.Start("result.pdf"); } } } 添加效果(截图): 点击按钮,即可跳转至指定的文档第3页。 关于添加PDF页面跳转按钮的方法,本文介绍到这里,希望文中的代码能给各位开发者提供一定参考价值。 如需转载,请注明出处。 感谢阅读!
脚注和尾注是对文本的补充说明。脚注一般位于页面的底部,可以作为文档某处内容的注释;尾注一般位于文档的末尾,列出引文 的出处等。在本示例中将介绍如何来添加或读取Word脚注尾注。 工具使用: Free Spire. Doc for .NET(免费版) 第一步 :dll引用 第二步: 添加Word脚注、尾注 【C#】 using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; using System.Drawing; namespace InsertFootnote_Doc { class Program { static void Main(string[] args) { //新建一个word文档对象并加载需要添加脚注尾注的word文档 Document document = new Document(); document.LoadFromFile("sample.docx", FileFormat.Docx2010); //获取第3个段落 Paragraph paragraph = document.Sections[0].Paragraphs[2]; //添加脚注 Footnote footnote = paragraph.AppendFootnote(FootnoteType.Footnote); //在第一段里查找指定字符串,并添加脚注 DocumentObject obj = null; for (int i = 0; i < paragraph.ChildObjects.Count; i++) { obj = paragraph.ChildObjects[i]; if (obj.DocumentObjectType == DocumentObjectType.TextRange) { TextRange textRange = obj as TextRange; if (textRange.Text == "中国——东盟自贸区框架") { //为添加脚注的字符串设置加粗格式 textRange.CharacterFormat.Bold = true; //插入脚注 paragraph.ChildObjects.Insert(i + 1, footnote); break; } } } //添加脚注内容被设置字体格式 TextRange text = footnote.TextBody.AddParagraph().AppendText("2002年11月4日,朱镕基总理和东盟10国领导人共同签署了《中国-东盟全面经济合作框架协议》,这标志着中国与东盟的经贸合作进入了一个新的历史阶段。"); text.CharacterFormat.FontName = "Arial Black"; text.CharacterFormat.FontSize = 9; text.CharacterFormat.TextColor = Color.DarkGray; footnote.MarkerCharacterFormat.FontName = "Calibri"; footnote.MarkerCharacterFormat.FontSize = 12; footnote.MarkerCharacterFormat.Bold = true; footnote.MarkerCharacterFormat.TextColor = Color.DarkGreen; //获取第5段落 Paragraph paragraph2 = document.Sections[0].Paragraphs[4]; //添加尾注并设置尾注和格式 Footnote endnote = paragraph2.AppendFootnote(FootnoteType.Endnote); TextRange text2 = endnote.TextBody.AddParagraph().AppendText("党的十七大报告明确指出:" +"“坚持对外开放的基本国策,把‘引进来’和‘走出去’更好地结合起来," +"扩大开放领域,优化开放结构,提高开放质量,完善内外联动," +"互利共赢、安全高效的开放型经济体系,形成经济全球化条件下参与国际经济合作和竞争的新优势。"); text2.CharacterFormat.FontName = "Arial Black"; text2.CharacterFormat.FontSize = 9; text2.CharacterFormat.TextColor = Color.Black; endnote.MarkerCharacterFormat.FontName = "Calibri"; endnote.MarkerCharacterFormat.FontSize = 12; endnote.MarkerCharacterFormat.Bold = false; endnote.MarkerCharacterFormat.TextColor = Color.DarkGreen; //保存并打开文档 document.SaveToFile("添加脚注尾注.docx", FileFormat.Docx2010); System.Diagnostics.Process.Start("添加脚注尾注.docx"); } } } 测试结果: 第三步 :读取脚注/尾注 【C#】 //创建Document类对象,加载需要测试的文档 Document document = new Document(); document.LoadFromFile("添加脚注尾注.docx"); //获取文档第一个section Section section = document.Sections[0]; //实例化StringBuilder类 StringBuilder sb = new StringBuilder(); //遍历文档中所有段落 foreach (Paragraph paragraph in section.Paragraphs) { for (int i = 0, cnt = paragraph.ChildObjects.Count; i < cnt; i++) { ParagraphBase pBase = paragraph.ChildObjects[i] as ParagraphBase; if (pBase is Footnote) { //若需要读取尾注,将此处FootnoteType.Footnote改成 FootnoteType.Endnote即可 if ((pBase as Footnote).FootnoteType == FootnoteType.Footnote) { foreach (Paragraph footPara in (pBase as Footnote).TextBody.Paragraphs) { sb.Append(footPara.Text); } } } } } //将读取内容写入文本并保存 File.WriteAllText("FootNotes.txt", sb.ToString()); //打开文档 System.Diagnostics.Process.Start("FootNotes.txt"); 读取结果: 脚注读取结果: 尾注读取结果:
使用项目符号和编号,可以让文档的层次结构更清晰、更有条理,也更容易突出重点。在编辑文档的过程中,我个人也比较偏爱项目标号来标注文章重点信息。在之前的文章中,介绍了如何在Word中来创建项目标号和编号列表,在本篇文章中,将介绍创建PDF项目符号列表和多级编号列表的方法。 借助工具: Spire.PDF.dll PS:dll可以直接在安装路径下的Bin文件夹中获取。 1.创建PDF符号列表 C# using System; using System.Drawing; using Spire.Pdf; using Spire.Pdf.Graphics; using Spire.Pdf.Lists; namespace CreateList_PDF { class Program { static void Main(string[] args) { //创建一个PDF文档 PdfDocument doc = new PdfDocument(); //添加一页A4大小的页面 PdfPageBase page = doc.Pages.Add(PdfPageSize.A4); float y = 10; //创建标题并设置格式,包括字体、字号、颜色 PdfBrush brush1 = PdfBrushes.Black; PdfTrueTypeFont font1 = new PdfTrueTypeFont(new Font("楷体", 18f, FontStyle.Regular), true); PdfStringFormat format1 = new PdfStringFormat(PdfTextAlignment.Center); page.Canvas.DrawString("Categories List(项目列表)", font1, brush1, page.Canvas.ClientSize.Width / 2, y, format1); y = y + font1.MeasureString("Categories List(项目列表)", format1).Height; y = y + 5; //创建列表文字并设置格式 RectangleF rctg = new RectangleF(new PointF(0, 0), page.Canvas.ClientSize); PdfLinearGradientBrush brush = new PdfLinearGradientBrush(rctg, Color.SteelBlue, Color.Blue, PdfLinearGradientMode.Vertical); PdfTrueTypeFont font2 = new PdfTrueTypeFont(new Font("宋体", 15f, FontStyle.Regular), true); String formatted = "Part 1 Listening(听力部分) \n Part 2 Speaking(口语部分) \n Part 3 Reading(阅读部分) \n Part 4 Writing(写作部分)" + "\n Part 5 Test(测试) 1 \n Part 6 Test(测试) 2 \n Part 7 Test Answers(测试答案)"; //创建PdfList 类对象,并设置列表及样式 PdfList list = new PdfList(formatted); list.Font = font2; list.Indent = 8; list.TextIndent = 5; list.Brush = brush; PdfLayoutResult result = list.Draw(page, 0, y); y = result.Bounds.Bottom; //保存并打开文档 doc.SaveToFile("List.pdf"); System.Diagnostics.Process.Start("List.pdf"); } } } 测试结果: VB.NET Imports System Imports System.Drawing Imports Spire.Pdf Imports Spire.Pdf.Graphics Imports Spire.Pdf.Lists Namespace CreateList_PDF Class Program Private Shared Sub Main(ByVal args As String()) Dim doc As PdfDocument = New PdfDocument() Dim page As PdfPageBase = doc.Pages.Add(PdfPageSize.A4) Dim y As Single = 10 Dim brush1 As PdfBrush = PdfBrushes.Black Dim font1 As PdfTrueTypeFont = New PdfTrueTypeFont(New Font("楷体", 18F, FontStyle.Regular), True) Dim format1 As PdfStringFormat = New PdfStringFormat(PdfTextAlignment.Center) page.Canvas.DrawString("Categories List(项目列表)", font1, brush1, page.Canvas.ClientSize.Width / 2, y, format1) y = y + font1.MeasureString("Categories List(项目列表)", format1).Height y = y + 5 Dim rctg As RectangleF = New RectangleF(New PointF(0, 0), page.Canvas.ClientSize) Dim brush As PdfLinearGradientBrush = New PdfLinearGradientBrush(rctg, Color.SteelBlue, Color.Blue, PdfLinearGradientMode.Vertical) Dim font2 As PdfTrueTypeFont = New PdfTrueTypeFont(New Font("宋体", 15F, FontStyle.Regular), True) Dim formatted As String = "Part 1 Listening(听力部分) " & vbLf & " Part 2 Speaking(口语部分) " & vbLf & " Part 3 Reading(阅读部分) " & vbLf & " Part 4 Writing(写作部分)" & vbLf & " Part 5 Test(测试) 1 " & vbLf & " Part 6 Test(测试) 2 " & vbLf & " Part 7 Test Answers(测试答案)" Dim list As PdfList = New PdfList(formatted) list.Font = font2 list.Indent = 8 list.TextIndent = 5 list.Brush = brush Dim result As PdfLayoutResult = list.Draw(page, 0, y) y = result.Bounds.Bottom doc.SaveToFile("List.pdf") System.Diagnostics.Process.Start("List.pdf") End Sub End Class End Namespace 2.创建PDF多级编号列表 Spire.Pdf.dll支持多种类型的编号类型: C# using Spire.Pdf; using Spire.Pdf.Graphics; using Spire.Pdf.Lists; using System; using System.Drawing; namespace List2 { class Program { static void Main(string[] args) { //新建PDF文档,并添加一页A4大小的空白页面 PdfDocument doc = new PdfDocument(); PdfPageBase page = doc.Pages.Add(PdfPageSize.A4); float y = 10; //添加标题并设置文本和格式 PdfBrush brush1 = PdfBrushes.Black; PdfTrueTypeFont font1 = new PdfTrueTypeFont(new Font("宋体", 18f, FontStyle.Regular), true); PdfStringFormat format1 = new PdfStringFormat(PdfTextAlignment.Center); page.Canvas.DrawString("目录一览", font1, brush1, page.Canvas.ClientSize.Width / 2, y, format1); y = y + font1.MeasureString("目录一览", format1).Height; y = y + 5; //添加文本并设置字体 RectangleF rctg = new RectangleF(new PointF(0, 0), page.Canvas.ClientSize); PdfLinearGradientBrush brush = new PdfLinearGradientBrush(rctg, Color.DarkBlue, Color.Brown, PdfLinearGradientMode.Vertical); PdfTrueTypeFont font2 = new PdfTrueTypeFont(new Font("宋体", 15f, FontStyle.Regular), true); String formatted1 = "第一章 总 论"; String formatted2 = "第一节 经济法概述 "; String formatted3 = "第二节 经济法主体 "; String formatted4 = "第二章 公司法律制度"; //设置编号列表样式 PdfOrderedMarker marker1 = new PdfOrderedMarker(PdfNumberStyle.Numeric, new PdfFont(PdfFontFamily.Helvetica, 15f)); PdfOrderedMarker marker2 = new PdfOrderedMarker(PdfNumberStyle.LowerRoman, new PdfFont(PdfFontFamily.Helvetica, 12f)); //为第一级编号列表设置格式 PdfSortedList list1 = new PdfSortedList(font2); list1.Indent = 0; list1.TextIndent = 5; list1.Brush = brush; list1.Marker = marker1; //为第二级编号列表设置格式 PdfSortedList list2 = new PdfSortedList(font2); list2.Marker = marker2; list2.Brush = brush; list2.TextIndent = 10; //应用编号列表格式到指定文本 PdfListItem item = list1.Items.Add(formatted1); item.SubList = list2; list2.Items.Add(formatted2); list2.Items.Add(formatted3); list1.Items.Add(formatted4); //设置PDF文档布局和位置 PdfTextLayout textLayout = new PdfTextLayout(); textLayout.Break = PdfLayoutBreakType.FitPage; textLayout.Layout = PdfLayoutType.Paginate; list1.Draw(page, new PointF(0, y), textLayout); //保存文件 doc.SaveToFile("多级列表.pdf"); System.Diagnostics.Process.Start("多级列表.pdf"); } } } 测试结果: VB.NET Imports Spire.Pdf Imports Spire.Pdf.Graphics Imports Spire.Pdf.Lists Imports System Imports System.Drawing Namespace List2 Class Program Private Shared Sub Main(ByVal args As String()) Dim doc As PdfDocument = New PdfDocument() Dim page As PdfPageBase = doc.Pages.Add(PdfPageSize.A4) Dim y As Single = 10 Dim brush1 As PdfBrush = PdfBrushes.Black Dim font1 As PdfTrueTypeFont = New PdfTrueTypeFont(New Font("宋体", 18F, FontStyle.Regular), True) Dim format1 As PdfStringFormat = New PdfStringFormat(PdfTextAlignment.Center) page.Canvas.DrawString("目录一览", font1, brush1, page.Canvas.ClientSize.Width / 2, y, format1) y = y + font1.MeasureString("目录一览", format1).Height y = y + 5 Dim rctg As RectangleF = New RectangleF(New PointF(0, 0), page.Canvas.ClientSize) Dim brush As PdfLinearGradientBrush = New PdfLinearGradientBrush(rctg, Color.DarkBlue, Color.Brown, PdfLinearGradientMode.Vertical) Dim font2 As PdfTrueTypeFont = New PdfTrueTypeFont(New Font("宋体", 15F, FontStyle.Regular), True) Dim formatted1 As String = "第一章 总 论" Dim formatted2 As String = "第一节 经济法概述 " Dim formatted3 As String = "第二节 经济法主体 " Dim formatted4 As String = "第二章 公司法律制度" Dim marker1 As PdfOrderedMarker = New PdfOrderedMarker(PdfNumberStyle.Numeric, NewPdfFont(PdfFontFamily.Helvetica, 15F)) Dim marker2 As PdfOrderedMarker = New PdfOrderedMarker(PdfNumberStyle.LowerRoman, NewPdfFont(PdfFontFamily.Helvetica, 12F)) Dim list1 As PdfSortedList = New PdfSortedList(font2) list1.Indent = 0 list1.TextIndent = 5 list1.Brush = brush list1.Marker = marker1 Dim list2 As PdfSortedList = New PdfSortedList(font2) list2.Marker = marker2 list2.Brush = brush list2.TextIndent = 10 Dim item As PdfListItem = list1.Items.Add(formatted1) item.SubList = list2 list2.Items.Add(formatted2) list2.Items.Add(formatted3) list1.Items.Add(formatted4) Dim textLayout As PdfTextLayout = New PdfTextLayout() textLayout.Break = PdfLayoutBreakType.FitPage textLayout.Layout = PdfLayoutType.Paginate list1.Draw(page, New PointF(0, y), textLayout) doc.SaveToFile("多级列表.pdf") System.Diagnostics.Process.Start("多级列表.pdf") End Sub End Class End Namespace 以上内容为本次关于“创建PDF项目标号列表和多级编号列表”的全部内容。如需转载,请注明出处。感谢阅读!
批注内容可以是对某段文字或内容的注释,也可以是对文段中心思想的概括提要,或者是对文章内容的评判、疑问,以及在阅读时给自己或他人起到提示作用。本篇文章中将介绍如何在C#中操作Word批注,主要包含以下要点: 插入Word批注 修改Word批注 删除Word批注 使用工具:Free Spire.Doc for .NET 6.3(最新社区版) 注:编辑代码前注意添加引用Sprie.Doc.dll(dll文件可在安装路径下的Bin文件夹中获取) 1.插入Word批注 C# using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; namespace InsertComment_Word { class Program { static void Main(string[] args) { //实例化一个Document类对象,并加载Word文档 Document document = new Document(); document.LoadFromFile("sample.docx"); //获取第一段第一节 Section section = document.Sections[0]; Paragraph paragraph = section.Paragraphs[0]; //添加文本到批注 string str = "This paragraph describes the origin and the purpose of WEF"; Comment comment = paragraph.AppendComment(str); //添加批注作者 comment.Format.Author = "E-iceblue"; //保存并打开文档 document.SaveToFile("Comments.docx", FileFormat.Docx2010); System.Diagnostics.Process.Start("Comments.docx"); } } } VB.NET Imports Spire.Doc Imports Spire.Doc.Documents Imports Spire.Doc.Fields Namespace InsertComment_Word Class Program Private Shared Sub Main(ByVal args() As String) '实例化一个Document类对象,并加载Word文档 Dim document As Document = New Document document.LoadFromFile("sample.docx") '获取第一段第一节 Dim section As Section = document.Sections(0) Dim paragraph As Paragraph = section.Paragraphs(0) '添加文本到批注 Dim str As String = "This paragraph describes the origin and the purpose of WEF" Dim comment As Comment = paragraph.AppendComment(str) '添加批注作者 comment.Format.Author = "E-iceblue" '保存并打开文档 document.SaveToFile("Comments.docx", FileFormat.Docx2010) System.Diagnostics.Process.Start("Comments.docx") End Sub End Class End Namespace 测试结果: 2.修改、删除批注 测试文档: C# using Spire.Doc; namespace ReplaceAndRemoveComment_Word { class Program { static void Main(string[] args) { //初始化Document类实例,加载带有批注的Word文档 Document document = new Document(); document.LoadFromFile("test.docx"); //修改第一个批注内容 document.Comments[0].Body.Paragraphs[0].Replace("This paragraph describes the origin and the purpose of WEF", "What is the WEF ?", false, false); //移除第二个批注 document.Comments.RemoveAt(1); //保存并打开文档 document.SaveToFile("RemoveAndReplace.docx", FileFormat.Docx); System.Diagnostics.Process.Start("RemoveAndReplace.docx"); } } } VB.NET Imports Spire.Doc Namespace ReplaceAndRemoveComment_Word Class Program Private Shared Sub Main(ByVal args() As String) '初始化Document类实例,加载带有批注的Word文档 Dim document As Document = New Document document.LoadFromFile("test.docx") '修改第一个批注内容 document.Comments(0).Body.Paragraphs(0).Replace("This paragraph describes the origin and the purpose of WEF", "What is the WEF ?", false, false) '移除第二个批注 document.Comments.RemoveAt(1) '保存并打开文档 document.SaveToFile("RemoveAndReplace.docx", FileFormat.Docx) System.Diagnostics.Process.Start("RemoveAndReplace.docx") End Sub End Class End Namespace 测试结果: 以上是本次关于操作Word批注的全部内容。感谢浏览!
一、概述 数据透视表(Pivot Table)是一种交互式的表,可以进行某些计算,如求和与计数等,可动态地改变透视表版面布置,也可以重新安排行号、列标和页字段。当改变版面布置时,数据透视表也会按照新的布置来进行更新,可以说是一个功能强大的数据分析工具。因此,本篇文章将介绍在C# 中关于Excel数据透视表的操作示例,示例内容主要包含以下要点: 1. 创建透视表 (1)创建数据缓存 (2)创建数据透视表 (3)添加行字段和列字段 (4)添加值字段 (5)设置样式 2. 设置行折叠、展开 3. 设置字段升序、降序 4. 删除透视表 二、准备工具 Spire.XLS for .NET (可支持80余种Excel内置的数据透视表样式) PS:安装后,注意在项目中引用Spire.XLS.dll再进行代码操作,dll文件在安装路径下的Bin文件夹中获取。 三、示例操作 1.创建透视表 C# //创建一个Workbook类实例,并加载Excel文档 Workbook workbook = new Workbook(); workbook.LoadFromFile("test.xlsx"); //获取第一个工作表 Worksheet sheet = workbook.Worksheets[0]; //为需要汇总和分析的数据创建缓存 CellRange dataRange = sheet.Range["A1:D10"]; PivotCache cache = workbook.PivotCaches.Add(dataRange); //使用缓存创建数据透视表,并指定透视表的名称以及在工作表中的位置 PivotTable pivotTable = sheet.PivotTables.Add("PivotTable", sheet.Range["A12"], cache); //添加行字段 var r1 = pivotTable.PivotFields["月份"]; r1.Axis = AxisTypes.Row; var r2 = pivotTable.PivotFields["厂商"]; r2.Axis = AxisTypes.Row; //设置行字段的标题 pivotTable.Options.RowHeaderCaption = "月份"; //添加列字段 var col1 = pivotTable.PivotFields["产品"]; col1.Axis = AxisTypes.Column; //设置列字段的标题 pivotTable.Options.ColumnHeaderCaption = "产品"; //添加值字段 pivotTable.DataFields.Add(pivotTable.PivotFields["总产量"], "求和项:总产量", SubtotalTypes.Sum); //设置透视表的样式(Spire.XLS共支持80余种Excel内置的数据透视表样式) pivotTable.BuiltInStyle = PivotBuiltInStyles.PivotStyleDark13; //保存并打开文档 workbook.SaveToFile("数据透视表.xlsx", ExcelVersion.Version2013); System.Diagnostics.Process.Start("数据透视表.xlsx"); 测试结果: 2. 设置行折叠、展开 C# //创建Workbook类对象,加载Excel文档 Workbook workbook = new Workbook(); workbook.LoadFromFile("数据透视表.xlsx"); //获取数据透视表 XlsPivotTable pivotTable = workbook.Worksheets[0].PivotTables[0] as XlsPivotTable; //计算数据 pivotTable.CalculateData(); //展开”月份”字段下“2”的详细信息 (pivotTable.PivotFields["月份"] as Spire.Xls.Core.Spreadsheet.PivotTables.XlsPivotField).HideItemDetail("2", false); //折叠”月份”字段下“3”的详细信息 (pivotTable.PivotFields["月份"] as Spire.Xls.Core.Spreadsheet.PivotTables.XlsPivotField).HideItemDetail("3", true); //保存并打开文档 workbook.SaveToFile("折叠、展开行.xlsx", ExcelVersion.Version2013); System.Diagnostics.Process.Start("折叠、展开行.xlsx"); 测试结果: 3. 设置字段排序 这里支持三种不同类型的排序,可根据需要选择相应的排序类型。 C# //创建一个Workbook类对象,并加载Excel文档 Workbook workbook = new Workbook(); workbook.LoadFromFile("数据透视表.xlsx"); //获取数据透视表 Spire.Xls.Core.Spreadsheet.PivotTables.XlsPivotTable pivotTable = workbook.Worksheets[0].PivotTables[0] as Spire.Xls.Core.Spreadsheet.PivotTables.XlsPivotTable; //对指定字段进行升序排序 pivotTable.PivotFields[2].SortType = PivotFieldSortType.Ascending; //保存并打开文档 workbook.SaveToFile("升序.xlsx", ExcelVersion.Version2013); System.Diagnostics.Process.Start("升序.xlsx"); 测试结果: 4. 删除透视表 删除透视表可通过以下两种方法: 根据透视表名称删除 根据透视表索引删除 //创建一个工作簿,并加载Excel文档 Workbook workbook = new Workbook(); workbook.LoadFromFile("数据透视表.xlsx"); //删除第一张工作表上名称为“PivotTable”的数据透视表 workbook.Worksheets[0].PivotTables.Remove("PivotTable"); //删除第一张工作表上索引为0即第一个数据透视表 //workbook.Worksheets[0].PivotTables.RemoveAt(0); //保存文档 workbook.SaveToFile("删除数据透视表.xlsx", ExcelVersion.Version2013); 测试结果: 以上内容为本次关于“Excel数据透视表的示例操作”的全部内容,欢迎转载(转载请注明出处) 感谢阅读!
在Word文档中,对于有多条并列的信息内容或者段落时,我们常以添加项目标号的形式来使文档条理化,在阅读时,文档也更具美观性。另外,对于在逻辑上存在一定层级结构的内容时,也可以通过多级编号列表来标明文档内容的层次,并且,在修改、编辑文档时也增加了灵活性。因此,在本篇文档中,将介绍如何在C#中通过使用类库Free Spire.Doc for .NET 来创建项目编号列表和多级编号列表的方法。 使用工具: Free Spire.Doc for .NET(社区版) 使用方法:在安装该类库后,在项目中引用Spire.Doc.dll即可(dll文件可在安装路径下的Bin文件夹中获取) 一、创建项目标号列表 using Spire.Doc; using Spire.Doc.Documents; namespace WordBullets { class Program { static void Main(string[] args) { //初始化Document类实例,并添加section Document doc = new Document(); Section section = doc.AddSection(); //添加七个段落并分别添加文字 Paragraph para1 = section.AddParagraph(); para1.AppendText("国际政治类组织"); Paragraph para2 = section.AddParagraph(); para2.AppendText("欧洲联盟(欧盟)"); Paragraph para3 = section.AddParagraph(); para3.AppendText("独立国家联合体(独联体)"); Paragraph para4 = section.AddParagraph(); para4.AppendText("上海合作组织"); Paragraph para5 = section.AddParagraph(); para5.AppendText("阿拉伯会议联盟"); Paragraph para6 = section.AddParagraph(); para6.AppendText("国际生态安全合作组织"); Paragraph para7 = section.AddParagraph(); para7.AppendText("阿拉伯国家联盟"); //创建段落格式(字体) ParagraphStyle style = new ParagraphStyle(doc); style.Name = "fontStyle"; style.CharacterFormat.FontName = "宋体"; style.CharacterFormat.FontSize = 12f; doc.Styles.Add(style); //遍历所有段落 for (int i = 0; i < section.Paragraphs.Count; i++) { //从第二段开始应用项目符号排列 if (i != 0) { section.Paragraphs[i].ApplyStyle(BuiltinStyle.ListBullet2); } //应用字体格式到每一段 section.Paragraphs[i].ApplyStyle("fontStyle"); } //保存并打开文档 doc.SaveToFile("项目列表.docx", FileFormat.Docx2013); System.Diagnostics.Process.Start("项目列表.docx"); } } } 测试效果: 二、创建多级编号列表 using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; namespace Multi_levelList_Doc { class Program { static void Main(string[] args) { //新建Word文档 Document doc = new Document(); Section section = doc.AddSection(); //初始化ListStyle对象,指定List类型为数字列表并命名 ListStyle listStyle = new ListStyle(doc, ListType.Numbered); listStyle.Name = "levelstyle"; //设定一级列表模式为阿拉伯数字 listStyle.Levels[0].PatternType = ListPatternType.Arabic; //设置二级列表数字前缀及模式 listStyle.Levels[1].NumberPrefix = "\x0000."; listStyle.Levels[1].PatternType = ListPatternType.Arabic; //设置三级列表数字前缀及模式 listStyle.Levels[2].NumberPrefix = "\x0000.\x0001."; listStyle.Levels[2].PatternType = ListPatternType.Arabic; //在ListStyles集合中添加新建的list style doc.ListStyles.Add(listStyle); //创建字体格式 Spire.Doc.Formatting.CharacterFormat format = new Spire.Doc.Formatting.CharacterFormat(doc); format.FontName = "宋体"; //添加段落,设置一级序列 Paragraph paragraph = section.AddParagraph(); TextRange tr = paragraph.AppendText("主要组织机构"); tr.ApplyCharacterFormat(format); //应用字体格式 paragraph.ApplyStyle(BuiltinStyle.Heading1); //应用标题1样式 paragraph.ListFormat.ApplyStyle("levelstyle"); //应用列表样式 //添加段落,设置一级序列 paragraph = section.AddParagraph(); tr = paragraph.AppendText("主要职能"); tr.ApplyCharacterFormat(format); paragraph.ApplyStyle(BuiltinStyle.Heading1); paragraph.ListFormat.ApplyStyle("levelstyle"); //添加段落,设置二级序列 paragraph = section.AddParagraph(); tr = paragraph.AppendText("基本职能"); tr.ApplyCharacterFormat(format); paragraph.ApplyStyle(BuiltinStyle.Heading2); paragraph.ListFormat.ListLevelNumber = 1; //设置等级为第二等级 paragraph.ListFormat.ApplyStyle("levelstyle"); //添加段落,设置二级序列 paragraph = section.AddParagraph(); tr = paragraph.AppendText("5大职能"); tr.ApplyCharacterFormat(format); paragraph.ApplyStyle(BuiltinStyle.Heading2); paragraph.ListFormat.ContinueListNumbering(); paragraph.ListFormat.ApplyStyle("levelstyle"); //添加段落,设置三级序列 paragraph = section.AddParagraph(); tr = paragraph.AppendText("管理职能 \n 组织职能 \n 协调职能 \n 调节职能 \n 提供职能"); tr.ApplyCharacterFormat(format); paragraph.ApplyStyle(BuiltinStyle.Heading5); paragraph.ListFormat.ListLevelNumber = 2; //设置等级为第三等级 paragraph.ListFormat.ApplyStyle("levelstyle"); //添加段落,设置一级序列 paragraph = section.AddParagraph(); tr = paragraph.AppendText("基本原则"); tr.ApplyCharacterFormat(format); paragraph.ApplyStyle(BuiltinStyle.Heading1); paragraph.ListFormat.ApplyStyle("levelstyle"); //保存并打开文档 doc.SaveToFile("多级列表.docx", FileFormat.Docx); System.Diagnostics.Process.Start("多级列表.docx"); } } } 测试效果: 以上代码供参考,欢迎转载(转载请注明出处)。 感谢阅读!
对于一些重要的word文档,出于防止资料被他人查看,或者防止文档被修改的目的,我们在选择文档保护时可以选择文档打开添加密码或者设置文档操作权限等,在下面的文章中将介绍如何使用类库Free Spire.Doc for .NET来加密、解密以及给文档设置操作权限等,主要分为以下几个要点来具体阐述 添加Word密码保护 解除Word密码保护 设置word文档操作权限 设置Word部分内容编辑权限 工具使用: 安装Free Spire.Doc之后,在程序中引用Spire.Doc.dll即可(dll可以在安装路径下的Bin文件夹中获取) 1. Word文档加密 using Spire.Doc; namespace EncryptWord_Doc { class Program { static void Main(string[] args) { //初始化一个Document类实例并加载需要加密的Word文档 Document doc = new Document(@"C:\Users\Administrator\Desktop\sample.docx"); //设置打开Word文档的密码 doc.Encrypt("abc123"); //保存并打开文档 doc.SaveToFile("加密文件.docx", FileFormat.Docx2013); System.Diagnostics.Process.Start("加密文件.docx"); } } } 调试运行程序,生成文档后,可见如下文档效果: 正确输入密码后就可以打开文档了。 2. Word文档解密 using Spire.Doc; namespace DecryptWord_Doc { class Program { static void Main(string[] args) { //初始化一个Document类实例 Document doc = new Document(); //加载密码参数为"adc123"的Word文档 doc.LoadFromFile("加密文件.docx", FileFormat.Docx2013, "abc123"); //调用方法RemoveEncryption()解除密码保护 doc.RemoveEncryption(); //保存文档并打开文档 doc.SaveToFile("解密文件.docx", FileFormat.Docx2013); System.Diagnostics.Process.Start("解密文件.docx"); } } } 此时打开文档时已经没有密码保护了。 3. Word文档操作权限设置 (这里提供了4种不同类型的操作权限,可以根据自己的需要选择相应的类型) using Spire.Doc; namespace EditPermissions_Doc { class Program { static void Main(string[] args) { //新建一个Document类对象并加载需要设置编辑权限的Word文档 Document doc = new Document(@"C:\Users\Administrator\Desktop\sample.docx"); //不允许任何更改(只读),设置解除限制编辑的密码 doc.Protect(ProtectionType.AllowOnlyReading, "123"); //只允许填写窗体,设置解除限制编辑的密码 doc.Protect(ProtectionType.AllowOnlyFormFields, "123"); //只允许批注,设置解除限制编辑的密码 doc.Protect(ProtectionType.AllowOnlyComments, "123"); //只允许修订,设置解除限制编辑的密码 doc.Protect(ProtectionType.AllowOnlyRevisions, "123"); //保存并预览文件 doc.SaveToFile("有限权限文档3.docx",FileFormat.Docx2013); System.Diagnostics.Process.Start("有限权限文档3.docx"); } } } 4. 设置部分文档内容权限 (当文档中部分内容不想被他人修改时,也可以设置该部分内容的可编辑权限,参考如下代码。) using Spire.Doc; namespace LockSpecifiedSections_Doc { class Program { static void Main(string[] args) { //创建一个Document类对象 Document doc = new Document(); //初始化2个section类实例,并添加文本内容到section Section s1 = doc.AddSection(); Section s2 = doc.AddSection(); s1.AddParagraph().AppendText("section 1"); s2.AddParagraph().AppendText("section 2"); //设置保护模式及密码 doc.Protect(ProtectionType.AllowOnlyFormFields, "123"); //设置section2 的保护属性为false,即,可编辑 s2.ProtectForm = false; //保存并打开文档 doc.SaveToFile("Protect_Section.docx",FileFormat.Docx2010); System.Diagnostics.Process.Start("Protect_Section.docx"); } } } 此时,生成的文档中,section1 这里是设置了编辑权限的,如果想要编辑需要输入密码。 以上全部内容为本次关于Word文档加密、解密以及文档操作权限设置的全部代码操作,代码供参考。如果喜欢,欢迎转载(转载请注明出处)。 感谢浏览!
Word是我们日常生活、学习和工作中必不可少的文档处理工具。精致美观的文档能给人带来阅读时视觉上的美感。在本篇文章中,将介绍如何使用组件Free Spire.Doc for .NET(社区版)给Word设置文档背景。下面的示例中,给Word添加背景分为三种情况来讲述,即添加纯色背景,渐变色背景和图片背景。 工具使用:下载安装控件Free Spire.Doc后,在项目程序中添加Spire.Doc.dll即可(该dll可在安装文件下Bin文件夹中获取) 一、添加纯色背景 using Spire.Doc; using System.Drawing; namespace AddBackground { class Program { static void Main(string[] args) { //创建一个Document类对象,并加载Word文档 Document document = new Document(); document.LoadFromFile(@"C:\Users\Administrator\Desktop\Test.docx"); //设置文档的背景填充模式为颜色填充 document.Background.Type = Spire.Doc.Documents.BackgroundType.Color; //设置背景颜色 document.Background.Color = Color.MistyRose; //保存并打开文档 document.SaveToFile("PureBackground.docx", FileFormat.Docx2013); System.Diagnostics.Process.Start("PureBackground.docx"); } } } 调试运行程序后,生成文档 二、添加渐变色背景 using Spire.Doc; using System.Drawing; using Spire.Doc.Documents; namespace AddGradientBackground { class Program { static void Main(string[] args) { //创建Document类实例,并加载Word文档 Document document = new Document(); document.LoadFromFile(@"C:\Users\Administrator\Desktop\Test.docx"); //设置文档的背景填充模式为渐变填充 document.Background.Type = Spire.Doc.Documents.BackgroundType.Gradient; //设置渐变背景颜色 BackgroundGradient gradient = document.Background.Gradient; gradient.Color1 = Color.LightSkyBlue; gradient.Color2 = Color.PaleGreen; //设置渐变模式 gradient.ShadingVariant = GradientShadingVariant.ShadingMiddle; gradient.ShadingStyle = GradientShadingStyle.FromCenter; //保存并打开文档 document.SaveToFile("GradientColor.docx", FileFormat.Docx2013); System.Diagnostics.Process.Start("GradientColor.docx"); } } } 三、添加图片背景 using System.Drawing; using Spire.Doc; namespace ImageBackground { class Program { static void Main(string[] args) { //创建一个Document类实例,并加载Word文档 Document document = new Document(); document.LoadFromFile(@"C:\Users\Administrator\Desktop\Test.docx"); //设置文档的背景填充模式为图片填充 document.Background.Type = Spire.Doc.Documents.BackgroundType.Picture; //设置背景图片 document.Background.Picture = Image.FromFile(@"C:\Users\Administrator\Desktop\1.jpg"); //保存并打开文档 document.SaveToFile("ImageBackground.docx", FileFormat.Docx2013); System.Diagnostics.Process.Start("ImageBackground.docx"); } } } 以上全部内容为三种添加Word文档背景的方法,如果喜欢本文,欢迎转载(转载请注明出处)。 感谢浏览!
在Word文档中,我们可以通过添加页眉、页脚的方式来丰富文档内容。添加页眉、页脚时,可以添加时间、日期、文档标题,文档引用信息、页码、内容解释、图片/LOGO等多种图文信息。同时也可根据需要调整文字或图片在页眉页脚的位置。因此,本文将介绍如何在C#中使用免费组件Free Spire. Doc for .NET来添加页眉、页脚的方法。 提示:下载安装该组件后注意在你的VS项目程序中引用dll文件(该dll文件可在安装文件下的Bin文件夹中获取) 一、添加文本、图片页眉 using Spire.Doc; using Spire.Doc.Documents; using System.Drawing; using Spire.Doc.Fields; namespace AddHeaderAndFooter { class Program { static void Main(string[] args) { //创建一个Document类实例,添加section和Paragraph Document document = new Document(@"C:\Users\Administrator\Desktop\Test.docx"); Section sec = document.AddSection(); Paragraph para = sec.AddParagraph(); //声明一个HeaderFooter类对象,添加页眉、页脚 HeaderFooter header = sec.HeadersFooters.Header; Paragraph headerPara = header.AddParagraph(); HeaderFooter footer = sec.HeadersFooters.Footer; Paragraph footerPara = footer.AddParagraph(); //添加图片和文本到页眉,并设置文本格式 DocPicture headerImage = headerPara.AppendPicture(Image.FromFile(@"C:\Users\Administrator\Desktop\2.jpg")); TextRange TR = headerPara.AppendText("The Word Trade Organization, WTO"); TR.CharacterFormat.FontName = "Andalus"; TR.CharacterFormat.FontSize = 12; TR.CharacterFormat.TextColor = Color.Green; TR.CharacterFormat.Bold = false; headerImage.TextWrappingType = TextWrappingType.Right; //添加文本到页脚,并设置格式 TR = footerPara.AppendText("The World Trade Organization is an intergovernmental organization that regulates international trade.The WTO officially commenced on 1 January 1995 under the Marrakesh Agreement, signed by 123 nations on 15 April 1994, replacing the General Agreement on Tariffs and Trade, which commenced in 1948. "); TR.CharacterFormat.Bold = false; TR.CharacterFormat.FontSize = 9; //保存文档并运行该文档 document.SaveToFile("图文页眉.docx", FileFormat.Docx); System.Diagnostics.Process.Start("图文页眉.docx"); } } } 运行结果: PS :对于需要设置图片在文字中的位置的情况,我们可以通过TextWrappingStyle或TextWrappingTpye 来实现。 Eg: headerImage.TextWrappingStyle = TextWrappingStyle.Through;或 headerImage.TextWrappingType = TextWrappingType.Right; 二、添加页码 添加页码,我们可以选择在页眉或者页脚处添加。 using Spire.Doc; using Spire.Doc.Documents; namespace AddPageNumber_Doc { class Program { static void Main(string[] args) { //实例化一个Document类,添加section和Paragraph Document document = new Document(); Section sec = document.AddSection(); Paragraph para = sec.AddParagraph(); //添加文本到paragraph,设置BreakType为分页 para.AppendText("第1页"); para.AppendBreak(BreakType.PageBreak); para.AppendText("第2页"); //创建一个HeaderFooter类实例,添加页脚 HeaderFooter footer = sec.HeadersFooters.Footer; Paragraph footerPara = footer.AddParagraph(); //添加字段类型为页码,添加当前页、分隔线以及总页数 footerPara.AppendField("页码", FieldType.FieldPage); footerPara.AppendText(" / "); footerPara.AppendField("总页数", FieldType.FieldNumPages); footerPara.Format.HorizontalAlignment = HorizontalAlignment.Right; //保存文档 document.SaveToFile("添加页码.docx", FileFormat.Docx); System.Diagnostics.Process.Start("添加页码.docx"); } } } 效果展示: 以上是本文关于Word如何添加页眉、页脚和页码的代码操作。如果喜欢,欢迎转载(转载请注明出处)。 感谢浏览!
一款有着强大的文档转换功能的工具,无论何时何地都会是现代办公环境极为需要的。在本篇文章中,将继续介绍关于Word文档的转换功能(Word转XPS/SVG/EMF/EPUB/TIFF)希望方法中的代码能为各位开发者们提供一定的参考价值。 PS:更多Word转换功能可以参阅这两篇文章 Word转HTML/XML/PDF/IMAGE Word转TXT 使用工具:Free Spire.Doc for .NET 使用方法:下载安装该控件后,在VS控制台应用程序中添加引用Spire.Doc.dll文件(dll文件可在该安装文件夹下Bin中获取) 1. Word转XPS using Spire.Doc; using System; namespace WordtoXPS_Doc { class Program { static void Main(string[] args) { //初始化String类,元素为需要转换的Word文档 String file = "sample.docx"; //创建一个Document类对象,加载sample文件 Document doc = new Document(file); //将Word文件保存为XPS,并运行生成的文档 doc.SaveToFile("Word2XPS.xps", FileFormat.XPS); System.Diagnostics.Process.Start("Word2XPS.xps"); } } } 调试运行该项目生成文档,如下图: 2. Word转SVG using Spire.Doc; namespace WordtoSVG_Doc { class Program { static void Main(string[] args) { //实例化Document类,并加载Word sample Document doc = new Document(); doc.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.docx"); //保存为svg格式 doc.SaveToFile("result.svg", FileFormat.SVG); } } } 3. Word转Emf using Spire.Doc; using System.Drawing; using System.Drawing.Imaging; namespace WordtoEmf_Doc { class Program { static void Main(string[] args) { //实例化一个Document类,并加载Word sample Document doc = new Document(); doc.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.docx", FileFormat.Docx); //调用方法 SaveToImages()将Word第一页转为image并保存为Emf格式 System.Drawing.Image image = doc.SaveToImages(0, Spire.Doc.Documents.ImageType.Metafile); image.Save("WordtoEmf.emf", ImageFormat.Emf); } } } 4. Word转Epub using Spire.Doc; namespace WordtoEPUB { class Epub { static void Main(string[] args) { //实例化Document类,并加载Word sample Document document = new Document(); document.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.docx"); //保存为Epub格式,并运行生成的文档 document.SaveToFile("ToEpub.epub", FileFormat.EPub); System.Diagnostics.Process.Start("ToEpub.epub"); } } } 5. Word转Word XML using Spire.Doc; namespace WordtoWordXML_Doc { class Program { static void Main(string[] args) { //创建一个Document类对象并加载Word sample Document doc = new Document(); doc.LoadFromFile("sample.docx"); //调用方法SaveToFile()保存Word为Word Xml doc.SaveToFile("WordToWordXML.xml", FileFormat.WordXml); } } } 6. Word转Tiff using Spire.Doc; using Spire.Doc.Documents; using System; using System.Drawing; using System.Drawing.Imaging; namespace convert_word_to_tiff { class Program { static void Main(string[] args) { //实例化一个Document类,加载Word sample Document document = new Document(@"C:\Users\Administrator\Desktop\sample.docx"); //调用方法JoinTiffImages()将Word保存为tiff格式,并运行生成的文档 JoinTiffImages(SaveAsImage(document), "result.tiff", EncoderValue.CompressionLZW); System.Diagnostics.Process.Start("result.tiff"); } //自定义方法SaveAsImage()将Word文档保存为图像 private static Image[] SaveAsImage(Document document) { Image[] images = document.SaveToImages(ImageType.Bitmap); return images; } private static ImageCodecInfo GetEncoderInfo(string mimeType) { ImageCodecInfo[] encoders = ImageCodecInfo.GetImageEncoders(); for (int j = 0; j < encoders.Length; j++) { if (encoders[j].MimeType == mimeType) return encoders[j]; } throw new Exception(mimeType + " mime type not found in ImageCodecInfo"); } //自定义方法JoinTiffImages()将Word保存为TIFF图片格式(使用指定编码器和图像编码参数) public static void JoinTiffImages(Image[] images, string outFile, EncoderValue compressEncoder) { System.Drawing.Imaging.Encoder enc = System.Drawing.Imaging.Encoder.SaveFlag; EncoderParameters ep = new EncoderParameters(2); ep.Param[0] = new EncoderParameter(enc, (long)EncoderValue.MultiFrame); ep.Param[1] = new EncoderParameter(System.Drawing.Imaging.Encoder.Compression, (long)compressEncoder); Image pages = images[0]; int frame = 0; ImageCodecInfo info = GetEncoderInfo("image/tiff"); foreach (Image img in images) { if (frame == 0) { pages = img; pages.Save(outFile, info, ep); } else { ep.Param[0] = new EncoderParameter(enc, (long)EncoderValue.FrameDimensionPage); pages.SaveAdd(img, ep); } if (frame == images.Length - 1) { ep.Param[0] = new EncoderParameter(enc, (long)EncoderValue.Flush); pages.SaveAdd(ep); } frame++; } } } } 以上是本次关于Word转成其他格式文件的具体描述,方法中的代码供参考。欢迎转载(转载请注明出处)
在前面的文章中,我们已经知道如何合并、拆分多个PDF文件,在这篇文章中的合并、拆分PDF文档主要是以方便文档管理的目的来操作文档,在文档查阅、管理及存储上很方便实用。但是我们如果想要合并多个文档中的部分文档页的内容,该如何来做呢?可以参考接下来将要介绍的合并方法。 PS: 本篇文章是对Free Spire.PDF 的合并功能的进一步介绍,即如何合并多个PDF文档中的指定页(指定单页、指定多页)为一个新文档,更多关于Free Spire.PDF对PDF文档的操作功能可参阅这里的博客。 使用工具:Free Spire.PDF for .NET 提示:下载安装该组件后,注意在项目程序中添加引用Spire.PDF.dll文件 代码细节可参考以下主要代码段: //初始化数组,数组元素为需要合并的PDF文档 string[] files = { "sample1.pdf", "sample2.pdf" }; PdfDocument[] docs = new PdfDocument[files.Length]; //遍历PDF文档 for (int i = 0; i < files.Length; i++) { docs[i] = new PdfDocument(); docs[i].LoadFromFile(files[i]); } //创建一个新的PDF文档并插入从原文档选取的指定页 PdfDocument doc = new PdfDocument(); doc.InsertPage(docs[0], 0);//指定单页 doc.InsertPageRange(docs[1], 0, 1);//指定多页 //保存并命名合并后的文档,同时运行文档 doc.SaveToFile("Result.pdf"); Process.Start("Result.pdf"); 合并前: 合并后: 全部代码 C# using Spire.Pdf; using System.Diagnostics; namespace MergeSelectedPDFpages { class Program { static void Main(string[] args) { string[] files = { "sample1.pdf", "sample2.pdf" }; PdfDocument[] docs = new PdfDocument[files.Length]; for (int i = 0; i < files.Length; i++) { docs[i] = new PdfDocument(); docs[i].LoadFromFile(files[i]); } PdfDocument doc = new PdfDocument(); doc.InsertPage(docs[0], 0); doc.InsertPageRange(docs[1], 0, 1); doc.SaveToFile("Result.pdf"); Process.Start("Result.pdf"); } } } VB.NET Imports Spire.Pdf Imports System.Diagnostics Namespace MergeSelectedPDFpages Class Program Private Shared Sub Main(ByVal args() As String) Dim files() As String = New String() {"sample1.pdf", "sample2.pdf"} Dim docs() As PdfDocument = New PdfDocument((files.Length) - 1) {} Dim i As Integer = 0 Do While (i < files.Length) docs(i) = New PdfDocument docs(i).LoadFromFile(files(i)) i = (i + 1) Loop Dim doc As PdfDocument = New PdfDocument doc.InsertPage(docs(0), 0) doc.InsertPageRange(docs(1), 0, 1) doc.SaveToFile("Result.pdf") Process.Start("Result.pdf") End Sub End Class End Namespace 以上内容是本次关于“如何合并PDF文档指定页”的全部介绍,如果喜欢,欢迎转载(转载请注明出处) 感谢阅读!
PDF是一种在我们日常工作学习中最常用到的文档格式之一,但常常也会因为文档的不易编辑的特点,在遇到需要编辑PDF文档内容或者转换文件格式的情况时让人苦恼。通常对于开发者而言,可选择通过使用组件的方式来实现PDF文档的编辑或者格式转换,因此本文将介绍如何通过使用免费版的组件Free Spire.PDF for .NET来转换PDF文档。这里介绍将PDF转换多种不同格式的图像文件格式,如PNG,BMP,EMF,TIFF等,同时,转换文档也分为转换全部文档和转换部分文档为图片两种情况,本文也将作进一步介绍。下面是实现转换功能的详述,供参考。 提示:在下载安装该组件后,在项目中注意添加引用Spire.PDF.dll文件,如下图: 一、转换整个PDF文档为图片 (一)PDF转Png using Spire.Pdf; using System.Drawing; namespace PDFtoImage1 { class Program { static void Main(string[] args) { //初始化一个PdfDocument类实例,并加载PDF文档 PdfDocument doc = new PdfDocument(); doc.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.pdf"); //遍历PDF每一页 for (int i = 0; i < doc.Pages.Count; i++) { //将PDF页转换成Bitmap图形 System.Drawing.Image bmp = doc.SaveAsImage(i); //将Bitmap图形保存为Png格式的图片 string fileName = string.Format("Page-{0}.png", i + 1); bmp.Save(fileName, System.Drawing.Imaging.ImageFormat.Png); } } } } 调试运行程序,生成文档。 运行结果: Spire.PDF支持将PDF文档转换为多种图像格式的文件,可根据需要选择相应的文件格式,这里以Png为例。 (二) PDF转TIFF using System; using System.Drawing; using System.Drawing.Imaging; using Spire.Pdf; namespace SavePdfAsTiff { class Program { static void Main(string[] args) { //创建一个PdfDocument类对象,并加载PDF文档 PdfDocument document = new PdfDocument(); document.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.pdf"); //调用方法SaveAsImage()将PDF文档保存为tiff格式 JoinTiffImages(SaveAsImage(document), "result.tiff", EncoderValue.CompressionLZW); System.Diagnostics.Process.Start("result.tiff"); } //自定义方法SaveAsImage()将PDF文档保存图像文件 private static Image[] SaveAsImage(PdfDocument document) { Image[] images = new Image[document.Pages.Count]; for (int i = 0; i < document.Pages.Count; i++) { images[i] = document.SaveAsImage(i); } return images; } private static ImageCodecInfo GetEncoderInfo(string mimeType) { ImageCodecInfo[] encoders = ImageCodecInfo.GetImageEncoders(); for (int j = 0; j < encoders.Length; j++) { if (encoders[j].MimeType == mimeType) return encoders[j]; } throw new Exception(mimeType + " mime type not found in ImageCodecInfo"); } //自定义JoinTiffImages()方法,使用指定编码器和图像编码器参数将图像从pdf页面保存到tiff图像类型,。 public static void JoinTiffImages(Image[] images, string outFile, EncoderValue compressEncoder) { Encoder enc = Encoder.SaveFlag; EncoderParameters ep = new EncoderParameters(2); ep.Param[0] = new EncoderParameter(enc, (long)EncoderValue.MultiFrame); ep.Param[1] = new EncoderParameter(Encoder.Compression, (long)compressEncoder); Image pages = images[0]; int frame = 0; ImageCodecInfo info = GetEncoderInfo("image/tiff"); foreach (Image img in images) { if (frame == 0) { pages = img; pages.Save(outFile, info, ep); } else { ep.Param[0] = new EncoderParameter(enc, (long)EncoderValue.FrameDimensionPage); pages.SaveAdd(img, ep); } if (frame == images.Length - 1) { ep.Param[0] = new EncoderParameter(enc, (long)EncoderValue.Flush); pages.SaveAdd(ep); } frame++; } } } } 运行结果: 二、 转换PDF指定页为图片( PDF转Png、Bmp、Emf) using Spire.Pdf; using System.Drawing; using System.Drawing.Imaging; namespace PDFtoImage { class Program { static void Main(string[] args) { //实例化一个PdfDocument类对象,并加载PDF文档 PdfDocument doc = new PdfDocument(); doc.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.pdf"); //调用方法SaveAsImage()将PDF第二页保存为Bmp格式 Image bmp = doc.SaveAsImage(1); //调用另一个SaveAsImage()方法,并将指定页面保存保存为Emf、Png Image emf = doc.SaveAsImage(0, Spire.Pdf.Graphics.PdfImageType.Metafile); Image zoomImg = new Bitmap((int)(emf.Size.Width * 2), (int)(emf.Size.Height * 2)); using (Graphics g = Graphics.FromImage(zoomImg)) { g.ScaleTransform(2.0f, 2.0f); g.DrawImage(emf, new Rectangle(new Point(0, 0), emf.Size), new Rectangle(new Point(0, 0), emf.Size), GraphicsUnit.Pixel); } //命名保存的文件并打开 bmp.Save("convertToBmp.bmp", ImageFormat.Bmp); System.Diagnostics.Process.Start("convertToBmp.bmp"); emf.Save("convertToEmf.emf", ImageFormat.Emf); System.Diagnostics.Process.Start("convertToEmf.emf"); zoomImg.Save("convertToZoom.png", ImageFormat.Png); System.Diagnostics.Process.Start("convertToZoom.png"); } } } 运行结果: PS:更多关于PDF转换功能的介绍可参见以下博客内容: XPS to PDF HTML to PDF PDF to Word PDF to XPS PDF to SVG 以上全部内容为本篇文章关于PDF转为多种图像文件的方法介绍,如果喜欢本文欢迎转载(转载请注明出处)。 感谢阅读!
PDF格式的文档广泛用于各种办公场所,在工作中难免会有将PDF文档转换为其他文档格式的需要。在本篇文档中,将介绍PDF转为SVG的方法。根据不同的转换需求,这里分三种情况进行讲述,即转PDF所有页为SVG、转PDF指定页为SVG和转PDF到指定高度、宽度的SVG。以上三种情况,下面将作详细介绍。 使用工具:Spire.PDF for .NET 提示:使用该组件需要先下载安装,在项目程序中注意须添加引用Spire.PDF.dll文件(如下所示) 原PDF文档: 1.将PDF所有页转为SVG using Spire.Pdf; namespace PDFtoSVG_PDF { class Program { static void Main(string[] args) { //新建一个PdfDocument类对象,加载sample,保存为SVG格式的文件 PdfDocument document = new PdfDocument(); document.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.pdf"); document.SaveToFile("output.svg", FileFormat.SVG); } } } 调试运行该项目,生成文档: 2.将指定PDF页转为SVG using Spire.Pdf; namespace ConvertPDFPagetoSVG_PDF { class Program { static void Main(string[] args) { //实例化一个PdfDocument类对象 PdfDocument doc = new PdfDocument(); //加载PDF文件 doc.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.pdf"); //调用方法SaveToFile(string filename, int startIndex, int endIndex, FileFormat )将PDF指定页保存为SVG格式 doc.SaveToFile("Result.svg", 1, 2, FileFormat.SVG); } } } 调试运行程序后,可查看成功转换的SVG文档 转换后的文档: 3.PDF转指定宽度、高度的SVG using Spire.Pdf; namespace PDFtoSVG1_PDF { class Program { static void Main(string[] args) { //创建一个PdfDocument类对象,并加载PDF文件 PdfDocument document = new PdfDocument(); document.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.pdf"); //调用方法SetPdfToSvgOptions()指定转换SVG的宽度和高度 document.ConvertOptions.SetPdfToSvgOptions(700f, 1000f); //保存到文件,命名文档,并设置保存格式 document.SaveToFile("result.svg", FileFormat.SVG); } } } 以上内容为PDF转为SVG的三种情况的方法介绍,可根据不同的办公需求选择相应的转换方法。 如果喜欢,欢迎转载(转载请注明出处)
文档合并、拆分是实现文档管理的一种有效方式。在工作中,我们可能会遇到需要将多个文档合并的情况,那如何来实现呢,本文将进一步介绍。关于拆分Excel工作表,可参见这篇文章——C#如何拆分EXCEL工作表。 使用工具:Free Spire.XLS for .NET Visual Studio 2013 PS: 编辑代码前需要引用Spire.XLS.dll到项目程序中,并添加相应的命名空间 合并Excel表格分两种: 合并多个工作表为一个工作簿 二是合并多个工作表为一个工作表 一、合并多个工作表为一个工作簿 using Spire.Xls; namespace MergeWorksheet_XLS { class Program { static void Main(string[] args) { //创建一个Workbook类对象 Workbook newbook = new Workbook(); newbook.Version = ExcelVersion.Version2013; //删除文档中的工作表(新创建的文档默认包含3张工作表) newbook.Worksheets.Clear(); //创建一个临时的workbook,用于加载需要合并的Excel文档 Workbook tempbook = new Workbook(); //加载需要合并的Excel文档保存到数组 string[] excelFiles = new string[] { @"C:\Users\Administrator\Desktop\test.xlsx", @"C:\Users\Administrator\Desktop\sample.xlsx" }; //遍历数组 for (int i = 0; i < excelFiles.Length; i++) { //载入Excel文档 tempbook.LoadFromFile(excelFiles[i]); //调用AddCopy方法,将文档中所有工作表添加到新的workbook foreach (Worksheet sheet in tempbook.Worksheets) { newbook.Worksheets.AddCopy(sheet); } } //保存文档 newbook.SaveToFile("MergeFiles.xlsx", ExcelVersion.Version2013); } } } 合并前: 合并后: 二、合并多个工作表为一个工作表 using Spire.Xls; namespace MergeWorksheetsToOne_XLS { class Program { static void Main(string[] args) { //实例化一个Workbook类,加载Excel文档 Workbook workbook = new Workbook(); workbook.LoadFromFile(@"C:\Users\Administrator\Desktop\test.xlsx"); //获取第1、2张工作表 Worksheet sheet1 = workbook.Worksheets[0]; Worksheet sheet2 = workbook.Worksheets[1]; //复制第2张工作表内容到第1张工作表的指定区域中 sheet2.AllocatedRange.Copy(sheet1.Range[sheet1.LastRow +3, 1]); //删除第2张工作表 sheet2.Remove(); //重命名的工作表1 sheet1.Name = "外贸单证"; //保存并运行文档 workbook.SaveToFile("MergeSheets.xlsx", ExcelVersion.Version2013); System.Diagnostics.Process.Start("MergeSheets.xlsx"); } } } 合并前: 合并后: 以上合并方法为本次关于合并Excel文档的全部内容,如果有需要合并/拆分PDF、Word等文档,可参见链接处所给文章。 如果喜欢欢迎转载(转载请注明出处)
文档合并是一种高效文档处理方式。如果能够有一个方法能将多种不同类型的文档合并成一种文档格式,那么在文档存储管理上将为我们提供极大的便利。因此,本篇文章介绍了一种如何使用免费组件Free Spire.Office for .NET来实现将多种各式的文档合并为PDF的方法。本方法中可合并的文档格式可以是doc、docx、xls、xlsx、pdf等。下面将进行详细阐述。 使用方法:安装Free Spire.Office for .NET后,添加引用spire.doc.dll, spire.xls.dll, spire.pdf.dll三个文件,如下图所示: 添加以后,在命名空间添加如下using 指令: using Spire.Doc; using Spire.Xls; using Spire.Pdf; using System.IO; 文档合并前: 主要代码: //声明PdfDocument对象数组 PdfDocument[] documents = new PdfDocument[4]; using (MemoryStream ms1 = new MemoryStream()) { //加载doc文档 Document doc = new Document(@"C:\Users\Administrator\Desktop\sample.doc", Spire.Doc.FileFormat.Doc); //转换PDF,并以流的形式保存 doc.SaveToStream(ms1, Spire.Doc.FileFormat.PDF); //加载PDF流文件为PdfDocument对象数组的第一个元素 documents[0] = new PdfDocument(ms1); } using (MemoryStream ms2 = new MemoryStream()) { //加载docx文档 Document docx = new Document(@"C:\Users\Administrator\Desktop\test.docx", Spire.Doc.FileFormat.Docx2010); //转换PDF,并以流的形式保存 docx.SaveToStream(ms2, Spire.Doc.FileFormat.PDF); //加载PDF流文件为PdfDocument对象数组的第二个元素 documents[1] = new PdfDocument(ms2); } using (MemoryStream ms3 = new MemoryStream()) { //加载xlsx文档 Workbook workbook = new Workbook(); workbook.LoadFromFile(@"C:\Users\Administrator\Desktop\Sample.xlsx", ExcelVersion.Version97to2003); //转换PDF,并以流的形式保存 workbook.SaveToStream(ms3, Spire.Xls.FileFormat.PDF); //加载PDF流文件为PdfDocument对象数组的第三个元素 documents[2] = new PdfDocument(ms3); } //加载pdf文档,作为PdfDocument对象数组的第四个元素 documents[3] = new PdfDocument(@"C:\Users\Administrator\Desktop\sample.pdf"); //将前三个文档合并到第四个文档,并另存为新的PDF文档 for (int i = 2; i > -1; i--) { documents[3].AppendPage(documents[i]); } documents[3].SaveToFile("Result.pdf"); 完成代码后,调试运行该项目,生成文件。 合并效果展示: 以上全部内容为合并不同格式文件为PDF文件的方法,如果想合并多个单一格式的PDF文档为一个文件,可参见这篇文章:http://www.cnblogs.com/Yesi/p/5604166.html 。 如果喜欢本文,欢迎转载(转载请注明出处) 感谢浏览!
一般在创建或者打开一个Word文档时,如果没有进行过特殊设置的话,系统默认的输入语言的是英语输入,但是为适应不同的办公环境,我们其实是需要对文字嵌入的语言进行切换的,因此,本文将介绍如何使用免费版组件Free Spire.Doc for .NET来实现Word语言输入。另外,针对这款组件的多种Word操作功能,如,设置文档属性、文档视图模式等,本文中也将作进一步演示演示。 代码操作前准备 安装Spire.Doc for .NET之后,添加引用Spire.Doc.dll文件到项目程序集,同时添加相应的using指令到命名空间。 注意:以下代码中,以选取西班牙语(秘鲁)为例,其他语言设置,可参见 Microsoft Locale ID Values 具体步骤如下: 步骤一:添加如下命名空间 using System; using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; 步骤二:更改文本输入语言 //创建一个Document类实例,并添加Section和Paragraph到Document Document doc = new Document(); Section sec = doc.AddSection(); Paragraph para = sec.AddParagraph(); //向段落添加西班牙(秘鲁)语文字并设置文本对齐方式 TextRange txtRange = para.AppendText("Puedo escribir los versos más tristes esta noche.\n Escribir, por ejemplo: La noche está estrellada,y tiritan, azules, los astros, a lo lejos.\n El viento de la noche gira en el cielo y canta.\n Puedo escribir los versos más tristes esta noche."); txtRange.CharacterFormat.LocaleIdASCII= 10250; para.Format.HorizontalAlignment = HorizontalAlignment.Center; 步骤三:设置试图模式为Web视图,调整视图缩放比例 doc.ViewSetup.DocumentViewType = DocumentViewType.WebLayout; doc.ViewSetup.ZoomPercent = 120; doc.ViewSetup.ZoomType = ZoomType.None; 步骤四:添加文档属性(可根据需要自行设置文档内置属性或者自定义属性) //添加文档属性(内置属性) doc.BuiltinDocumentProperties.Title = "测试文件"; doc.BuiltinDocumentProperties.Category = "非机密文档"; doc.BuiltinDocumentProperties.Author = "James"; doc.BuiltinDocumentProperties.LastAuthor = "Mia"; doc.BuiltinDocumentProperties.Keywords = "Word文档, 属性, 样本"; doc.BuiltinDocumentProperties.Comments = "此文档仅供测试使用"; doc.BuiltinDocumentProperties.Subject = "Demo"; //添加文档属性(自定义属性) CustomDocumentProperties custom = doc.CustomDocumentProperties; custom.Add("Authorized Date", DateTime.Today); 步骤五:保存并打开文档 doc.SaveToFile("Sample.doc", FileFormat.Doc); System.Diagnostics.Process.Start("Sample.doc"); 完成以上步骤后,运行该项目生成文件(可在该项目文件夹下bin>Debug下查看),如下图所示: 对文档属性的设置如下图所示: 以上全部内容为本次对Word文档进行语言设置方法的讲述,文中对文档的属性设置在文档的保存与日后文档管理上其实也很有帮助。希望本文能提供一定帮助,欢迎转载(转载请注明出处)。感谢浏览!
对于Word中的邮件合并功能,用户可以将邮件合并后的结果文档保存并打印,也可以通过邮件的形式发送,在很多场合需要使用到此功能。那对于编程人员,我们也可以在C#语言环境中通过代码的形式来实现。根据需要先创建邮件合并模板后,可合并文本和图片,在下面的方法中,需要使用到组件Free Spire.Doc for .NET 。创建模板前,需先安装该组件,注意添加引用该组件dll文件到控制台应用程序中,同时添加命名空间。 一、创建邮件合并模板 第一步:添加命名空间 using System; using Spire.Doc; using Spire.Doc.Documents; using System.Drawing; using Spire.Doc.Fields; 第二步:主要代码段 //创建一个Document类对象,并添加Section Document document = new Document(); Section section = document.AddSection(); //添加段落到Section,并向段落添加文字,设置文字颜色、字体粗细 Paragraph paragraph = section.AddParagraph(); TextRange tr = paragraph.AppendText("人 物 基 本 信 息"); tr.CharacterFormat.TextColor = Color.YellowGreen; tr.CharacterFormat.Bold = true; //添加文本,并添加合并域“Image:Portrait” paragraph.AppendText("\n人 物 肖 像 : "); paragraph.AppendField("Image:Portrait", FieldType.FieldMergeField); //添加文本,并添加合并域“Name” paragraph.AppendText("\n姓 名 : "); paragraph.AppendField("Name", FieldType.FieldMergeField); //添加文本,并添加合并域“Nation” paragraph.AppendText("\n民 族 :"); paragraph.AppendField("Nation", FieldType.FieldMergeField); //添加文本,并添加合并域“Nationality” paragraph.AppendText("\n国 籍 : "); paragraph.AppendField("Nationality", FieldType.FieldMergeField); //添加文本,并添加合并域“Graduated From” paragraph.AppendText("\n院 校 : "); paragraph.AppendField("Graduated From", FieldType.FieldMergeField); //保存并打开文档 document.SaveToFile("模板.docx", FileFormat.Docx2013); System.Diagnostics.Process.Start("模板.docx"); 完成以上步骤后,调试运行程序,生成文件(可在项目文件下bin>Debug中查看) 如下图: 二:合并文本、图片 在完成模板创建之后,可添加文本和图片,如下: 第一步:添加命名空间 using System; using Spire.Doc; using System.Drawing; using Spire.Doc.Reporting; 第二步:主要代码段 static void Main(string[] args) { //实例化一个Document类,并加载文档模板 Document doc = new Document(); doc.LoadFromFile(@"C:\Users\Administrator\Desktop\模板.docx"); var textFieldNames = new string[] { "Name", "Nation", "Nationality", "Graduated From"}; var textFieldValues = new string[] { "乔 治•华 盛 顿 (George Washington)", "美 利 坚 民 族", "美 国", "威 廉 与 玛 丽 学 院 (William and Mary)"}; var imageFieldNames = new string[] { "Portrait" }; var imageFieldValues = new string[] { @"C:\Users\Administrator\Desktop\images\华盛顿.jpg" }; //合并文本到模板 doc.MailMerge.Execute(textFieldNames, textFieldValues); //创建合并图片自定义事件 doc.MailMerge.MergeImageField += new MergeImageFieldEventHandler(MailMerge_MergeImageField); //合并图片到模板 doc.MailMerge.Execute(imageFieldNames, imageFieldValues); //保存并打开文档 doc.SaveToFile("result.docx", FileFormat.Docx); System.Diagnostics.Process.Start("result.docx"); } //添加自定义事件载入图片 static void MailMerge_MergeImageField(object sender, MergeImageFieldEventArgs field) { string filePath = field.FieldValue as string; if (!string.IsNullOrEmpty(filePath)) { field.Image = Image.FromFile(filePath); } } 运行程序,生成文件,如下图: 以上全部内容为本文创建邮件合并模板并合并文本和图片的方法讲述,方法中使用到的组件Spire.Doc for .NET在处理Word文档方面具有很好的辅助作用,感兴趣的话可以动手试试。如果本文对你有所帮助,欢迎转载(转载请注明出处)。
表格能够直观的传达数据信息,使信息显得条理化,便于阅读同时也利于管理。那在PDF类型的文档中如何来添加表格并且对表格进行格式化操作呢?使用常规方法直接在PDF中添加表格行不通,那我们可以在借助第三方组件的情况下来实现。本篇文章中将介绍如何正确使用组件Free Spire.PDF for .NET添加表格到PDF。该组件提供了两个类PdfTable和PdfGrid用于创建表格,在进行代码编辑前,需先安装,添加Spire.PDF. dll到项目程序集中,同时添加到命名空间。下面是两种方法来添加表格的全部代码,供参考。 两种类用于创建表格的异同: PdfTable PdfGrid 行 无API支持,可通过事件设置 可直接通过API设置 列 可直接通过API设置(StringFormat) 可直接通过API设置(StringFormat) 单元格 无API支持,可通过事件设置 可直接通过API设置 单元格纵向合并 不支持 可直接通过API设置 单元格横向合并 无API支持,可通过事件设置 可直接通过API设置 嵌套表格 无API支持,可通过事件设置 可直接通过API设置 事件 BeginCellLayout, BeginPageLayout, BeginRowLayout, EndCellLayout, EndPageLayout, EndRowLayout BeginPageLayout, EndPageLayout 一、通过PdfTable类来创建表格 1 using System.Drawing; 2 using Spire.Pdf; 3 using Spire.Pdf.Tables; 4 using Spire.Pdf.Graphics; 5 using System.Data; 6 7 namespace DrawTable1_PDF 8 { 9 class Program 10 { 11 static void Main(string[] args) 12 { 13 //创建一个PdfDocument类对象并向文档新添加一页 14 PdfDocument doc = new PdfDocument(); 15 PdfPageBase page = doc.Pages.Add(); 16 17 //创建一个PdfTable对象 18 PdfTable table = new PdfTable(); 19 //设置字体 20 table.Style.DefaultStyle.Font = new PdfTrueTypeFont(new Font("Arial Unicode MS", 9f), true); 21 table.Style.HeaderStyle.Font = new PdfTrueTypeFont(new Font("Arial Unicode MS", 9f), true); 22 23 //创建一个DataTable并写入数据 24 DataTable dataTable = new DataTable(); 25 dataTable.Columns.Add("产品类型"); 26 dataTable.Columns.Add("产品编号"); 27 dataTable.Columns.Add("采购数额(件)"); 28 dataTable.Columns.Add("所属月份"); 29 30 dataTable.Rows.Add(new string[] { "A", "00101", "35", "7月"}); 31 dataTable.Rows.Add(new string[] { "B", "00102", "56", "8月"}); 32 dataTable.Rows.Add(new string[] { "C", "00103", "25", "9月"}); 33 34 //填充数据到PDF表格 35 table.DataSource = dataTable; 36 //显示表头(默认不显示) 37 table.Style.ShowHeader = true; 38 //在BeginRowLayout事件处理方法中注册自定义事件 39 table.BeginRowLayout += Table_BeginRowLayout; 40 41 //将表格绘入PDF并指定位置和大小 42 table.Draw(page, new RectangleF(0, 60, 200, 200)); 43 44 //保存到文档并预览 45 doc.SaveToFile("PDF表格_1.pdf"); 46 System.Diagnostics.Process.Start("PDF表格_1.pdf"); 47 } 48 49 //在自定义事件中设置行高 50 private static void Table_BeginRowLayout(object sender, BeginRowLayoutEventArgs args) 51 { 52 args.MinimalHeight = 10f; 53 } 54 } 55 } 运行程序生成文件(可在该项目文件下bin>Debug查看) 效果展示: 二、通过PdfGrid类来添加表格 1 using Spire.Pdf; 2 using System.Drawing; 3 using Spire.Pdf.Grid; 4 using Spire.Pdf.Graphics; 5 using Spire.Pdf.Tables; 6 7 namespace DrawTable_PDF 8 { 9 class Program 10 { 11 static void Main(string[] args) 12 { 13 //创建一个PdfDocument类对象,并新添加一页到PDF文档 14 PdfDocument doc = new PdfDocument(); 15 PdfPageBase page = doc.Pages.Add(); 16 17 //创建一个PdfGrid对象 18 PdfGrid grid = new PdfGrid(); 19 //设置单元格边距和表格默认字体 20 grid.Style.CellPadding = new PdfPaddings(1, 1, 1, 1); 21 grid.Style.Font = new PdfTrueTypeFont(new Font("Arial Unicode MS", 9f), true); 22 23 //添加一个5行6列表格到新建的PDF文档 24 PdfGridRow row1 = grid.Rows.Add(); 25 PdfGridRow row2 = grid.Rows.Add(); 26 PdfGridRow row3 = grid.Rows.Add(); 27 PdfGridRow row4 = grid.Rows.Add(); 28 PdfGridRow row5 = grid.Rows.Add(); 29 grid.Columns.Add(6); 30 31 //设置列宽 32 foreach (PdfGridColumn col in grid.Columns) 33 { 34 col.Width = 55f; 35 } 36 37 //写入数据 38 row1.Cells[0].Value = "新入职员工基本信息"; 39 row2.Cells[0].Value = "入职时间"; 40 row2.Cells[1].Value = "姓名"; 41 row2.Cells[2].Value = "部门"; 42 row2.Cells[3].Value = "学历"; 43 row2.Cells[4].Value = "联系电话"; 44 row2.Cells[5].Value = "正式员工"; 45 46 row3.Cells[0].Value = "3月"; 47 row3.Cells[1].Value = "马超"; 48 row3.Cells[2].Value = "研发部"; 49 row3.Cells[3].Value = "硕士"; 50 row3.Cells[4].Value = "153****6543"; 51 row3.Cells[5].Value = "是"; 52 53 row4.Cells[0].Value = "4月"; 54 row4.Cells[1].Value = "刘陵"; 55 row4.Cells[2].Value = "研发部"; 56 row4.Cells[3].Value = "本科"; 57 row4.Cells[4].Value = "176****5464"; 58 row4.Cells[5].Value = "是"; 59 60 row5.Cells[0].Value = "4月"; 61 row5.Cells[1].Value = "张丽"; 62 row5.Cells[2].Value = "研发部"; 63 row5.Cells[3].Value = "本科"; 64 row5.Cells[4].Value = "158****4103"; 65 row5.Cells[5].Value = "是"; 66 67 //水平和垂直方向合并单元格 68 row1.Cells[0].ColumnSpan = 6; 69 row4.Cells[0].RowSpan = 2; 70 row3.Cells[2].RowSpan = 3; 71 row4.Cells[3].RowSpan = 2; 72 73 //设置单元格内文字对齐方式 74 PdfTable table = new PdfTable(); 75 row1.Cells[0].StringFormat = new PdfStringFormat(PdfTextAlignment.Center); 76 row4.Cells[0].StringFormat = new PdfStringFormat(PdfTextAlignment.Justify, PdfVerticalAlignment.Middle); 77 row3.Cells[2].StringFormat = new PdfStringFormat(PdfTextAlignment.Justify, PdfVerticalAlignment.Middle); 78 row4.Cells[3].StringFormat = new PdfStringFormat(PdfTextAlignment.Justify, PdfVerticalAlignment.Middle); 79 80 //设置单元格背景颜色 81 row1.Cells[0].Style.BackgroundBrush = PdfBrushes.LightGreen; 82 83 //设置表格边框颜色、粗细 84 PdfBorders borders = new PdfBorders(); 85 borders.All = new PdfPen(Color.Black, 0.1f); 86 foreach (PdfGridRow pgr in grid.Rows) 87 { 88 foreach (PdfGridCell pgc in pgr.Cells) 89 { 90 pgc.Style.Borders = borders; 91 } 92 } 93 94 //在指定位置绘入表格 95 grid.Draw(page, new PointF(0, 40)); 96 97 //保存到文档 98 doc.SaveToFile("PDF表格.pdf"); 99 System.Diagnostics.Process.Start("PDF表格.pdf"); 100 } 101 } 102 } 效果展示: 以上是关于组件Free Spire.PDF for .NET用于在PDF 中创建表格的方法介绍,如对您有所帮助,欢迎转载(转载请注明出处)
在Excel中如果能够将具有多级明细的数据进行分组显示,可以清晰地展示数据表格的整体结构,使整个文档具有一定层次感。根据需要设置显示或者隐藏分类数据下的详细信息,在便于数据查看、管理的同时也使文档更具美观性。那么,在C#中如何来创建Excel数据的多级分组显示呢?下面将进行详细阐述。方法中使用了免费版组件Free Spire.XLS for .NET,下载安装该组件,创建一个控制台应用程序后,添加引用该组件安装包下的dll文件到项目中,同时添加相应的命名空间即可。下面是具体的代码操作步骤,供参考。 步骤一:创建一个Wordbook类对象,获取第一个工作表 Workbook workbook = new Workbook(); Worksheet sheet = workbook.Worksheets[0]; 步骤二:写入数据到单元格 sheet.Range["A1"].Value = "公司部门"; sheet.Range["A3"].Value = "综合部"; sheet.Range["A4"].Value = "行政"; sheet.Range["A5"].Value = "人事"; sheet.Range["A6"].Value = "市场部"; sheet.Range["A7"].Value = "业务部"; sheet.Range["A8"].Value = "客服部"; sheet.Range["A9"].Value = "技术部"; sheet.Range["A10"].Value = "技术开发"; sheet.Range["A11"].Value = "技术支持"; sheet.Range["A12"].Value = "售前支持"; sheet.Range["A13"].Value = "售后支持"; 步骤三:设置IsSummaryRowBelow属性为false, 即总结行显示在明细行上方 sheet.PageSetup.IsSummaryRowBelow = false; 步骤四:选择行进行分组,参数false表示展开当前分组,如需隐藏,设置成true //选择行进行一级分组 sheet.GroupByRows(2, 13, false); //选择行进行二级分组 sheet.GroupByRows(4,5 , false); sheet.GroupByRows(7, 8, false); sheet.GroupByRows(10,13 , false); //选择行进行三级分组 sheet.GroupByRows(12,13, true); 步骤五:定义一个CellStyle对象,设置并运用格式到单元格内字体 CellStyle style = workbook.Styles.Add("style"); style.Font.IsBold = true; style.Color = Color.LawnGreen; sheet.Range["A1"].CellStyleName = style.Name; sheet.Range["A3"].CellStyleName = style.Name; sheet.Range["A6"].CellStyleName = style.Name; sheet.Range["A9"].CellStyleName = style.Name; 步骤六:设置区域边框样式 sheet.Range["A4:A5"].BorderAround(LineStyleType.Thin); sheet.Range["A4:A5"].BorderInside(LineStyleType.Thin); sheet.Range["A7:A8"].BorderAround(LineStyleType.Thin); sheet.Range["A7:A8"].BorderInside(LineStyleType.Thin); sheet.Range["A10:A13"].BorderAround(LineStyleType.Thin); sheet.Range["A10:A13"].BorderInside(LineStyleType.Thin); 步骤七:保存文档 workbook.SaveToFile("output.xlsx", ExcelVersion.Version2013); 运行程序生成文档(可在该项目文件夹下bin>Debug文件夹下查看生成的文档) 效果展示: 全部代码: 1 using System; 2 using System.Drawing; 3 using Spire.Xls; 4 5 6 namespace MultilevelGroup_XLS 7 { 8 class Program 9 { 10 static void Main(string[] args) 11 { 12 //创建一个Wordbook类对象,获取第一个工作表 13 Workbook workbook = new Workbook(); 14 Worksheet sheet = workbook.Worksheets[0]; 15 16 //写入数据到单元格 17 sheet.Range["A1"].Value = "公司部门"; 18 sheet.Range["A3"].Value = "综合部"; 19 sheet.Range["A4"].Value = "行政"; 20 sheet.Range["A5"].Value = "人事"; 21 sheet.Range["A6"].Value = "市场部"; 22 sheet.Range["A7"].Value = "业务部"; 23 sheet.Range["A8"].Value = "客服部"; 24 sheet.Range["A9"].Value = "技术部"; 25 sheet.Range["A10"].Value = "技术开发"; 26 sheet.Range["A11"].Value = "技术支持"; 27 sheet.Range["A12"].Value = "售前支持"; 28 sheet.Range["A13"].Value = "售后支持"; 29 30 //设置IsSummaryRowBelow为false, 即总结行显示在明细行上方 31 sheet.PageSetup.IsSummaryRowBelow = false; 32 33 //选择行进行一级分组 34 //参数false表示展开当前分组,若要隐藏设置成true 35 sheet.GroupByRows(2, 13, false); 36 37 //选择行进行二级分组 38 sheet.GroupByRows(4,5 , false); 39 sheet.GroupByRows(7, 8, false); 40 sheet.GroupByRows(10,13 , false); 41 42 //选择行进行三级分组 43 sheet.GroupByRows(12,13, true); 44 45 //定义一个CellStyle对象,设置并运用单元格内字体格式 46 CellStyle style = workbook.Styles.Add("style"); 47 style.Font.IsBold = true; 48 style.Color = Color.LawnGreen; 49 sheet.Range["A1"].CellStyleName = style.Name; 50 sheet.Range["A3"].CellStyleName = style.Name; 51 sheet.Range["A6"].CellStyleName = style.Name; 52 sheet.Range["A9"].CellStyleName = style.Name; 53 54 //设置区域边框样式 55 sheet.Range["A4:A5"].BorderAround(LineStyleType.Thin); 56 sheet.Range["A4:A5"].BorderInside(LineStyleType.Thin); 57 sheet.Range["A7:A8"].BorderAround(LineStyleType.Thin); 58 sheet.Range["A7:A8"].BorderInside(LineStyleType.Thin); 59 sheet.Range["A10:A13"].BorderAround(LineStyleType.Thin); 60 sheet.Range["A10:A13"].BorderInside(LineStyleType.Thin); 61 62 63 //保存文档 64 workbook.SaveToFile("output.xlsx", ExcelVersion.Version2013); 65 System.Diagnostics.Process.Start("output.xlsx"); 66 } 67 } 68 } View Code 以上是关于设置Excel多级分组的全部操作步骤,如果对您有所帮助,欢迎转载(转载请注明出处)。 感谢阅读!
Excel表格中的迷你图表能够直观地向我们展示出数据的变化趋势。本文将介绍C#如何实现为表格数据生成迷你图表,以及修改和删除迷你图表的方法。下面将详细讲述。 所用组件工具:Spire.XLS for .NET 原Excel图表: 一、添加迷你图表(折线图、柱形图、盈亏图) 1.添加命名空间 using System; using Spire.Xls; using System.Drawing; 2.主要代码 //创建一个Workbook类对象并加载Excel文档 Workbook workbook = new Workbook(); workbook.LoadFromFile(@"C:\Users\Administrator\Desktop\Sample.xlsx"); //获取第一个工作表,在特定单元格添加文本并设置格式 Worksheet sheet = workbook.Worksheets[0]; sheet.Range["H2"].Text = "外贸进/出口额走势"; sheet.Range["H2"].Style.Font.FontName = "Arial Narrow"; sheet.Range["H2"].Style.Font.Color = Color.Black; sheet.Range["A1:H5"].Columns[7].ColumnWidth = 15F; sheet.Range["H2"].Style.Font.IsBold = true; sheet.Range["H2:H5"].BorderInside(LineStyleType.Thin); sheet.Range["H2:H5"].BorderAround(LineStyleType.Thin); //添加折线迷你图 SparklineGroup sparklineGroup1 = sheet.SparklineGroups.AddGroup(); sparklineGroup1.SparklineType = SparklineType.Line; //设置折折线迷你图格式 sparklineGroup1.SparklineColor = Color.Tomato; sparklineGroup1.HighPointColor = Color.Red; //设置添加折现迷你图表的单元格以及图表生成的数据范围 SparklineCollection sparklines1 = sparklineGroup1.Add(); sparklines1.Add(sheet["B3:G3"], sheet["H3"]); //添加柱形迷你图并设置图表颜色 SparklineGroup sparklineGroup2 = sheet.SparklineGroups.AddGroup(); sparklineGroup2.SparklineType = SparklineType.Column; sparklineGroup2.SparklineColor = Color.PaleGreen; sparklineGroup2.HighPointColor = Color.SeaGreen; //设置添加柱形迷你图表的单元格以及图表生成的数据范围 SparklineCollection sparklines2 = sparklineGroup2.Add(); sparklines2.Add(sheet["B4:G4"], sheet["H4"]);//添加盈亏迷你图并设置颜色 SparklineGroup sparklineGroup3 = sheet.SparklineGroups.AddGroup(); sparklineGroup3.SparklineType = SparklineType.Stacked; sparklineGroup3.SparklineColor = Color.SkyBlue; sparklineGroup3.HighPointColor = Color.Blue; //设置盈亏迷你图表的单元格以及图表生成的数据范围 SparklineCollection sparklines3 = sparklineGroup3.Add(); sparklines3.Add(sheet["B5:G5"], sheet["H5"]); //保存文档 workbook.SaveToFile("添加迷你图.xlsx", ExcelVersion.Version2010); 调试运行项目程序,生成文件 二、修改迷你图(图表类型/数据范围) 1.添加命名空间 using System; using Spire.Xls; using Spire.Xls.Core.Spreadsheet; 2.主要代码 //实例化一个Workbook类,加载Excel文档 Workbook workbook = new Workbook(); workbook.LoadFromFile("添加迷你图.xlsx"); //获取第一个工作表 Worksheet sheet = workbook.Worksheets[0];//修改第一个迷你图组中迷你图表类型和数据范围 ISparklineGroup sparklineGroup = sheet.SparklineGroups[0]; sparklineGroup.SparklineType = SparklineType.Column; ISparklines sparklines = sparklineGroup[0]; sparklines.RefreshRanges(sheet.Range["C3:G3"], sheet.Range["H3"]); //保存文档 workbook.SaveToFile("修改迷你图.xlsx", ExcelVersion.Version2010); 三、删除迷你图表 1.添加命名空间 using System; using Spire.Xls; using Spire.Xls.Core.Spreadsheet; 2.主要代码 //实例化一个Workbook类,加载Excel文档 Workbook workbook = new Workbook(); workbook.LoadFromFile("添加迷你图.xlsx"); //获取第一个工作表 Worksheet sheet = workbook.Worksheets[0]; //获取第2个迷你图 ISparklineGroup sparklineGroup = sheet.SparklineGroups[1]; //从工作表中删除图表 sheet.SparklineGroups.Remove(sparklineGroup); //保存文件 workbook.SaveToFile("删除迷你图.xlsx", ExcelVersion.Version2010); 以上全部内容为本次关于Excel迷你图表生成、修改和删除的全部操作,希望对你有所帮助。如果觉得不错,欢迎转载(转载请注明出处)。 感谢浏览。
数据表格能够清晰的呈现数据信息,但是我们对于一些繁杂多变的数据想要很直观的看到数据变化走势或者数据的占比时,数据图表会更具代表性,并且在呈现数据信息上也更形象,也能获取更多纯数字信息所不能直接展现的信息。在下面的代码中,将向您展示如何通过使用免费的Free Spire XLS for .NET组件来实现。 原数据表格: C# 1 using Spire.Xls; 2 using System.Drawing; 3 using System.Drawing.Imaging; 4 5 namespace CreateChart_XLS 6 { 7 class Program 8 { 9 static void Main(string[] args) 10 { 11 //创建一个Workbook类实例,加载Excel文档 12 Workbook workbook = new Workbook(); 13 workbook.LoadFromFile(@"C:\Users\Administrator\Desktop\Sample.xlsx"); 14 15 //获取第一个工作表 16 Worksheet sheet = workbook.Worksheets[0]; 17 18 //设置工作表的名称 19 sheet.Name = "柱状图"; 20 sheet.GridLinesVisible = false; 21 22 //创建柱状图 23 Chart chart = sheet.Charts.Add(ExcelChartType.ColumnClustered); 24 25 //指定用于生成图表的数据区域 26 chart.DataRange = sheet.Range["A2:G6"]; 27 chart.SeriesDataFromRange = false; 28 29 //指定图表所在的位置 30 chart.LeftColumn = 1; 31 chart.TopRow = 9; 32 chart.RightColumn = 12; 33 chart.BottomRow = 26; 34 35 //设置图表的名称及字体格式 36 chart.ChartTitle = "上半年产品销售情况(单位:万美元)"; 37 chart.ChartTitleArea.IsBold = true; 38 chart.ChartTitleArea.Size = 12; 39 40 //设置X轴坐标名称及字体格式 41 chart.PrimaryCategoryAxis.Title = "产品类别"; 42 chart.PrimaryCategoryAxis.Font.IsBold = true; 43 chart.PrimaryCategoryAxis.TitleArea.IsBold = false; 44 45 //设置Y轴坐标名称及字体格式 46 chart.PrimaryValueAxis.Title = "销售额"; 47 chart.PrimaryValueAxis.HasMajorGridLines = false; 48 chart.PrimaryValueAxis.TitleArea.TextRotationAngle = 90; 49 chart.PrimaryValueAxis.MinValue = 0.5; 50 chart.PrimaryValueAxis.TitleArea.IsBold = false; 51 52 //设置图例的位置 53 chart.Legend.Position = LegendPositionType.Right; 54 55 //保存文档 56 workbook.SaveToFile("ColumnChart.xlsx", ExcelVersion.Version2013); 57 58 59 //加载生成图表后的Excel文档 60 workbook.LoadFromFile("ColumnChart.xlsx"); 61 62 //遍历工作簿,诊断是否包含图表 63 Image[] images = workbook.SaveChartAsImage(sheet); 64 65 for (int i = 0; i < images.Length; i++) 66 { 67 //将图表保存为图片 68 images[i].Save(string.Format("img-{0}.png", i), ImageFormat.Png); 69 } 70 } 71 } 72 } 生成的图表文件及图片如下图所示: 组件获取地址:https://www.e-iceblue.cn/Downloads/Free-Spire-XLS-NET.html 以上是对Excel数据表格生成并转化为图表的全部操作,希望对你有所帮助,欢迎转载(转载请注明出处) 感谢浏览!
文档中包含图片的话,会使得整个文档比较大,占用存储空间且不利于快速、高效的传输文件。针对一些包含大量高质图片的PDF文档,若是对图片进行压缩,可以有效减少文档的占用空间。并且,在文档传输过程中也可以减少传送时间,提高效率。本文将介绍2种通过C#来实现PDF图片文档压缩的方法。使用此方法,需要用到最新版本组件Spire.PDF for .NET3.9.462。下面是通过C#代码来压缩图片,从而实现整个PDF文档压缩的方法。 提示:编辑代码前,需要安装该组件,并添加引用dll文件到项目程序中,同时添加指令。 方法一 using Spire.Pdf; using System.Drawing; using Spire.Pdf.Graphics; using Spire.Pdf.Exporting; namespace CompressImage_PDF { class Program { static void Main(string[] args) { //初始化一个PdfDocument类实例并加载一个pdf文档 PdfDocument doc = new PdfDocument(@"C:\Users\Administrator\Desktop\Input.pdf"); //禁用增量更新 doc.FileInfo.IncrementalUpdate = false; //遍历PDF所有页,诊断页面是否含有图片 foreach (PdfPageBase page in doc.Pages) { if (page != null) { if (page.ImagesInfo != null) { foreach (PdfImageInfo info in page.ImagesInfo) { //调用方法TryCompressImage()压缩图片 page.TryCompressImage(info.Index); } } } } //保存文档 doc.SaveToFile("Output.pdf"); } } } 方法二 using Spire.Pdf; using System.Drawing; using Spire.Pdf.Graphics; namespace CompressImage_PDF { class Program { static void Main(string[] args) { //初始化一个PdfDocument类实例并加载一个pdf文档 PdfDocument doc = new PdfDocument(@"C:\Users\Administrator\Desktop\Input.pdf"); //禁用增量更新 doc.FileInfo.IncrementalUpdate = false; //遍历所有PDF页,提取图片 foreach (PdfPageBase page in doc.Pages) { Image[] images = page.ExtractImages(); //遍历所有图片 if (images != null && images.Length > 0) { for (int j = 0; j < images.Length; j++) { Image image = images[j]; PdfBitmap bp = new PdfBitmap(image); //设置bp.Quality值,压缩图片 bp.Quality = 20; //将压缩后的图片替换原有图片 page.ReplaceImage(j, bp); } } } //保存文档 doc.SaveToFile("Output2.pdf"); } } } 针对包含大量高质图片的PDF文档,以上方法可以有效压缩文档,并且不会出现市面上压缩软件在压缩文档时存在的广告水印或者破坏源文档的情况。方法介绍到此,如果对您有用,欢迎转载(转载请注明出处)。 (本文完)
工作中我们会使用到各种各样的文档,其中,PPT起着不可或缺的作用。一份PPT文档里可能包含重要商业计划、企业运营资料或者公司管理资料等。因此,在竞争环境里,企业重要资料的保密工作就显得尤为重要,而对于重要资料我们可以选择添加密码的形式来进行文档保护。本文将介绍如何通过C#来给PPT添加密码,当然你也可以根据需要来修改密码或者解除密码。下面将对三种操作方法进行具体讲述。 所用工具:Spire.Presentation for. NET Visual Studio 2013 工具使用说明:Spire.Presentation for .NET支持生成、写入、修改、转换、打印PPT等操作,这里我使用的是免费版的,使用前需要下载并安装,完成后需要添加引用dll文件到程序集中,同时也需添加using指令。 1.添加密码 1 using Spire.Presentation; 2 3 namespace Security_PPT 4 { 5 class Program 6 { 7 static void Main(string[] args) 8 { 9 //新建一个Presentation类实例,并加载需要加密的文档 10 Presentation presentation = new Presentation(); 11 presentation.LoadFromFile(@"C:\Users\Administrator\Desktop\test.pptx"); 12 //加密文件,设置打开密码并保存文档 13 presentation.Encrypt("test"); 14 presentation.SaveToFile("encrypt.pptx", FileFormat.Pptx2007); 15 } 16 } 17 } 调试运行项目生成文件,如下图 打开文件,此时需要嵌入密码,正确输入密码后即可打开文档。 2.重置密码 1 using Spire.Presentation; 2 3 namespace ResetPassword_PPT 4 { 5 class Program 6 { 7 static void Main(string[] args) 8 { 9 //创建一个Presentation类实例并加载已加密的文档 10 Presentation presentation = new Presentation(); 11 presentation.LoadFromFile(@"C:\Users\Administrator\Desktop\encrypt.pptx", FileFormat.Pptx2010, "test"); 12 13 //解除原有密码,添加新密码 14 presentation.RemoveEncryption(); 15 presentation.Protect("newtest"); 16 17 //保存文档 18 presentation.SaveToFile("newresult.pptx", FileFormat.Pptx2010); 19 20 } 21 } 22 } 同样的,调试运行程序生成文件 打开后输入新密码,这里可以选择可修改或者以只读方式查看文件 3.解除密码 上面描述的修改密码的方法中,若只是想解除密码而不新设置密码的话,只需删除掉添加新密码,即 presentation.Protect("newtest")这一行代码,调试运行后,生成的文档就没有密码保护了。 以上是对PPT文档进行加密、解密以及重设密码的操作,希望对你有所帮助。如果对你有用,欢迎转载(转载请注明出处)。 感谢浏览!
表格是组织整理数据的一种重要手段,应在生活中的方方面面。在Word文档中将繁杂的文字表述内容表格化,能快速、直接地获取关键内容信息。那么,通过C#,我们也可以在Word文档中添加表格,这里将介绍两种不同的表格添加方法。 使用工具:Spire.Doc for .NET 使用方法:安装后,添加引用dll文件到项目中即可 表格添加方法一:动态地向Word添加表格行和单元格内容,需调用方法section. AddTable()、table. AddRow和row. AddCell() 1 using System; 2 using Spire.Doc; 3 using Spire.Doc.Documents; 4 using Spire.Doc.Fields; 5 using System.Drawing; 6 7 8 namespace CreateTable_Doc 9 { 10 class Program 11 { 12 static void Main(string[] args) 13 { 14 //创建一个Document类实例,并添加section 15 Document doc = new Document(); 16 Section section = doc.AddSection(); 17 18 //添加表格 19 Table table = section.AddTable(true); 20 21 //添加表格第1行 22 TableRow row1 = table.AddRow(); 23 24 //添加第1个单元格到第1行 25 TableCell cell1 = row1.AddCell(); 26 cell1.AddParagraph().AppendText("序列号"); 27 28 //添加第2个单元格到第1行 29 TableCell cell2 = row1.AddCell(); 30 cell2.AddParagraph().AppendText("设备名称"); 31 32 //添加第3个单元格到第1行 33 TableCell cell3 = row1.AddCell(); 34 cell3.AddParagraph().AppendText("设备型号"); 35 36 //添加第4个单元格到第1行 37 TableCell cell4 = row1.AddCell(); 38 cell4.AddParagraph().AppendText("设备数量"); 39 40 //添加第5个单元格到第1行 41 TableCell cell5 = row1.AddCell(); 42 cell5.AddParagraph().AppendText("设备价格"); 43 44 45 //添加表格第2行 46 TableRow row2 = table.AddRow(true, false); 47 48 //添加第6个单元格到第2行 49 TableCell cell6 = row2.AddCell(); 50 cell6.AddParagraph().AppendText("1"); 51 52 //添加第7个单元格到第2行 53 TableCell cell7 = row2.AddCell(); 54 cell7.AddParagraph().AppendText("机床"); 55 56 //添加第8个单元格到第2行 57 TableCell cell8 = row2.AddCell(); 58 cell8.AddParagraph().AppendText("M170010"); 59 60 //添加第9个单元格到第2行 61 TableCell cell9 = row2.AddCell(); 62 cell9.AddParagraph().AppendText("12"); 63 64 //添加第10个单元格到第2行 65 TableCell cell10 = row2.AddCell(); 66 cell10.AddParagraph().AppendText("8W"); 67 table.AutoFitBehavior(AutoFitBehaviorType.wdAutoFitWindow); 68 69 //保存文档 70 doc.SaveToFile("Table.docx"); 71 } 72 } 73 } View Code 表格添加方法二:预定义表格行和列 1 using System; 2 using Spire.Doc; 3 using Spire.Doc.Fields; 4 using System.Drawing; 5 6 namespace CreateTable2_Word 7 { 8 class Program 9 { 10 static void Main(string[] args) 11 { 12 //创建一个Document类实例,并添加section 13 Document document = new Document(); 14 Section section = document.AddSection(); 15 16 //添加表格指定表格的行数和列数(2行,5列) 17 Table table = section.AddTable(true); 18 table.ResetCells(2, 5); 19 20 //获取单元格(第1行第1个单元格)并添加文本内容,设置字体字号颜色等(单元格中内容及个性化设置可以根据需要来进行调整) 21 TextRange range = table[0, 0].AddParagraph().AppendText("序列号"); 22 range.CharacterFormat.FontName = "Arial"; 23 range.CharacterFormat.FontSize = 12; 24 range.CharacterFormat.TextColor = Color.Brown; 25 range.CharacterFormat.Bold = true; 26 27 //获取单元格(第1行第2个单元格)并添加文本 28 range = table[0, 1].AddParagraph().AppendText("设备名称"); 29 range.CharacterFormat.FontName = "Arial"; 30 range.CharacterFormat.FontSize = 12; 31 range.CharacterFormat.TextColor = Color.Brown; 32 range.CharacterFormat.Bold = true; 33 34 //获取单元格(第1行第3个单元格)并添加文本 35 range = table[0, 2].AddParagraph().AppendText("设备型号"); 36 range.CharacterFormat.FontName = "Arial"; 37 range.CharacterFormat.FontSize = 12; 38 range.CharacterFormat.TextColor = Color.Brown; 39 range.CharacterFormat.Bold = true; 40 41 //获取单元格(第1行第4个单元格)并添加文本 42 range = table[0, 3].AddParagraph().AppendText("设备数量"); 43 range.CharacterFormat.FontName = "Arial"; 44 range.CharacterFormat.FontSize = 12; 45 range.CharacterFormat.TextColor = Color.Brown; 46 range.CharacterFormat.Bold = true; 47 48 //获取单元格(第1行第5个单元格)并添加文本 49 range = table[0, 4].AddParagraph().AppendText("设备价格"); 50 range.CharacterFormat.FontName = "Arial"; 51 range.CharacterFormat.FontSize = 12; 52 range.CharacterFormat.TextColor = Color.Brown; 53 range.CharacterFormat.Bold = true; 54 55 //获取单元格(第2行第1个单元格)并添加文本 56 range = table[1, 0].AddParagraph().AppendText("1"); 57 range.CharacterFormat.FontName = "Arial"; 58 range.CharacterFormat.FontSize = 12; 59 60 //获取单元格(第2行第2个单元格)并添加文本 61 range = table[1, 1].AddParagraph().AppendText("机床"); 62 range.CharacterFormat.FontName = "Arial"; 63 range.CharacterFormat.FontSize = 12; 64 65 //获取单元格(第2行第3个单元格)并添加文本 66 range = table[1, 2].AddParagraph().AppendText("M170010"); 67 range.CharacterFormat.FontName = "Arial"; 68 range.CharacterFormat.FontSize = 12; 69 70 //获取单元格(第2行第4个单元格)并添加文本 71 range = table[1, 3].AddParagraph().AppendText("12"); 72 range.CharacterFormat.FontName = "Arial"; 73 range.CharacterFormat.FontSize = 12; 74 75 //获取单元格(第2行第5个单元格)并添加文本 76 range = table[1, 4].AddParagraph().AppendText("8W"); 77 range.CharacterFormat.FontName = "Arial"; 78 range.CharacterFormat.FontSize = 12; 79 80 //保存文档 81 document.SaveToFile("Table2.docx"); 82 } 83 } 84 } View Code 以上两种方法中,鉴于文章篇幅,示例中只添加了比较简单的表格,在实际运用中,你可以根据自己的需要添加内容或者设置内容格式等。如果觉得对你有用的话,欢迎转载! 感谢阅读。
提取文本的情况在工作和学习中常会遇到,在前面的文章中,已经讲述了如何提取PPT中文本框里的文本,在本篇文章中,将介绍如何使用C#代码语言提取PPT文档中SmartArt和批注中的文本。同样的,程序里面需要使用到Spire.Presentation for .NET,在编写代码前,需先安装,并添引用dll文件到项目程序中。 1.提取SmartArt中的文本 测试文件如下(在第二张幻灯片中插入了SmartArt图形,包含文本内容) 【C#】 1 using Spire.Presentation.Diagrams; 2 using System.Drawing; 3 using System.Text; 4 using System.IO; 5 using Spire.Presentation; 6 7 namespace ExtractTextFromSmartArt_PPT 8 { 9 class Program 10 { 11 static void Main(string[] args) 12 { 13 //初始化一个Presentation类实例,并加载文档 14 Presentation ppt = new Presentation(); 15 ppt.LoadFromFile(@"C:\Users\Administrator\Desktop\Sample.pptx"); 16 //新建一个StringBuilder对象 17 StringBuilder st = new StringBuilder(); 18 //遍历文档中的SmartArt图形 19 for (int i = 0; i < ppt.Slides.Count; i++) 20 { 21 for (int j = 0; j < ppt.Slides[i].Shapes.Count; j++) 22 { 23 if (ppt.Slides[i].Shapes[j] is ISmartArt) 24 { 25 ISmartArt smartArt = ppt.Slides[i].Shapes[j] as ISmartArt; 26 for (int k = 0; k < smartArt.Nodes.Count; k++) 27 { 28 st.Append(smartArt.Nodes[k].TextFrame.Text); 29 } 30 } 31 } 32 } 33 //将文本写入TXT文档 34 File.WriteAllText("Result.txt", st.ToString()); 35 } 36 } 37 } 提取的文本如下图所示: 2.提取批注中文本 测试文件如下(在第一张幻灯片中,插入了批注,包含文本内容) 【C#】 1 using System; 2 using System.Text; 3 using Spire.Presentation; 4 using System.IO; 5 6 namespace ExtractTextFromComment_PPT 7 { 8 class Program 9 { 10 static void Main(string[] args) 11 { 12 //实例化一个Presentation类,并加载文档 13 Presentation ppt = new Presentation(); 14 ppt.LoadFromFile(@"C:\Users\Administrator\Desktop\comment.pptx"); 15 //创建一个StringBuilder对象 16 StringBuilder str = new StringBuilder(); 17 //获取第一张幻灯片中的所有批注 18 Comment[] comments = ppt.Slides[0].Comments; 19 //遍历批注内容 20 for (int i = 0; i < comments.Length; i++) 21 { 22 str.Append(comments[i].Text + "\r\n"); 23 } 24 //将文本写入TXT文档 25 File.WriteAllText("TextFromComment.txt", str.ToString()); 26 } 27 } 28 } 调试运行程序后,生成文档,如下: 以上方法是提取PPT SmartArt和批注中文本的实现方法,供参考,希望能对您有所帮助,感谢阅读! (本文完)
在图文混排的文档中,我们可以根据需要将文档中的文字信息或者图片提取出来,通过C#代码可以提取Word和PDF文件中的文本和图片,那么同样的,我们也可以提取PPT幻灯片当中的文本和图片。本篇文档将讲述如何使用C#来实现提取PPT文本和图片的操作。首先也是需要安装组件Spire.Presentation,然后添加引用dll文件到项目中。下面是主要的代码步骤。 原文档: 1. 提取文本 步骤一:创建一个Presentation实例并加载文档 Presentation presentation = new Presentation(@"C:\Users\Administrator\Desktop\sample.pptx", FileFormat.Pptx2010); 步骤二:创建一个StringBuilder对象 StringBuilder sb = new StringBuilder(); 步骤三:遍历幻灯片及幻灯片中的图形,提取文本内容 foreach (ISlide slide in presentation.Slides) { foreach (IShape shape in slide.Shapes) { if (shape is IAutoShape) { foreach (TextParagraph tp in (shape as IAutoShape).TextFrame.Paragraphs) { sb.Append(tp.Text + Environment.NewLine); } } } } 步骤四:写入Txt文档 File.WriteAllText("target.txt", sb.ToString()); Process.Start("target.txt"); 2. 提取图片 这里提取图片有两种情况,一种是提取整个文档中的所有图片,另外一种是只提取文档中某一特定幻灯片中的图片。 2.1提取所有图片 步骤一:初始化一个Presentation类实例,并加载文档 Presentation ppt = new Presentation(); ppt.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.pptx"); 步骤二:遍历文档中图片,提取图片并保存 for (int i = 0; i < ppt.Images.Count; i++) { Image image = ppt.Images[i].Image; image.Save(string.Format(@"..\..\Images{0}.png", i)); } 提取的图片已保存到项目文件夹下 2.2.提取特定幻灯片中的图片 步骤一:创建一个Presentation类实例,并加载文档 Presentation PPT = new Presentation(); PPT.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.pptx"); 步骤二:获取第三张幻灯片,提取并保存图片 int i = 0; foreach (IShape s in PPT.Slides[2].Shapes) { if (s is SlidePicture) { SlidePicture ps = s as SlidePicture; ps.PictureFill.Picture.EmbedImage.Image.Save(string.Format("{0}.png", i)); i++; } if (s is PictureShape) { PictureShape ps = s as PictureShape; ps.EmbedImage.Image.Save(string.Format("{0}.png", i)); i++; } } 提取的第三张幻灯片中的图片已保存至指定位置 上文演示了如何提取文本和图片,步骤比较简单实用,希望对你有所帮助,感谢阅读! 如需转载请注明出处。
对文档添加水印可以有效声明和保护文档,是保护重要文件的方式之一。在PPT文档中同样也可以设置水印,包括文本水印和图片水印,本文将讲述如何通过Spire.Presentation for .NET来对PPT添加水印,下载安装Free Spire.Presentationfor .NET后,添加引用dll文件,参考下面的操作步骤,完成水印添加。 1.添加文本水印 步骤一:初始化Presentation类实例,并加载文档 Presentation ppt = new Presentation(); ppt.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.pptx", FileFormat.Pptx2010); 步骤二:初始化一个Font类实例,并实例化字体格式 Font stringFont = new Font("Arial", 90); Size size = TextRenderer.MeasureText("内部资料", stringFont); 步骤三:绘制一个shape并指定大小、填充颜色、边框颜色和旋转角度 RectangleF rect = new RectangleF((ppt.SlideSize.Size.Width - size.Width) / 2, (ppt.SlideSize.Size.Height - size.Height) / 2, size.Width, size.Height); IAutoShape shape = ppt.Slides[0].Shapes.AppendShape(Spire.Presentation.ShapeType.Rectangle, rect); shape.Fill.FillType = FillFormatType.None; shape.ShapeStyle.LineColor.Color = Color.White; shape.Rotation = -45; 步骤四:设定形状属性为保护属性 shape.Locking.SelectionProtection = true; shape.Line.FillType = FillFormatType.None; 步骤五:设置文本大小、颜色 shape.TextFrame.Text = "内部资料"; TextRange textRange = shape.TextFrame.TextRange; textRange.Fill.FillType = Spire.Presentation.Drawing.FillFormatType.Solid; textRange.Fill.SolidColor.Color = Color.FromArgb(120, Color.Gray); textRange.FontHeight = 45; 步骤六:保存文档 ppt.SaveToFile("TextWatermark.pptx", FileFormat.Pptx2010); 完成以上代码步骤后,调试运行项目程序,生成文件(可在该项目文件中bin>Debug中查看),如下图所示: 全部代码: using System; using System.Text; using Spire.Presentation; using System.Drawing; using Spire.Presentation.Drawing; using System.Windows.Forms; namespace InsertWatermark_PPT { class Program { static void Main(string[] args) { //初始化一个Presentation类实例并加载文档 Presentation ppt = new Presentation(); ppt.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.pptx", FileFormat.Pptx2010); //初始化一个Font类字体实例并实例化字体格式 Font stringFont = new Font("Arial", 90); Size size = TextRenderer.MeasureText("内部资料", stringFont); //绘制一个Shape并指定大小、填充颜色、边框颜色和旋转度 RectangleF rect = new RectangleF((ppt.SlideSize.Size.Width - size.Width) / 2, (ppt.SlideSize.Size.Height - size.Height) / 2, size.Width, size.Height); IAutoShape shape = ppt.Slides[0].Shapes.AppendShape(Spire.Presentation.ShapeType.Rectangle, rect); shape.Fill.FillType = FillFormatType.None; shape.ShapeStyle.LineColor.Color = Color.White; shape.Rotation = -45; //设定形状属性为保护属性 shape.Locking.SelectionProtection = true; shape.Line.FillType = FillFormatType.None; //设置文本大小、颜色 shape.TextFrame.Text = "内部资料"; TextRange textRange = shape.TextFrame.TextRange; textRange.Fill.FillType = Spire.Presentation.Drawing.FillFormatType.Solid; textRange.Fill.SolidColor.Color = Color.FromArgb(150, Color.LightBlue); textRange.FontHeight = 90; //保存文档 ppt.SaveToFile("TextWatermark.pptx", FileFormat.Pptx2010); } } View full Code 2.添加图片水印 步骤一:初始化一个Presentation类实例并加载文档 Presentation ppt = new Presentation(); ppt.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.pptx", FileFormat.Pptx2010); 步骤二: 为第一张幻灯片设置背景图片类型和样式 ppt.Slides[0].SlideBackground.Type = Spire.Presentation.Drawing.BackgroundType.Custom; ppt.Slides[0].SlideBackground.Fill.FillType = FillFormatType.Picture; ppt.Slides[0].SlideBackground.Fill.PictureFill.FillType = PictureFillType.Stretch; 步骤三:加载图片并为第一张幻灯片设置水印 Image img = Image.FromFile(@"C:\Users\Administrator\Desktop\images\1.jpg"); IImageData image = ppt.Images.Append(img); ppt.Slides[0].SlideBackground.Fill.PictureFill.Picture.EmbedImage = image; 步骤四:保存文档 ppt.SaveToFile("ImageWatermark1.pptx", FileFormat.Pptx2010); 全部代码: using System; using System.Drawing; using Spire.Presentation; using Spire.Presentation.Drawing; namespace ImageWatermark_PPT { class Program { static void Main(string[] args) { //初始化一个Presentation类实例并加载文档 Presentation ppt = new Presentation(); ppt.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.pptx", FileFormat.Pptx2010); //为第一张幻灯片设置背景图片类型和样式 ppt.Slides[0].SlideBackground.Type = Spire.Presentation.Drawing.BackgroundType.Custom; ppt.Slides[0].SlideBackground.Fill.FillType = FillFormatType.Picture; ppt.Slides[0].SlideBackground.Fill.PictureFill.FillType = PictureFillType.Stretch; //加载图片并为第一张幻灯片设置水印效果 Image img = Image.FromFile(@"C:\Users\Administrator\Desktop\images\1.jpg"); IImageData image = ppt.Images.Append(img); ppt.Slides[0].SlideBackground.Fill.PictureFill.Picture.EmbedImage = image; //保存文档 ppt.SaveToFile("ImageWatermark1.pptx", FileFormat.Pptx2010); } } } View full Code 以上是对PPT添加水印的代码操作,希望该方法能提供帮助,感谢阅读!
高亮的文本有助于阅读者快速有效地获取文章关键信息。在PDF文件中,对文章的不同文本,关键词、句等进行不同颜色的文本高亮操作,可以使阅读者在阅读过程中有效地区分不同高亮颜色文本的意义。在下面的示例中,我使用Free Spire.PDF for .NET来进行操作(https://www.e-iceblue.cn/Downloads/Free-Spire-Doc-NET.html),可以参考以下步骤: 原文件如下: 步骤一:初始化并加载一个PDF文档实例 PdfDocument pdf = new PdfDocument(@"C:\Users\Administrator\Desktop\C#.pdf"); 步骤二:调用FindText()方法,查找指定文本“C#” PdfTextFind[] result1 = null; result1 = pdf.Pages[0].FindText("C#").Finds; 步骤三;遍历所有查找结果,以蓝色高亮文本“C#” foreach (PdfTextFind find in result1) { find.ApplyHighLight(Color.Blue); } 步骤四:调用FindText()方法,查找指定文本“微软” PdfTextFind[] result2 = null; result2 = pdf.Pages[0].FindText("微软").Finds; 步骤五:遍历所有查找结果,以紫色高亮文本“微软” foreach (PdfTextFind find in result2) { find.ApplyHighLight(Color.Purple) } 步骤六:保存文档 pdf.SaveToFile("result.pdf", FileFormat.PDF); 完成以上操作后,调试运行该项目,生成文档(可在该项目中文件夹bin>Debug中查看)如下图: 以上是关于C#在PDF中文本查找及高亮的简单操作,希望对你有所帮助,感谢阅读!
超链接简单来讲就是内容链接,通过设置超链接可以实现对象与网页、站点之间的连接。链接目标可以是网页、图片、邮件地址、文件夹或者是应用程序。设置链接的对象可以是文本或者图片。 在以下内容中,我将介绍如何用C#编程语言对Word文档中的文本和图片进行超链接设置。执行该操作需要使用免费版组件Spire.Doc for. NET,可在这里下载安装(https://www.e-iceblue.cn/Downloads/Free-Spire-Doc-NET.html) 1.添加文本超链接 步骤一:创建一个Document实例并添加Section Document doc = new Document(); Section section = doc.AddSection(); 步骤二:添加指向网址的超链接 Paragraph para1 = section.AddParagraph(); para1.AppendHyperlink("www.google.com","www.google.com",HyperlinkType.WebLink); 步骤三:添加指向邮件地址的超链接 Paragraph para2 = section.AddParagraph(); para2.AppendHyperlink("mailto:support@e-iceblue.com", "support@e-iceblue.com", HyperlinkType.EMailLink); 步骤四:添加指向外部文件的超链接 Paragraph para3 = section.AddParagraph(); string filePath = @"C:\Users\Administrator\Desktop\2017NobelPrize.docx"; para3.AppendHyperlink(filePath, "点击打开文档", HyperlinkType.FileLink); 步骤五:设置段落之间的间距 para1.Format.AfterSpacing = 15f; para2.Format.AfterSpacing = 15f; 步骤六:保存文档 doc.SaveToFile("文本超链接.docx", FileFormat.Docx2013); 完成操作步骤后,运行该项目生成文件,如下图所示: 2、添加图片超链接 步骤一:创建一个Document实例并添加Section Document doc = new Document(); Section section = doc.AddSection(); 步骤二:添加段落 Paragraph para = section.AddParagraph(); 步骤三:添加图片到段落并添加网站超链接 Image image = Image.FromFile(@"C:\Users\Administrator\Desktop\images\Google.jpg"); Spire.Doc.Fields.DocPicture picture = para.AppendPicture(image); para.AppendHyperlink("www.google.com", picture, HyperlinkType.WebLink); 步骤四:保存文档 doc.SaveToFile("图片超链接.docx", FileFormat.Docx2013); 完成操作步骤,运行程序得到如下文件: 以上是利用C#编程语言对如何添加文本及图片超链接的代码操作演示,希望上述方法对你有所帮助,感谢阅读!
现代学习和办公当中,经常会接触到对表格的运用,像各种单据、报表、账户等等。在PPT演示文稿中同样不可避免的应用到各种数据表格。对于在PPT中插入表格,我发现了一个新方法,不过我用到了一款免费的.NET组件——Free Spire.Presentation,在C#中添加该产品DLL文件,可以简单快速地实现对演示文稿的表格插入、编辑和删除等操作。有需要的话可以在下面的网址下载:https://www.e-iceblue.cn/Downloads/Free-Spire-Presentation-NET.html 1.插入表格 步骤一:创建一个PowerPoint文档 Presentation ppt = new Presentation(); ppt.SlideSize.Type = SlideSizeType.Screen16x9; 步骤二:初始化一个ITable实例,并指定位置、行数和列数、行高和列宽 double[] widths = new double[] { 100, 100, 100, 100, 100 }; double[] heights = new double[] { 15, 15, 15, 15, 15 }; ITable table = ppt.Slides[0].Shapes.AppendTable(80, 80, widths, heights); 步骤三:为表格设置内置格式 table.StylePreset = TableStylePreset.LightStyle1Accent2; 步骤四:声明并初始化一个String[,]数组 string[,] data = new string[,] { {"排名","姓名","销售额","回款额","工号"}, {"1","李彪","18270","18270","0011"}, {"2","李娜","18105","18105","0025"}, {"3","张丽","17987","17987","0008"}, {"4","黄艳","17790","17790","0017"}, }; 步骤六:保存文档 ppt.SaveToFile("创建表格.pptx", FileFormat.Pptx2010); 完成操作后得到以下PPT文档效果 2.删除表格行与列 步骤一:初始化一个Presentation实例并加载一个PowerPoint文档 Presentation ppt = new Presentation(); ppt.LoadFromFile(@"C:\Users\Administrator\Desktop\创建表格.pptx"); 步骤二:获取第一张幻灯片上的表格 for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { table[j, i].TextFrame.Text = data[i, j]; table[j, i].TextFrame.Paragraphs[0].TextRanges[0].LatinFont = new TextFont("Arial"); } } 步骤三:删除第四列及第四行 table.ColumnsList.RemoveAt(3, false); table.TableRows.RemoveAt(4, false); 步骤四:保存文档 ppt.SaveToFile("删除行与列.pptx", FileFormat.Pptx2010); 3.删除表格 步骤一:初始化一个Presentation实例并加载一个PowerPoint文档 Presentation ppt = new Presentation(); ppt.LoadFromFile(@"C:\Users\Administrator\Desktop\创建表格.pptx"); 步骤二:初始化一个List对象,元素类型为IShape List<IShape> tableShapes = new List<IShape>(); 步骤三:获取第一张幻灯片上所有的表格图形并添加到List for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { table[j, i].TextFrame.Text = data[i, j]; table[j, i].TextFrame.Paragraphs[0].TextRanges[0].LatinFont = new TextFont("Arial"); } } 步骤四:从幻灯片删除第一个表格图形 ppt.Slides[0].Shapes.Remove(tableShapes[0]); 步骤五:保存文档 ppt.SaveToFile("删除表格.pptx", FileFormat.Pptx2010); 以上是本人使用Free Spire.Presentation这款组件对PPT文档中表格的一些操作,希望能提供帮助,感谢阅读!
在查看很多有复杂的数据的表格时,为了能够快速地找到所需要的数据组时,往往需要对该数据组进行分类,一个简单快速的方法就是对数据组所在的单元格填充背景颜色,这样就使得我们在阅读文件时能够直观的看到数据分类,既美观又实用。那对于开发者而言,我这里提供一个简单快速的方法,即用C#给单元格设置背景颜色。下面是我的操作方法,供参考。我这里使用了一个叫Spire.XLS for . NET的免费版组件,该产品由E-iceblue公司发布,具体详情可上官网了解(https://www.e-iceblue.cn/Introduce/Spire-XLS-NET.html),不废话,下面我演示一下我的操作。 原文件如图: 步骤: 1、 添加命名空间 Using Spire.Xls; Using System.Drawing; 2、 初始化工作簿并加载文档 Workbook workbook = new Workbook(); workbook.LoadFromFile(@"C:\Users\Administrator\Desktop\test.xlsx", ExcelVersion.Version97to2003); Worksheet worksheet = workbook.Worksheets[0];Worksheet worksheet = workbook.Worksheets[0]; 3、设置单元格背景颜色 worksheet.Range["A1:C2"].Style.Color = Color.LightSeaGreen; worksheet.Range["A3:C4"].Style.Color = Color.LightYellow; worksheet.Range["A5:C19"].Style.Color = Color.SpringGreen;worksheet.Range["A20:C21"].Style.Color = Color.DeepSkyBlue; worksheet.Range["A22:C23"].Style.Color = Color.Yellow; 4、保存并预览文件 workbook.SaveToFile("GradesRank.xls",ExcelVersion.Version97to2003; System.Diagnostics.Process.Start(workbook.FileName); 完成以上步骤后文档背景颜色添加成功,如下图所示: 完整代码: C# using System.Drawing; using Spire.Xls; namespace background_color { class Program { static void Main(string[] args) { Workbook workbook = new Workbook(); workbook.LoadFromFile(@"C:\Users\Administrator\Desktop\test.xlsx", ExcelVersion.Version97to2003); Worksheet worksheet = workbook.Worksheets[0]; //set the backgroundcolor of Range["A1:C2"] worksheet.Range["A1:C2"].Style.Color = Color.LightSeaGreen; //set the backgroundcolor of Range["A3:C4"] worksheet.Range["A3:C4"].Style.Color = Color.LightYellow; //set the backgroundcolor of Range["A5:C19"] worksheet.Range["A5:C19"].Style.Color = Color.SpringGreen; //set the backgroundcolor of Range["A20:C21"] worksheet.Range["A20:C21"].Style.Color = Color.DeepSkyBlue; //set the backgroundcolor of Range["A22:C23"] worksheet.Range["A22:C23"].Style.Color = Color.Yellow; //save and launch the project workbook.SaveToFile("Sample.xls", ExcelVersion.Version97to2003); System.Diagnostics.Process.Start(workbook.FileName); } } } VB.NET: Imports System.Drawing Imports Spire.Xls Namespace background_color Class Program Private Shared Sub Main(ByVal args() As String) Dim workbook As Workbook = New Workbook workbook.LoadFromFile("C:\Users\Administrator\Desktop\test.xlsx", ExcelVersion.Version97to2003) Dim worksheet As Worksheet = workbook.Worksheets(0) 'set the backgroundcolor of Range["A1:C2"] worksheet.Range("A1:C2").Style.Color = Color.LightSeaGreen 'set the backgroundcolor of Range["A3:C4"] worksheet.Range("A3:C4").Style.Color = Color.LightYellow 'set the backgroundcolor of Range["A5:C19"] worksheet.Range("A5:C19").Style.Color = Color.SpringGreen 'set the backgroundcolor of Range["A20:C21"] worksheet.Range("A20:C21").Style.Color = Color.DeepSkyBlue 'set the backgroundcolor of Range["A22:C23"] worksheet.Range("A22:C23").Style.Color = Color.Yellow 'save and launch the project workbook.SaveToFile("Sample.xls", ExcelVersion.Version97to2003) System.Diagnostics.Process.Start(workbook.FileName) End Sub End Class End Namespace
在现代办公环境中,阅读或者编辑较长篇幅的Word文档时,想要在文档中某一处或者几处留下标记,方便日后查找、修改时,需要在相对应的文档位置插入书签。那对于开发者而言,在C#或者VB.NET语言环境中,如何来快速、简便的插入书签呢,我分享一下我的经验。这里我用到了一款E-iceblue公司发布的一款免费的Word组件(Free Spire.Doc for .NET),方法很简单,如下: 步骤一:初始化Document实例并加载Word文档 Document document = new Document(); document.LoadFromFile(@"C:\Users\Administrator\Desktop\中国梦.docx "); 步骤二:于第七段末和第八段间插入书签,命名书签为“C#.bookmark” Section section = document.Sections[0]; section.Paragraphs[7].AppendBookmarkStart("C#.bookmark"); section.Paragraphs[8].AppendBookmarkEnd("C#.bookmark "); 步骤三:保存文件 document.SaveToFile("Bookmark.docx", FileFormat.Docx); System.Diagnostics.Process.Start("Bookmark.docx"); 完成后以上步骤后,文档中查找定位即可,文档自动定位到当前所设书签位置。 以上简单三个步骤即可完成对word文档书签插入。 完整代码如下,供参考: C# using System; using Spire.Doc; using Spire.Doc.Documents; namespace WordBookmark { class Bookmark { static void Main(string[] args) { //Load Document Document document = new Document(); document.LoadFromFile(@"C:\Users\Administrator\Desktop\中国梦.docx "); //Insert Bookmark Section section = document.Sections[0]; section.Paragraphs[7].AppendBookmarkStart(".NETFramework"); section.Paragraphs[8].AppendBookmarkEnd(".NETFramework"); //Save and Launch document.SaveToFile("Bookmark.docx", FileFormat.Docx); System.Diagnostics.Process.Start("Bookmark.docx"); } } } VB.NET: Imports System Imports Spire.Doc Imports Spire.Doc.Documents Namespace WordBookmark Class Bookmark Private Shared Sub Main(ByVal args() As String) 'Load Document Dim document As Document = New Document document.LoadFromFile("C:\Users\Administrator\Desktop\中国梦.docx ") 'Insert Bookmark Dim section As Section = document.Sections(0) section.Paragraphs(7).AppendBookmarkStart(".NETFramework") section.Paragraphs(8).AppendBookmarkEnd(".NETFramework") 'Save and Launch document.SaveToFile("Bookmark.docx", FileFormat.Docx) System.Diagnostics.Process.Start("Bookmark.docx") End Sub End Class End Namespace 同样的,撤销书签也可以参考执行我下面的操作 步骤一:加载需要撤销书签的Word文档 Document doc = new Document(); doc.LoadFromFile(@"C:\Users\Administrator\Desktop\中国梦(书签).docx"); 步骤二:撤销已有书签 doc.Bookmarks.RemoveAt(0); 步骤三:保存文件 doc.SaveToFile("Remove Bookmark.docx", FileFormat.Docx); System.Diagnostics.Process.Start("Remove Bookmark.docx"); 撤销书签后,得到以下文档效果 如图,原本插入书签的段落已撤销书签 完整代码如下 C#: using Spire.Doc; namespace Removing { class Program { static void Main(string[] args) { //Load Document Document doc = new Document(); doc.LoadFromFile(@"C:\Users\Administrator\Desktop\中国梦(书签).docx "); //Remove Bookmark doc.Bookmarks.RemoveAt(0); //Save and Launch doc.SaveToFile("Remove Bookmark.docx", FileFormat.Docx); System.Diagnostics.Process.Start("Remove Bookmark.docx"); } } } VB.NET: Imports Spire.Doc Namespace Removing Class Program Private Shared Sub Main(ByVal args() As String) 'Load Document Dim doc As Document = New Document doc.LoadFromFile("C:\Users\Administrator\Desktop\中国梦(书签).docx ") 'Remove Bookmark doc.Bookmarks.RemoveAt(0) 'Save and Launch doc.SaveToFile("Remove Bookmark.docx", FileFormat.Docx) System.Diagnostics.Process.Start("Remove Bookmark.docx") End Sub End Class End Namespace 以上内容是本人对word插入及撤销书签的操作演示,希望我的这个分享对你有所启发,感谢阅读!
在日常工作中,在编辑文档时,为了方便自己或者Boss能够实时查看到需要的网页或者文档时,需要对在Excel中输入的相关文字设置超链接,那么对于一些在Excel中插入的图片我们该怎么实现超链接呢,下面给大家分享一个方法: 首先简单了解一下一款叫Spire.XLS的组件,这个组件是由E-iceblue公司发布的一款独立的Excel组件,它的最大优点在于不依赖Microsoft Excel, 可以用在各种 .NET 框架中,包括 ASP.NET 和 Windows Forms 等相关的 .NET 应用程序,功能齐全,而且易于使用。有兴趣的朋友可以上E-iceblue官网了解详细内容,也可以在该网站上下载免费版Excel组件。 使用C#为Excel中的图片进行超链接,可以参考我下面的操作步骤,这里需要使用到一些代码,但只需要几步就可以完成: 操作步骤: 第一步:创建一个工作簿,获取第一个工作表 Workbook wb = new Workbook(); Worksheet sheet = wb.Worksheets[0]; 第二步:在特定单元格内添加文本内容 sheet.Range["A1"].Text = "Excel图片超链接"; sheet.Range["A1"].Style.VerticalAlignment = VerticalAlignType.Top; 第三步:插入图片并添加超链接 string picPath = @"C:\Users\Administrator\Desktop\tupian.jpg"; ExcelPicture picture = sheet.Pictures.Add(1, 1, picPath); picture.SetHyperLink("https://github.com/", true); 第四步:设置第一列宽度和第一行高度 sheet.Columns[0].ColumnWidth = 30; sheet.Rows[0].RowHeight = 150;picture.TopRowOffset = 25; 第五步:保存文件 wb.SaveToFile("ImageHyperlink.xlsx", ExcelVersion.Version2013); 操作完成后得到以下输出结果: 所以,实现对图片的超链接,只需要完成以上几个步骤就可以了。 同样的道理,在VB.NET中,也可以实现对Excel图片的超链接。 完整的代码如下,供参考: C#: using System; using System.Collections.Generic; using System.Linq; using System.Text; using Spire.Xls; namespace Excel_image_hyperlink { class Program { static void Main(string[] args) { Workbook wb = new Workbook(); Worksheet sheet = wb.Worksheets[0]; sheet.Range["A1"].Text = "Excel图片超链接"; sheet.Range["A1"].Style.VerticalAlignment = VerticalAlignType.Top; string picPath = @"C:\Users\Administrator\Desktop\tupian.jpg"; ExcelPicture picture = sheet.Pictures.Add(1, 1, picPath); picture.SetHyperLink("https://github.com/", true); sheet.Columns[0].ColumnWidth = 30; sheet.Rows[0].RowHeight = 150; picture.TopRowOffset = 25; wb.SaveToFile("ImageHyperlink.xlsx", ExcelVersion.Version2013); } } VB: Imports System Imports System.Collections.Generic Imports System.Linq Imports System.Text Imports Spire.Xls Namespace Excel_image_hyperlink Class Program Private Shared Sub Main(ByVal args() As String) Dim wb As Workbook = New Workbook Dim sheet As Worksheet = wb.Worksheets(0) sheet.Range("A1").Text = "Excel图片超链接" sheet.Range("A1").Style.VerticalAlignment = VerticalAlignType.Top Dim picPath As String = "C:\Users\Administrator\Desktop\tupian.jpg" Dim picture As ExcelPicture = sheet.Pictures.Add(1, 1, picPath) picture.SetHyperLink("https://github.com/", true) sheet.Columns(0).ColumnWidth = 30 sheet.Rows(0).RowHeight = 150 picture.TopRowOffset = 25 wb.SaveToFile("ImageHyperlink.xlsx", ExcelVersion.Version2013) End Sub End Class End Namespace 希望这个方法对你有所帮助。 感谢阅读!
C# 添加、修改和删除PDF书签 有时候我们在阅读PDF文档时会遇到这样一种情况:PDF文档页数比较多,但是又没有书签,所以我们不能根据书签快速了解文档所讲解的内容,也不能点击书签快速跳转到相应的位置,而只能一页一页的翻阅,非常苦恼。相信开发人员在开发和PDF有关的应用程序时,也会有这样的功能需求,因此在这篇文章中我就介绍一下如何使用编程的方式(C#)和Spire.PDF组件给PDF文档添加书签(包括添加书签到现有文档和添加子书签),以及修改和删除现有PDF文档中的指定书签。 Spire.PDF组件概述 Spire.PDF是一个专业的PDF组件,用于在.NET应用程序中创建,编辑,处理和阅读PDF文档。支持丰富的PDF文档处理操作,如PDF文档合并/拆分、转换(如HTML转PDF,PDF转图片等)、打印(包括静默打印)、压缩、添加/修改/删除书签、添加注释、安全设置(包括数字签名)、创建与填充域、图片插入与提取、文本提取与高亮等。它不依赖Adobe Acrobat,因此运行环境无需安装Adobe Reader或其他类似组件。 该组件分为商业版和免费版(不是试用版)两种,一般个人使用或者操作的PDF文档不超过10页时,可以使用免费版。 关于它的安装,有很多种渠道,包括官网以及开发者最喜欢和常用的NuGet方式。在Visual Studio的 NuGet Package Manager Console中输入以下PowerShell命令回车,组件的dll就会自动地引用到项目中: PM> Install-Package Spire.PDF 添加、修改和删除PDF书签的实现 一、添加书签 1.1 添加书签 在Spire.PDF中,每个PDF文档都有一个书签列表(PdfBookmarkCollection)。我们可以通过PdfDocument对象的Bookmarks属性来获取该列表,然后通过Add () 方法将书签添加到列表中。 //新建PDF文档 PdfDocument pdf = new PdfDocument(); //添加页面 PdfPageBase page = pdf.Pages.Add(); //添加书签 PdfBookmark bookmark = pdf.Bookmarks.Add("第一页"); //设置书签所指向的页面和位置,(0,0)表示页面的开始位置 bookmark.Destination = new PdfDestination(page); bookmark.Destination.Location = new PointF(0, 0); //设置书签的文本格式和颜色 bookmark.DisplayStyle = PdfTextStyle.Bold; bookmark.Color = Color.Black; //保存文档 pdf.SaveToFile("Bookmark2.pdf"); 1.2 添加子书签 添加子书签和添加普通书签的方式基本一样,不同的是普通书签是直接添加到文档的书签列表里,而子书签则是添加到父书签的列表里。 //新建PDF文档 PdfDocument pdf = new PdfDocument(); //添加页面 PdfPageBase page = pdf.Pages.Add(); //添加书签 PdfBookmark bookmark = pdf.Bookmarks.Add("第一章 热传导"); //设置书签指向的页面和位置 bookmark.Destination = new PdfDestination(page); bookmark.Destination.Location = new PointF(0, 0); //设置书签的文本格式和颜色 bookmark.DisplayStyle = PdfTextStyle.Bold; bookmark.Color = Color.SeaGreen; //添加子书签 PdfBookmark childBookmark = bookmark.Insert(0, "1.1 热传导基本知识"); //设置子书签指向的页面和位置 childBookmark.Destination = new PdfDestination(page); childBookmark.Destination.Location = new PointF(400, 300); //设置子书签的文本格式和颜色 childBookmark.DisplayStyle = PdfTextStyle.Regular; childBookmark.Color = Color.Black; //保存文档 pdf.SaveToFile("ChildBookmark.pdf"); 1.3 添加书签到现有文档 除了在新建的PDF文档里添加书签,我们还可以给现有的PDF文档添加书签。加载PDF文档的方法除LoadFromFile以外,还有LoadFromStream (从流加载),LoadFromHTML(从HTML加载)等,可根据自己的需求选择相应的加载方式。 //加载文档 PdfDocument pdf = new PdfDocument(); pdf.LoadFromFile("示例.pdf"); for (int i = 0; i < pdf.Pages.Count; i++) { //添加书签 PdfBookmark bookmark = pdf.Bookmarks.Add(string.Format("第{0}章", i+1)); //设置书签指向的页面和位置 bookmark.Destination = new PdfDestination(pdf.Pages[i]); bookmark.Destination.Location = new PointF(0, 0); //设置书签的文本格式和颜色 bookmark.DisplayStyle = PdfTextStyle.Bold; bookmark.Color = Color.Black; } //保存文档 pdf.SaveToFile("Bookmark2.pdf"); 2. 修改书签 Spire.PDF支持多种书签修改方式,例如修改现有书签的内容,插入新书签到现有书签列表,插入子书签到现有书签等。这里我选取修改书签内容和插入新书签到现有书签列表进行介绍。 2.1 修改现有书签内容 //加载文档 PdfDocument pdf = new PdfDocument(); pdf.LoadFromFile("Bookmark2.pdf"); //获取书签列表 PdfBookmarkCollection bookmarks = pdf.Bookmarks; //获取第一个书签 PdfBookmark bookmark = bookmarks[0]; //修改书签指向的页面 bookmark.Destination = new PdfDestination(document.Pages[1]); //修改书签的文本格式和颜色 bookmark.DisplayStyle = PdfTextStyle.Bold; bookmark.Color = Color.Green; //修改书签的title bookmark.Title = "修改"; //保存文档 pdf.SaveToFile("ModifyBookmark.pdf"); 2.2 插入新书签到现有书签列表 //加载文档 PdfDocument pdf = new PdfDocument(); pdf.LoadFromFile("Bookmark2.pdf"); //插入新书签到指定位置(此处插入的是第三个书签的位置) PdfBookmark bookmark = pdf.Bookmarks.Insert(2, "新增第三章"); //设置书签所指向的页面和位置 bookmark.Destination = new PdfDestination(document.Pages[1]); bookmark.Destination.Location = new PointF(0, 300); //保存文档 pdf.SaveToFile("InsertBookmark.pdf"); 3. 删除书签 删除书签时,可以使用书签的序号,也可以使用书签的名称。这里我使用的是序号的方式。 //加载文档 PdfDocument pdf = new PdfDocument(); pdf.LoadFromFile("Bookmark2.pdf"); //获取书签列表 PdfBookmarkCollection bookmarks = document.Bookmarks; //删除第一个书签 bookmarks.RemoveAt(0); //保存文档 pdf.SaveToFile("DeleteBookmark.pdf"); 以上博主只总结了部分操作PDF书签的功能,如果需要详细了解其他的功能,请查阅:http://e-iceblue.cn/Introduce/Spire-PDF-NET.html。如有任何疑问,欢迎给博主留言。欢迎转载,转载时请注明出处!
编辑Word文档时,我们有时会突然想增加一段新内容;而将word文档给他人浏览时,有些信息我们是不想让他人看到的。那么如何运用C#编程的方式巧妙地插入或隐藏段落呢?本文将与大家分享一种向Word文档插入新段落及隐藏段落的好方法。 这里使用的是Free Spire.Doc for .NET组件,该组件允许开发人员轻松并灵活地操作Word文档。 向Word文档插入一个新段落的操作步骤 步骤1:新建一个文档并加载现有文档 Document document = new Document(); document.LoadFromFile(@"C:\Users\Administrator\Desktop\向日葵.docx", FileFormat.Docx); 步骤2:插入新段落并设置字体格式 Paragraph paraInserted = document.Sections[0].AddParagraph(); TextRange textRange1 = paraInserted.AppendText("向日葵的花语是——太阳、光辉、高傲、忠诚、爱慕、沉默的爱。向日葵又叫望日莲,一个很美的名字"); textRange1.CharacterFormat.TextColor = Color.Blue; textRange1.CharacterFormat.FontSize = 15; textRange1.CharacterFormat.UnderlineStyle = UnderlineStyle.Dash; 步骤3:保存文档 document.SaveToFile("result.docx", FileFormat.Docx); 以下是程序运行前后的对比图: 运行前 运行后 隐藏段落的操作步骤 当操作Word文档时,我们可以通过Microsoft Word点击字体对话框来隐藏所选择的文本。请通过如下的屏幕截图来查看Microsoft是如何隐藏文本的: 然而,Free Spire.Doc for .NET可以通过设置CharacterFormat.Hidden的属性来隐藏指定文本或整个段落,下面将为大家介绍详细步骤: 步骤1:新建一个文档并加载现有文档 Document doc = new Document(); doc.LoadFromFile(@"C:\Users\Administrator\Desktop\雏菊.docx", FileFormat.Docx); 步骤2:获取Word文档的第一个section和最后一段 Section sec = doc.Sections[0]; Paragraph para = sec.Paragraphs[sec.Paragraphs.Count - 1]; 步骤3:调用for循环语句来获取最后一段的所有TextRange并将CharacterFormat.Hidden的属性设置为true for (int i = 0; i < para.ChildObjects.Count;i++) { (para.ChildObjects[i] as TextRange).CharacterFormat.Hidden = true; } 步骤4:保存文档 doc.SaveToFile("result1.docx", FileFormat.Docx); 以下是程序运行前后的对比图: 运行前 运行后 C#完整代码 using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; namespace insert_new_paragraph_and_hide { class Program { static void Main(string[] args) { //该部分为插入新段落的代码 Document document = new Document(); document.LoadFromFile(@"C:\Users\Administrator\Desktop\向日葵.docx", FileFormat.Docx); Paragraph paraInserted = document.Sections[0].AddParagraph(); TextRange textRange1 = paraInserted.AppendText("向日葵的花语是——太阳、光辉、高傲、忠诚、爱慕、沉默的爱。向日葵又叫望日莲,一个很美的名字"); textRange1.CharacterFormat.TextColor = Color.Blue; textRange1.CharacterFormat.FontSize = 15; textRange1.CharacterFormat.UnderlineStyle = UnderlineStyle.Dash; document.SaveToFile("result.docx", FileFormat.Docx); //该部分为隐藏段落的代码 Document doc = new Document(); doc.LoadFromFile(@"C:\Users\Administrator\Desktop\雏菊.docx", FileFormat.Docx); Section sec = doc.Sections[0]; Paragraph para = sec.Paragraphs[sec.Paragraphs.Count - 1]; for (int i = 0; i < para.ChildObjects.Count;i++) { (para.ChildObjects[i] as TextRange).CharacterFormat.Hidden = true; } doc.SaveToFile("result1.docx", FileFormat.Docx); } } } 这是我本次要分享的全部内容,感谢您的浏览。