Translate Markdown to Document Object Model (DOM)

Chcete-li programově číst, manipulovat a upravovat obsah a formátování dokumentu, musíte jej přeložit do Aspose.Words objektového modelu dokumentu (DOM).

Na rozdíl od Word dokumentů Markdown neodpovídá DOM popsanému v Aspose.Words Model Objektu Dokumentu (DOM) článek. Aspose.Words však poskytuje svůj vlastní mechanismus pro překlad dokumentů Markdown do DOM a zpět, abychom mohli úspěšně pracovat s jejich prvky, jako je formátování textu, tabulky, záhlaví a další.

Tento článek vysvětluje, jak lze různé funkce markdown přeložit do Aspose.Words DOM a zpět do formátu Markdown.

Složitost překladu Markdown – DOM – Markdown

Hlavním problémem tohoto mechanismu je nejen přeložit Markdown na DOM, ale také provést reverzní transformaci – uložit dokument zpět do formátu Markdown s minimální ztrátou. Existují prvky, jako jsou víceúrovňové uvozovky, pro které není reverzní transformace triviální.

Náš překladový modul umožňuje uživatelům nejen pracovat se složitými prvky v existujícím dokumentu Markdown, ale také vytvářet vlastní dokument ve formátu Markdown s původní strukturou od nuly. Chcete-li vytvořit různé prvky, musíte použít styly se specifickými názvy podle určitých pravidel popsaných dále v tomto článku. Takové styly lze vytvářet programově.

Společné Principy Překladu

Pro vložené bloky používáme formátování Font. Pokud neexistuje přímá korespondence pro funkci Markdown v Aspose.Words DOM, použijeme znakový styl s názvem, který začíná některými speciálními slovy.

U kontejnerových bloků používáme dědičnost stylů k označení vnořených funkcí Markdown. V tomto případě, i když neexistují žádné vnořené funkce, používáme také styly odstavců s názvem, který začíná některými speciálními slovy.

Seznamy s odrážkami a seřazené seznamy jsou také bloky kontejnerů v Markdown. Jejich vnoření je reprezentováno v DOM stejným způsobem jako u všech ostatních kontejnerových bloků pomocí dědičnosti stylů. Seznamy v DOM však navíc odpovídaly formátování čísel buď ve stylu seznamu, nebo ve formátování odstavců.

Inline Bloky

Při překladu funkcí Bold, Italic nebo Strikethrough inline markdown používáme formátování Font.

Markdown funkce Aspose.Words
Bold
**bold text**
get_Font()->set_Bold(true)
For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// Use a document builder to add content to the document.
auto builder = System::MakeObject<DocumentBuilder>();
// Make the text Bold.
builder->get_Font()->set_Bold(true);
builder->Writeln(u"This text will be Bold");
Italic
*italic text*
get_Font()->set_Italic(true)
For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// Use a document builder to add content to the document.
auto builder = System::MakeObject<DocumentBuilder>();
// Make the text Italic.
builder->get_Font()->set_Italic(true);
builder->Writeln(u"This text will be Italic");
Strikethrough
~Strikethrough text~
get_Font()->set_StrikeThrough(true)
For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// Use a document builder to add content to the document.
auto builder = System::MakeObject<DocumentBuilder>();
// Make the text Strikethrough.
builder->get_Font()->set_StrikeThrough(true);
builder->Writeln(u"This text will be Strikethrough");

Používáme znakový styl s názvem, který začíná od slova InlineCode, následovaný volitelnou tečkou (.) a řadou zpětných tlačítek (`) pro funkci InlineCode. Pokud je vynechán počet backticků, bude ve výchozím nastavení použit jeden backtick.

Markdown funkce Aspose.Words
InlineCode
**inline code**
get_Font()->set_StyleName(u"InlineCode[.][N]")
For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// Use a document builder to add content to the document.
auto builder = System::MakeObject<DocumentBuilder>();
// Number of backticks is missed, one backtick will be used by default.
auto inlineCode1BackTicks = builder->get_Document()->get_Styles->Add(StyleType::Character, u"InlineCode");
builder->get_Font()->set_Style(inlineCode1BackTicks);
builder->Writeln(u"Text with InlineCode style with 1 backtick");
// There will be 3 backticks.
auto inlineCode3BackTicks = builder->get_Document()->get_Styles->Add(StyleType::Character, u"InlineCode.3");
builder->get_Font()->set_Style(inlineCode3BackTicks);
builder->Writeln(u"Text with InlineCode style with 3 backtick");
Autolink
<scheme://domain.com>
<email@domain.com>
Třída FieldHyperlink.
Link
[link text](url)
[link text](<url>"title")
[link text](url 'title')
[link text](url (title))
Třída FieldHyperlink.
Image
![](url)
![alt text](<url>"title")
![alt text](url ‘title’)
![alt text](url (title))
Třída Shape.
For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// Use a document builder to add content to the document.
auto doc = System::MakeObject<Document>();
auto builder = System::MakeObject<DocumentBuilder>(doc);
// Insert image.
auto shape = System::MakeObject<Shape>(doc, ShapeType::Image);
shape->set_WrapType(WrapType::Inline);
shape->get_ImageData()->set_SourceFullName(u"/attachment/1456/pic001.png");
shape->get_ImageData()->set_Title(u"title");
builder->InsertNode(shape);

Kontejnerové Bloky

Dokument je posloupnost kontejnerových bloků, jako jsou nadpisy, odstavce, seznamy, uvozovky a další. Kontejnerové bloky lze rozdělit do 2 tříd: listové bloky a složité kontejnery. Listové bloky mohou obsahovat pouze vložený obsah. Složité kontejnery zase mohou obsahovat další kontejnerové bloky, včetně listových bloků.

Listové Bloky

Níže uvedená tabulka ukazuje příklady použití Markdown listových bloků v Aspose.Words:

Markdown funkce Aspose.Words
HorizontalRule
-----
Jedná se o jednoduchý odstavec s odpovídajícím tvarem HorizontalRule:
DocumentBuilder::InsertHorizontalRule()
For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// Use a document builder to add content to the document.
auto builder = System::MakeObject<DocumentBuilder>();
// Insert horizontal rule.
builder->InsertHorizontalRule();
ATX Heading
# H1, ## H2, ### H3…
get_ParagraphFormat()->set_StyleName(u"Heading N"), kde (1<= N <= 9).
To je přeloženo do vestavěného stylu a mělo by být přesně zadaného vzoru (nejsou povoleny žádné přípony ani předpony).
Jinak to bude jen běžný odstavec s odpovídajícím stylem.
For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// Use a document builder to add content to the document.
auto builder = System::MakeObject<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->get_Font()->set_Bold(false);
builder->get_Font()->set_Italic(false);
builder->get_ParagraphFormat()->set_StyleName(u"Heading 1");
builder->Writeln(u"This is an H1 tag");
Setext Heading
=== (if Heading level 1),
--- (if Heading level 2)
get_ParagraphFormat->set_StyleName(u"SetextHeading[some suffix]"), na základě stylu' Nadpis N'.
Pokud (N >= 2), použije se ‘Heading 2’, jinak ‘Heading 1’.
Jakákoli Přípona je povolena ,ale Aspose.Words dovozce používá čísla “1” a “2”.
For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// Use a document builder to add content to the document.
auto doc = System::MakeObject<Document>();
auto builder = System::MakeObject<DocumentBuilder>(doc);
builder->get_ParagraphFormat()->set_StyleName(u"Heading 1");
builder->Writeln(u"This is an H1 tag");
// Reset styles from the previous paragraph to not combine styles between paragraphs.
builder->get_Font()->set_Bold(false);
builder->get_Font()->set_Italic(false);
auto setexHeading1 = builder->get_Document()->get_Styles->Add(StyleType::Paragraph, u"SetextHeading1");
builder->get_ParagraphFormat()->set_Style(setexHeading1);
doc->get_Styles()->idx_get(u"SetextHeading1")->set_BaseStyleName(u"Heading 1");
builder->Writeln(u"Setext Heading level 1");
builder->get_ParagraphFormat()->set_Style(doc->get_Styles()->idx_get(u"Heading 3"));
builder->Writeln(u"This is an H3 tag");
// Reset styles from the previous paragraph to not combine styles between paragraphs.
builder->get_Font()->set_Bold(false);
builder->get_Font()->set_Italic(false);
auto setexHeading2 = builder->get_Document()->get_Styles->Add(StyleType::Paragraph, u"SetextHeading2");
builder->get_ParagraphFormat()->set_Style(setexHeading2);
doc->get_Styles()->idx_get(u"SetextHeading2")->set_BaseStyleName(u"Heading 3");
// Setex heading level will be reset to 2 if the base paragraph has a Heading level greater than 2.
builder->Writeln(u"Setext Heading level 2");
Indented Code get_ParagraphFormat->set_StyleName(u"IndentedCode[some suffix]")
For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// Use a document builder to add content to the document.
auto doc = System::MakeObject<Document>();
auto builder = System::MakeObject<DocumentBuilder>(doc);
auto indentedCode = builder->get_Document()->get_Styles->Add(StyleType::Paragraph, u"IndentedCode");
builder->get_ParagraphFormat()->set_StyleName(indentedCode);
builder->Writeln(u"This is an indented code");
Fenced Code
``` c#
if ()
then
else
```
get_ParagraphFormat()->set_StyleName(u"FencedCode[.][info string]")
[.] a [info string] jsou volitelné.
For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// Use a document builder to add content to the document.
auto doc = System::MakeObject<Document>();
auto builder = System::MakeObject<DocumentBuilder>(doc);
auto fencedCode = builder->get_Document()->get_Styles->Add(StyleType::Paragraph, u"FencedCode");
builder->get_ParagraphFormat()->set_StyleName(fencedCode);
builder->Writeln(u"This is an fenced code");
auto fencedCodeWithInfo = builder->get_Document()->get_Styles->Add(StyleType::Paragraph, u"FencedCode.C#");
builder->get_ParagraphFormat()->set_StyleName(fencedCodeWithInfo);
builder->Writeln(u"This is a fenced code with info string");

Komplexní Kontejnery

Níže uvedená tabulka ukazuje příklady použití Markdown komplexních kontejnerů v Aspose.Words:

Markdown funkce Aspose.Words
Quote
> quote,
>> nested quote
get_ParagraphFormat()->set_StyleName(u"Quote[some suffix]")
přípona v názvu stylu je volitelná ,ale Aspose.Words dovozce používá seřazená čísla 1, 2, 3, …. v případě vnořených uvozovek.
Vnoření je definováno pomocí zděděných stylů.
For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// Use a document builder to add content to the document.
auto doc = System::MakeObject<Document>();
auto builder = System::MakeObject<DocumentBuilder>(doc);
// By default a document stores blockquote style for the first level.
builder->get_ParagraphFormat()->set_StyleName(u"Quote");
builder->Writeln(u"Blockquote");
// Create styles for nested levels through style inheritance.
auto quoteLevel2 = builder->get_Document()->get_Styles->Add(StyleType::Paragraph, u"Quote1");
builder->get_ParagraphFormat()->set_StyleName(quoteLevel2);
builder->get_Document()->get_Styles->idx_get(u"Quote1")->set_BaseStyleName(u"Quote");
builder->Writeln(u"1. Nested blockquote");
BulletedList
- Item 1
- Item 2
- Item 2a
- Item 2b
Seznamy s odrážkami jsou reprezentovány pomocí číslování odstavců:
get_ListFormat()->ApplyBulletDefault()
mohou existovat 3 typy seznamů s odrážkami. Liší se pouze ve formátu číslování úplně první úrovně. Jsou to: ‘-’, ‘+’ nebo ‘*’.
For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// Use a document builder to add content to the document.
auto builder = System::MakeObject<DocumentBuilder>();
builder->get_ListFormat()->ApplyBulletDefault();
builder->get_ListFormat()->get_List()->get_ListLevels()->idx_get(0)->set_NumberFormat(u"-");
builder->Writeln(u"Item 1");
builder->Writeln(u"Item 2");
builder->get_ListFormat()->ListIndent();
builder->Writeln(u"Item 2a");
builder->Writeln(u"Item 2b");
OrderedList
1. Item 1
2. Item 2
1) Item 2a
2) Item 2b
Uspořádané seznamy jsou reprezentovány pomocí číslování odstavců:
get_ListFormat()->ApplyNumberDefault()
mohou existovat 2 značky formátu čísel: ‘.’ a ‘)’. Výchozí značka je ‘.’.
For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// Use a document builder to add content to the document.
auto builder = System::MakeObject<DocumentBuilder>();
builder->get_ListFormat()->ApplyBulletDefault();
builder->get_ListFormat()->get_List()->get_ListLevels()->idx_get(0)->set_NumberFormat(System::String::Format(u"{0}.", (char16_t)0));
builder->get_ListFormat()->get_List()->get_ListLevels()->idx_get(1)->set_NumberFormat(System::String::Format(u"{0}.", (char16_t)1));
builder->Writeln(u"Item 1");
builder->Writeln(u"Item 2");
builder->get_ListFormat()->ListIndent();
builder->Writeln(u"Item 2a");
builder->Writeln(u"Item 2b");

Tabulka

Aspose.Words také umožňuje překládat tabulky do DOM, Jak je uvedeno níže:

Markdown funkce Aspose.Words
Table
a|b
-|-
c|d
Table, Row a Cell třídy.
For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// Use a document builder to add content to the document.
auto builder = System::MakeObject<DocumentBuilder>();
// Add the first row.
builder->InsertCell();
builder->Writeln(u"a");
builder->InsertCell();
builder->Writeln(u"b");
// Add the second row.
builder->InsertCell();
builder->Writeln(u"c");
builder->InsertCell();
builder->Writeln(u"d");

Vidět