Переклад Markdown до Document Object Model (Українська)DOMй

Щоб программатично читати, маніпулювати і змінювати зміст і форматування документа, потрібно перевести його до Aspose.Words Document Object Model (Українська)DOM).

На відміну від документів Word, Markdown не відповідає DOM описано в Aspose.Words Document Object Model (DOM) стаття. Однак Aspose.Words забезпечує власний механізм перетягування Markdown документи DOM і назад, так що ми можемо успішно працювати з елементами, такими як форматування тексту, таблиці, заголовки та інші.

Ця стаття пояснює, як різні markdown функції можна перекласти в Aspose.Words DOM і назад Markdown Формат.

Складність перекладу Markdown до DOM до Markdown

Основна складність цього механізму не тільки для перекладу Markdown до DOM, але також зробити зворотну трансформацію – зберегти документ назад до Markdown формат з мінімальною втратою. Є елементи, такі як багаторівневі котирування, для яких зворотна трансформація не тривіально.

Ми можемо самі зателефонувати одержувачу і узгодити зручний час і місце вручення квітів. Markdown документ, але також створити власний документ у Markdown формат з оригінальною структурою з нуля. Щоб створити різні елементи, потрібно використовувати стилі з певними назвами відповідно до певних правил, описаних пізніше в цій статті. Такі стилі можуть бути створені тематично.

Переклад Принципи

Ми використовуємо Font форматування для вбудованих блоків. Коли немає прямого листування Markdown в наявності Aspose.Words DOM, Ми використовуємо стиль персонажа з назвою, яка починається з деяких спеціальних слів.

Для контейнерних блоків ми використовуємо стиль спадкування, щоб викинути Markdown особливості. У цьому випадку, навіть якщо немає непристойних функцій, ми також використовуємо абзац стилі з назвою, яка починається з деяких спеціальних слів.

Булетні та замовлені списки є контейнерними блоками в Markdown і Їх гніздування представлена в DOM так само, як і для всіх інших контейнерних блоків з використанням стильного спадкування. Тим не менш, додатково, списки в DOM відповідати формату номеру в стилі список або форматування абзаців.

Внутрішні блоки

Ми використовуємо Font форматування при перекладі Bold, Italic або ~ ~ Розгортання ~ ~ inline markdown особливості.

Markdown Головна Aspose.Words
Bold
{1}
Font.Bold = true
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// Use a document builder to add content to the document.
DocumentBuilder builder = new DocumentBuilder();
// Make the text Bold.
builder.Font.Bold = true;
builder.Writeln("This text will be Bold");
Italic
*italic text*
Font.Italic = true
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// Use a document builder to add content to the document.
DocumentBuilder builder = new DocumentBuilder();
// Make the text Italic.
builder.Font.Italic = true;
builder.Writeln("This text will be Italic");
Strikethrough
~Strikethrough text~
Font.StrikeThrough = true
 // Use a document builder to add content to the document.
DocumentBuilder builder = new DocumentBuilder();

// Make the text Strikethrough.
builder.Font.Strikethrough = true;
builder.Writeln("This text will be Strikethrough"); 

Ми використовуємо стиль персонажа з назвою, яка починається з слова InlineCode, > далі за бажанням (.) і ряд бектики (`) для InlineCode функція. Якщо пропущено ряд спандексів, то один задняк буде використовуватися за замовчуванням.

Markdown Головна Aspose.Words
InlineCode
{1}
Font.StyleName = “InlineCode[.][N]”
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// Use a document builder to add content to the document.
DocumentBuilder builder = new DocumentBuilder();
// Number of backticks is missed, one backtick will be used by default.
Style inlineCode1BackTicks = builder.Document.Styles.Add(StyleType.Character, "InlineCode");
builder.Font.Style = inlineCode1BackTicks;
builder.Writeln("Text with InlineCode style with 1 backtick");
// There will be 3 backticks.
Style inlineCode3BackTicks = builder.Document.Styles.Add(StyleType.Character, "InlineCode.3");
builder.Font.Style = inlineCode3BackTicks;
builder.Writeln("Text with InlineCode style with 3 backtick");
Autolink
<scheme://domain.com>
<email@domain.com>
Про нас FieldHyperlink клас
Link
{1}
{2}
{3}
{4})
Про нас FieldHyperlink клас
Image
{1}
{2}
{3}
{4})
Про нас Shape клас
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// Use a document builder to add content to the document.
DocumentBuilder builder = new DocumentBuilder();
// Insert image.
Shape shape = new Shape(builder.Document, ShapeType.Image);
shape.WrapType = WrapType.Inline;
shape.ImageData.SourceFullName = "/attachment/1456/pic001.png";
shape.ImageData.Title = "title";
builder.InsertNode(shape);

Блоки контейнерів

Документ є послідовністю контейнерних блоків, таких як заголовки, абзаци, списки, котирування та інші. Контейнерні блоки можна розділити на 2 класи: Листові блоки та складні контейнери. Блоки Leaf можуть містити лише інлайн. Комплексні контейнери, в свою чергу, можуть містити інші контейнерні блоки, в тому числі блоки Leaf.

Листові блоки

Таблиця нижче показує приклади використання Markdown Листові блоки в Aspose.Words:

Markdown Головна Aspose.Words
HorizontalRule
-----
Це простий абзац з відповідною формою HorizontalRule:
DocumentBuilder.InsertHorizontalRule()
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// Use a document builder to add content to the document.
DocumentBuilder builder = new DocumentBuilder();
// Insert horizontal rule.
builder.InsertHorizontalRule();
ATX Heading
# H1, ## H2, ### H3…
ParagraphFormat.StyleName = "Heading N", де (1<= N <=9).
Це перекладається в вбудований стиль і має бути саме з зазначеного шаблону (не суфікси або префікси допускаються).
В іншому випадку це буде просто звичайний абзац з відповідним стилем
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// Use a document builder to add content to the document.
DocumentBuilder builder = new DocumentBuilder();
// By default Heading styles in Word may have Bold and Italic formatting.
//If we do not want to be emphasized, set these properties explicitly to false.
builder.Font.Bold = false;
builder.Font.Italic = false;
builder.ParagraphFormat.StyleName = "Heading 1";
builder.Writeln("This is an H1 tag");
Setext Heading
=== (якщо рівень заголовка 1),
--- (якщо рівень заголовка 2)
ParagraphFormat.StyleName = “SetextHeading[some suffix]”, на основі ‘Heading N’ стиль.
Якщо (N >= 2), то ‘Heading 2’ буде використовуватися, інакше ‘Heading 1’й
Допускається будь-який suffix, але Aspose.Words імпортер використовує номери “1” та “2” відповідно
 // Use a document builder to add content to the document.
DocumentBuilder builder = new DocumentBuilder();

builder.ParagraphFormat.StyleName = "Heading 1";
builder.Writeln("This is an H1 tag");

// Reset styles from the previous paragraph to not combine styles between paragraphs.
builder.Font.Bold = false;
builder.Font.Italic = false;

Style setexHeading1 = builder.Document.Styles.Add(StyleType.Paragraph, "SetextHeading1");
builder.ParagraphFormat.Style = setexHeading1;
builder.Document.Styles["SetextHeading1"].BaseStyleName = "Heading 1";
builder.Writeln("Setext Heading level 1");

builder.ParagraphFormat.Style = builder.Document.Styles["Heading 3"];
builder.Writeln("This is an H3 tag");

// Reset styles from the previous paragraph to not combine styles between paragraphs.
builder.Font.Bold = false;
builder.Font.Italic = false;

Style setexHeading2 = builder.Document.Styles.Add(StyleType.Paragraph, "SetextHeading2");
builder.ParagraphFormat.Style = setexHeading2;
builder.Document.Styles["SetextHeading2"].BaseStyleName = "Heading 3";

// Setex heading level will be reset to 2 if the base paragraph has a Heading level greater than 2.
builder.Writeln("Setext Heading level 2"); 
Indented Code ParagraphFormat.StyleName = “IndentedCode[some suffix]”
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// Use a document builder to add content to the document.
DocumentBuilder builder = new DocumentBuilder();
Style indentedCode = builder.Document.Styles.Add(StyleType.Paragraph, "IndentedCode");
builder.ParagraphFormat.Style = indentedCode;
builder.Writeln("This is an indented code");
Fenced Code
``` c#
if ()
then
else
```
ParagraphFormat.StyleName = “FencedCode[.][info string]”
Про нас [.] і [info string] необов’язково
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// Use a document builder to add content to the document.
DocumentBuilder builder = new DocumentBuilder();
Style fencedCode = builder.Document.Styles.Add(StyleType.Paragraph, "FencedCode");
builder.ParagraphFormat.Style = fencedCode;
builder.Writeln("This is an fenced code");
Style fencedCodeWithInfo = builder.Document.Styles.Add(StyleType.Paragraph, "FencedCode.C#");
builder.ParagraphFormat.Style = fencedCodeWithInfo;
builder.Writeln("This is a fenced code with info string");

Комплексні контейнери

Таблиця нижче показує приклади використання Markdown Комплексні контейнери в Aspose.Words:

Markdown Головна Aspose.Words
Quote
> quote,
>> nested quote
ParagraphFormat.StyleName = “Quote[some suffix]”
Суфікс в назві стилю необов’язково, але Aspose.Words імпортер використовує замовлені номери 1, 2, 3, …. в разі необрізних котирування.
Ведуться ведучі стилі
 // Use a document builder to add content to the document.
DocumentBuilder builder = new DocumentBuilder();

// By default a document stores blockquote style for the first level.
builder.ParagraphFormat.StyleName = "Quote";
builder.Writeln("Blockquote");

// Create styles for nested levels through style inheritance.
Style quoteLevel2 = builder.Document.Styles.Add(StyleType.Paragraph, "Quote1");
builder.ParagraphFormat.Style = quoteLevel2;
builder.Document.Styles["Quote1"].BaseStyleName = "Quote";
builder.Writeln("1. Nested blockquote"); 
BulletedList
- Item 1
- Item 2
- Item 2a
- Item 2b
Списки буклетів представлені за допомогою абзацу:
ListFormat.ApplyBulletDefault()
Ви можете бути 3 види бюлетенів. Вони розрізняються лише в форматі нумерації першого рівня. Це: ‘-’, ‘+’ або ‘*’ відповідно
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// Use a document builder to add content to the document.
DocumentBuilder builder = new DocumentBuilder();
builder.ListFormat.ApplyBulletDefault();
builder.ListFormat.List.ListLevels[0].NumberFormat = "-";
builder.Writeln("Item 1");
builder.Writeln("Item 2");
builder.ListFormat.ListIndent();
builder.Writeln("Item 2a");
builder.Writeln("Item 2b");
OrderedList
1. Item 1
2. Item 2
1) Item 2a
2) Item 2b
Замовлені списки представлені за допомогою абзаців:
ListFormat.ApplyNumberDefault()
Відмітки формату 2: “.” та “)” Маркувальник за замовчуванням “.”
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.ListFormat.ApplyBulletDefault();
builder.ListFormat.List.ListLevels[0].NumberFormat = $"{(char) 0}.";
builder.ListFormat.List.ListLevels[1].NumberFormat = $"{(char) 1}.";

builder.Writeln("Item 1");
builder.Writeln("Item 2");

builder.ListFormat.ListIndent();

builder.Writeln("Item 2a");
builder.Writeln("Item 2b"); 

Столи

Aspose.Words також дозволяє перевести таблиці в DOM, як показано нижче:

Markdown Головна Aspose.Words
Table
й
б<br />до
 // Use a document builder to add content to the document.
DocumentBuilder builder = new DocumentBuilder();

// Add the first row.
builder.InsertCell();
builder.Writeln("a");
builder.InsertCell();
builder.Writeln("b");

// Add the second row.
builder.InsertCell();
builder.Writeln("c");
builder.InsertCell();
builder.Writeln("d"); 

Дивитися ще