Traduci Markdown in Document Object Model (DOM)

Per leggere, manipolare e modificare in modo programmatico il contenuto e la formattazione di un documento, è necessario tradurlo in Aspose.Words Document Object Model (DOM).

A differenza dei documenti Word, Markdown non è conforme al DOM descritto nel Aspose.Words Modello a oggetti documento (DOM) articolo. Tuttavia, Aspose.Words fornisce il proprio meccanismo per tradurre i documenti Markdown in DOM e viceversa, in modo da poter lavorare con successo con i loro elementi come la formattazione del testo, le tabelle, le intestazioni e altri.

Questo articolo spiega come le varie funzionalità di markdown possono essere tradotte in Aspose.Words DOM e di nuovo in formato Markdown.

Complessità della traduzione Markdown – DOM – Markdown

La principale difficoltà di questo meccanismo non è solo quella di tradurre Markdown in DOM, ma anche di eseguire la trasformazione inversa – per salvare il documento nel formato Markdown con una perdita minima. Ci sono elementi, come le virgolette multilivello, per i quali la trasformazione inversa non è banale.

Il nostro motore di traduzione consente agli utenti non solo di lavorare con elementi complessi in un documento Markdown esistente, ma anche di creare il proprio documento in formato Markdown con la struttura originale da zero. Per creare vari elementi, è necessario utilizzare stili con nomi specifici in base a determinate regole descritte più avanti in questo articolo. Tali stili possono essere creati a livello di programmazione.

Principi comuni di traduzione

Usiamo la formattazione Font per i blocchi in linea. Quando non c’è corrispondenza diretta per una funzione Markdown in Aspose.Words DOM, usiamo uno stile di carattere con un nome che inizia da alcune parole speciali.

Per i blocchi contenitore, usiamo l’ereditarietà dello stile per indicare le funzionalità annidate Markdown. In questo caso, anche quando non ci sono caratteristiche nidificate, usiamo anche stili di paragrafo con un nome che inizia da alcune parole speciali.

Gli elenchi puntati e ordinati sono anche blocchi contenitore in Markdown. Il loro nesting è rappresentato in DOM allo stesso modo di tutti gli altri blocchi contenitore usando l’ereditarietà dello stile. Tuttavia, inoltre, gli elenchi in DOM hanno una formattazione numerica corrispondente in stile elenco o formattazione di paragrafo.

Blocchi in linea

Usiamo la formattazione Font quando traduciamo le funzionalità Bold, Italic o Strikethrough inline markdown.

Funzione Markdown 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");

Usiamo uno stile di carattere con un nome che inizia dalla parola InlineCode, seguito da un punto opzionale (.) e un numero di backticks (`) per la funzione InlineCode. Se un numero di backtick viene perso, verrà utilizzato un backtick per impostazione predefinita.

Funzione Markdown 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>
La classe FieldHyperlink.
Link
[link text](url)
[link text](<url>"title")
[link text](url 'title')
[link text](url (title))
La classe FieldHyperlink.
Image
![](url)
![alt text](<url>"title")
![alt text](url ‘title’)
![alt text](url (title))
La classe 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);

Blocchi contenitore

Un documento è una sequenza di blocchi contenitore come intestazioni, paragrafi, elenchi, virgolette e altri. I blocchi contenitore possono essere suddivisi in classi 2: blocchi foglia e Contenitori complessi. I blocchi foglia possono contenere solo contenuti in linea. I contenitori complessi, a loro volta, possono contenere altri blocchi contenitore, inclusi i blocchi foglia.

Blocchi foglia

La tabella seguente mostra esempi di utilizzo dei blocchi foglia Markdown in Aspose.Words:

Funzione Markdown Aspose.Words
HorizontalRule
-----
Questo è un paragrafo semplice con una forma corrispondente 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"), dove (1<= E <= 9).
Questo è tradotto in uno stile incorporato e dovrebbe essere esattamente del modello specificato (non sono consentiti suffissi o prefissi).
Altrimenti, sarà solo un paragrafo regolare con uno stile corrispondente.
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]"), basato sullo stile "Heading N".
Se (N > = 2), allora verrà usato "Heading 2", altrimenti "Heading 1".
Qualsiasi suffisso è consentito, ma l’importatore Aspose.Words utilizza rispettivamente i numeri “1” e" 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]")
[.] e [info string] sono facoltativi.
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");

Contenitori complessi

La tabella seguente mostra esempi di utilizzo di contenitori complessi Markdown in Aspose.Words:

Funzione Markdown Aspose.Words
Quote
> quote,
>> nested quote
get_ParagraphFormat()->set_StyleName(u"Quote[some suffix]")
Il suffisso in nome stile è facoltativo ,ma Aspose.Words importatore utilizza i numeri ordinati1, 2, 3, …. in caso di citazioni annidate.
Il nesting è definito tramite gli stili ereditati.
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
Gli elenchi puntati sono rappresentati utilizzando la numerazione dei paragrafi:
get_ListFormat()->ApplyBulletDefault()
Ci possono essere 3 tipi di elenchi puntati. Sono solo diff in un formato di numerazione del primo livello. Questi sono: ‘-’, ‘+’ o ‘*’ rispettivamente.
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
Gli elenchi ordinati sono rappresentati utilizzando la numerazione dei paragrafi:
get_ListFormat()->ApplyNumberDefault()
Ci possono essere marcatori di formato numerico 2: ‘.’ e ‘)’. Il marcatore predefinito è ‘.’.
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");

Tavolo

Aspose.Words permette anche di tradurre le tabelle in DOM, come mostrato di seguito:

Funzione Markdown Aspose.Words
Table
a|b
-|-
c|d
classi Table, Row e Cell.
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");

Vedi anche