Word格式处理控件Aspose.Words for .NET教程——插入段落并调整样式

Aspose.Words For .NET是一种高级Word文档处理API,用于执行各种文档管理和操作任务。API支持生成,修改,转换,呈现和打印文档,而无需在跨平台应用程序中直接使用Microsoft Word。此外,API支持所有流行的Word处理文件格式,并允许将Word文档导出或转换为固定布局文件格式和最常用的图像/多媒体格式。

>>Aspose.Words for .NET已经更新至最新版,提供显示/隐藏语法和拼写错误的功能,引入了可在文档内部使用水印的新帮助程序类,添加了为OOXML文档设置压缩级别的功能,点击下载体验

了解更多Aspose文档管理产品  Aspose技术交流群(761297826)


插入段落

DocumentBuilder.Writeln 也可以在文档中插入文本字符串,但除此之外,它还会添加一个段落分隔符。该DocumentBuilder.Font 属性还指定当前字体格式,而该 属性确定当前段落格式 DocumentBuilder.ParagraphFormat 。 下例显示了如何将段落插入文档。

// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithDocument();
// Initialize document.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Specify font formatting
Font font = builder.Font;
font.Size = 16;
font.Bold = true;
font.Color = System.Drawing.Color.Blue;
font.Name = "Arial";
font.Underline = Underline.Dash;

// Specify paragraph formatting
ParagraphFormat paragraphFormat = builder.ParagraphFormat;
paragraphFormat.FirstLineIndent = 8;
paragraphFormat.Alignment = ParagraphAlignment.Justify;
paragraphFormat.KeepTogether = true;

builder.Writeln("A whole paragraph.");
dataDir = dataDir + "DocumentBuilderInsertParagraph_out.doc";
doc.Save(dataDir);
 

计算段落的行数

如果要计算任何Word文档的段落中的行数,则可以使用以下代码示例。

  // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_WorkingWithDocument();

            string fileName = "Properties.doc";
            Document document = new Document(dataDir + fileName);

            var collector = new LayoutCollector(document);
            var it = new LayoutEnumerator(document);

            foreach (Paragraph paragraph in document.GetChildNodes(NodeType.Paragraph, true))
            {
                var paraBreak = collector.GetEntity(paragraph);

                object stop = null;
                var prevItem = paragraph.PreviousSibling;
                if (prevItem != null)
                {
                    var prevBreak = collector.GetEntity(prevItem);
                    if (prevItem is Paragraph)
                    {
                        it.Current = collector.GetEntity(prevItem); // para break
                        it.MoveParent();    // last line
                        stop = it.Current;
                    }
                    else if (prevItem is Table)
                    {
                        var table = (Table)prevItem;
                        it.Current = collector.GetEntity(table.LastRow.LastCell.LastParagraph); // cell break
                        it.MoveParent();    // cell
                        it.MoveParent();    // row
                        stop = it.Current;
                    }
                    else
                    {
                        throw new Exception();
                    }
                }

                it.Current = paraBreak;
                it.MoveParent();

                // We move from line to line in a paragraph.
                // When paragraph spans multiple pages the we will follow across them.
                var count = 1;
                while (it.Current != stop)
                {
                    if (!it.MovePreviousLogical())
                        break;
                    count++;
                }

                const int MAX_CHARS = 16;
                var paraText = paragraph.GetText();
                if (paraText.Length > MAX_CHARS)
                    paraText = $"{paraText.Substring(0, MAX_CHARS)}...";

                Console.WriteLine($"Paragraph '{paraText}' has {count} line(-s).");
            }

段落格式

当前段落格式由DocumentBuilder.ParagraphFormat属性返回的ParagraphFormat对象表示。该对象封装了Microsoft Word中可用的各种段落格式设置属性。您可以通过调用ParagraphFormat.ClearFormatting轻松将段落格式重置为默认样式,即默认样式为普通样式,左对齐,无缩进,无间距,无边框和无阴影 。下例显示了如何设置段落格式。

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Set paragraph formatting properties
ParagraphFormat paragraphFormat = builder.ParagraphFormat;
paragraphFormat.Alignment = ParagraphAlignment.Center;
paragraphFormat.LeftIndent = 50;
paragraphFormat.RightIndent = 50;
paragraphFormat.SpaceAfter = 25;

// Output text
builder.Writeln("I'm a very nice formatted paragraph. I'm intended to demonstrate how the left and right indents affect word wrapping.");
builder.Writeln("I'm another nice formatted paragraph. I'm intended to demonstrate how the space after paragraph looks like.");

dataDir = dataDir + "DocumentBuilderSetParagraphFormatting_out.doc";
doc.Save(dataDir);

应用段落样式

一些格式对象(例如Font或ParagraphFormat)支持样式。单个内置或用户定义的样式由Style对象表示,该对象包含相应的样式属性,例如名称,基本样式,样式的字体和段落格式,等等。

此外, Style 对象提供Style.StyleIdentifier 属性,该 属性返回由Style.StyleIdentifier 枚举值表示的与语言环境无关的样式标识符 。关键是Microsoft Word中内置样式的名称针对不同的语言进行了本地化。使用样式标识符,无论文档语言是什么,都可以找到正确的样式。枚举值对应于Microsoft Word内置样式,例如Normal,Heading 1,Heading 2等。所有用户定义的样式均分配有 StyleIdentifier.User值。下例显示了如何应用段落样式。

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Set paragraph style
builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Title;

builder.Write("Hello");
dataDir = dataDir + "DocumentBuilderApplyParagraphStyle_out.doc";
doc.Save(dataDir);

插入样式分隔符以放置不同的段落样式

一些格式对象(例如Font或ParagraphFormat)支持样式。单个内置或用户定义的样式由Style对象表示,该对象包含相应的样式属性,例如名称,基本样式,样式的字体和段落格式,等等。

可以使用Ctrl + Alt +在MS Word中输入键盘快捷键将样式分隔符添加到段落的末尾。此功能允许在一个逻辑打印段落中使用两种不同的段落样式。如果要使特定标题开头的某些文本出现在目录中,但又不想整个标题出现在目录中,则可以使用此功能。下面的代码示例演示如何插入样式分隔符以放置不同的段落样式。

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Style paraStyle = builder.Document.Styles.Add(StyleType.Paragraph, "MyParaStyle");
paraStyle.Font.Bold = false;
paraStyle.Font.Size = 8;
paraStyle.Font.Name = "Arial";

// Append text with "Heading 1" style.
builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading1;
builder.Write("Heading 1");
builder.InsertStyleSeparator();

// Append text with another style.
builder.ParagraphFormat.StyleName = paraStyle.Name;
builder.Write("This is text with some other formatting ");
 
dataDir = dataDir + "InsertStyleSeparator_out.doc";

// Save the document to disk.
doc.Save(dataDir);

在段落上应用边框和底纹

边框由BorderCollection表示。这是按索引或按边框类型访问的Border对象的集合。边框类型由BorderType枚举表示。枚举的某些值适用于多个或仅一个文档元素。例如,BorderType.Bottom适用于段落或表格单元格,而BorderType.DiagonalDown仅指定表格单元格中的对角线边框。

边框集合和每个单独的边框都具有相似的属性,例如颜色,线条样式,线条宽度,距文本的距离以及可选的阴影。它们由相同名称的属性表示。您可以通过组合属性值来实现不同的边框类型。此外,BorderCollection和Border对象都允许您通过调用Border.ClearFormatting方法将这些值重置为默认值。请注意,当边框属性重置为默认值时,边框是不可见的。该 着色 类包含文档元素的材质属性。您可以设置所需的明暗处理纹理以及应用于元素的背景和前景的颜色。

阴影纹理设置有 TextureIndex 枚举值,该值允许将各种图案应用到 Shading 对象。例如,要为文档元素设置背景色,请使用TextureIndex.TextureSolid值并适当设置前景色。下例显示了如何对段落应用边框和阴影。下例显示了如何对段落应用边框和阴影。

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Set paragraph borders
BorderCollection borders = builder.ParagraphFormat.Borders;
borders.DistanceFromText = 20;
borders[BorderType.Left].LineStyle = LineStyle.Double;
borders[BorderType.Right].LineStyle = LineStyle.Double;
borders[BorderType.Top].LineStyle = LineStyle.Double;
borders[BorderType.Bottom].LineStyle = LineStyle.Double;

// Set paragraph shading
Shading shading = builder.ParagraphFormat.Shading;
shading.Texture = TextureIndex.TextureDiagonalCross;
shading.BackgroundPatternColor = System.Drawing.Color.LightCoral;
shading.ForegroundPatternColor = System.Drawing.Color.LightSalmon;

builder.Write("I'm a formatted paragraph with double border and nice shading.");
dataDir = dataDir + "DocumentBuilderApplyBordersAndShadingToParagraph_out.doc";
doc.Save(dataDir);

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
Aspose.Words for .NET提供了将Word文档中的内容转换为图片的功能,可以使用以下代码将Word文档转换为图片并调整图片格式列宽: ```csharp // 加载Word文档 Document doc = new Document("input.docx"); // 创建ImageSaveOptions对象 ImageSaveOptions options = new ImageSaveOptions(SaveFormat.Png); // 设置图片格式列宽 options.HorizontalResolution = 200; options.VerticalResolution = 200; // 遍历文档中的每个页面,并将其转换为图片 for (int pageIndex = 0; pageIndex < doc.PageCount; pageIndex++) { // 创建MemoryStream对象 MemoryStream stream = new MemoryStream(); // 将当前页面保存为图片 doc.Save(stream, options); // 加载图片 Image image = Image.FromStream(stream); // 调整图片格式列宽 int newWidth = image.Width * 2; int newHeight = image.Height * 2; // 创建新的Bitmap对象 Bitmap newBitmap = new Bitmap(newWidth, newHeight); // 创建Graphics对象 Graphics graphics = Graphics.FromImage(newBitmap); // 绘制图像 graphics.DrawImage(image, new Rectangle(0, 0, newWidth, newHeight), new Rectangle(0, 0, image.Width, image.Height), GraphicsUnit.Pixel); // 保存图片 newBitmap.Save("output.png", ImageFormat.Png); // 释放资源 stream.Dispose(); image.Dispose(); graphics.Dispose(); newBitmap.Dispose(); } ``` 在上述代码中,我们使用了ImageSaveOptions对象来设置生成的图片的格式,包括水平分辨率和垂直分辨率。然后,我们遍历文档中的每个页面,并将其转换为图片。对于每个页面,我们先将其保存为MemoryStream对象,然后将其加载为Image对象。接着,我们根据需要调整图片的格式列宽,然后创建新的Bitmap对象,并使用Graphics对象将原始图像绘制到新的Bitmap对象中。最后,我们保存新的Bitmap对象为PNG格式的图片。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值