Làm việc với đoạn văn

Đoạn văn là một tập hợp các ký tự được kết hợp thành một khối logic và kết thúc bằng một ký tự đặc biệt – ngắt đoạn. Trong Aspose.Words, một đoạn văn được thể hiện bằng lớp Paragraph.

Chèn một đoạn văn

Để chèn một đoạn văn mới vào tài liệu, trên thực tế, bạn cần chèn ký tự ngắt đoạn vào đó. DocumentBuilder.Writeln không chỉ chèn một chuỗi văn bản vào tài liệu mà còn thêm dấu ngắt đoạn.

Định dạng phông chữ hiện tại cũng được xác định bởi thuộc tính Font và định dạng đoạn văn hiện tại được xác định bởi thuộc tính ParagraphFormat. Trong phần tiếp theo, chúng ta sẽ đi vào chi tiết hơn về định dạng đoạn văn.

Ví dụ mã sau đây cho thấy cách chèn một đoạn văn vào tài liệu:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// 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);

Định dạng đoạn

Định dạng đoạn văn hiện tại được thể hiện bằng đối tượng ParagraphFormat được trả về bởi thuộc tính ParagraphFormat. Đối tượng này đóng gói các thuộc tính định dạng đoạn văn khác nhau có sẵn trong Microsoft Word. Bạn có thể dễ dàng đặt lại định dạng của đoạn văn về mặc định – Kiểu bình thường, căn trái, không thụt lề, không khoảng cách, không viền, không đổ bóng – bằng cách gọi ClearFormatting.

Ví dụ mã sau đây cho biết cách đặt định dạng đoạn văn:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
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);

Áp dụng kiểu đoạn văn

Một số đối tượng định dạng, chẳng hạn như Font hoặc ParagraphFormat, hỗ trợ kiểu. Một kiểu dựng sẵn hoặc do người dùng xác định được thể hiện bằng một đối tượng Style, chứa các thuộc tính kiểu thích hợp như tên, kiểu cơ sở, phông chữ, định dạng đoạn kiểu, v.v.

Ngoài ra, đối tượng Style còn hiển thị thuộc tính StyleIdentifier, thuộc tính này trả về mã định danh kiểu độc lập với miền địa phương được biểu thị bằng giá trị liệt kê StyleIdentifier. Thực tế là tên của các kiểu tích hợp trong Microsoft Word đã được bản địa hóa cho các ngôn ngữ khác nhau. Bằng cách sử dụng mã định danh kiểu, bạn có thể tìm thấy kiểu chính xác bất kể ngôn ngữ tài liệu. Các giá trị liệt kê tương ứng với các kiểu Microsoft Word tích hợp sẵn như Normal, Heading 1, Heading 2, v.v. Tất cả các kiểu do người dùng xác định được đặt thành giá trị liệt kê StyleIdentifier.User.

Ví dụ mã sau đây cho thấy cách áp dụng kiểu đoạn văn:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
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);

Chèn dấu phân cách kiểu để đặt các kiểu đoạn văn khác nhau

Bạn có thể thêm dấu phân cách kiểu vào cuối đoạn bằng phím tắt Ctrl+Alt+Enter trong Microsoft Word. Tính năng này cho phép bạn sử dụng hai kiểu đoạn văn khác nhau trong cùng một đoạn văn được in logic. Nếu bạn muốn một số văn bản ở đầu một tiêu đề cụ thể xuất hiện trong mục lục nhưng không muốn toàn bộ tiêu đề hiển thị trong mục lục, bạn có thể sử dụng chức năng này.

Ví dụ mã sau đây cho thấy cách chèn dấu phân cách kiểu để phù hợp với các kiểu đoạn văn khác nhau:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
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);

Xác định dấu phân cách kiểu đoạn văn

Aspose.Words hiển thị thuộc tính công khai BreakIsStyleSeparator trên lớp Paragraph để xác định một đoạn văn có dấu phân cách kiểu, như trong ví dụ bên dưới:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_RenderingAndPrinting();
// Initialize document.
string fileName = "TestFile.doc";
Document doc = new Document(dataDir + fileName);
foreach (Paragraph paragraph in doc.GetChildNodes(NodeType.Paragraph, true))
{
if (paragraph.BreakIsStyleSeparator)
{
Console.WriteLine("Separator Found!");
}
}

Áp dụng viền và tô bóng cho đoạn văn

Các đường viền trong Aspose.Words được biểu thị bằng lớp BorderCollection - đây là tập hợp các đối tượng Border được truy cập theo chỉ mục hoặc theo loại đường viền. Loại đường viền lần lượt được biểu thị bằng bảng liệt kê BorderType. Một số giá trị liệt kê áp dụng cho nhiều hoặc chỉ một phần tử tài liệu. Ví dụ: BorderType.Bottom áp dụng cho một đoạn văn hoặc ô bảng, trong khi BorderType.DiagonalDown chỉ xác định đường viền chéo trong ô bảng.

Cả bộ sưu tập đường viền và mỗi đường viền riêng biệt đều có các thuộc tính tương tự như màu sắc, kiểu đường kẻ, độ rộng đường kẻ, khoảng cách từ văn bản và bóng tùy chọn. Chúng được đại diện bởi các thuộc tính cùng tên. Bạn có thể nhận được các loại đường viền khác nhau bằng cách kết hợp các giá trị thuộc tính. Ngoài ra, các đối tượng BorderCollectionBorder cho phép bạn đặt lại các giá trị này về giá trị mặc định của chúng bằng cách gọi phương thức ClearFormatting.

Aspose.Words cũng có lớp Shading chứa các thuộc tính tô bóng cho các thành phần tài liệu. Bạn có thể đặt kết cấu bóng và màu sắc mong muốn được áp dụng cho nền và nền trước của một phần tử bằng cách sử dụng giá trị liệt kê TextureIndex. TextureIndex cũng cho phép bạn áp dụng các mẫu khác nhau cho đối tượng Shading. Ví dụ: để đặt màu nền cho thành phần tài liệu, hãy sử dụng giá trị TextureIndex.TextureSolid và đặt màu bóng nền trước cho phù hợp.

Ví dụ mã sau đây cho thấy cách áp dụng đường viền và tô bóng cho một đoạn văn:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
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);

Đếm số dòng đoạn văn

Nếu bạn muốn đếm số dòng trong một đoạn văn cho bất kỳ tài liệu Word nào, có thể sử dụng mẫu mã sau:

// 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).");
}