Робота з документами

У статті ми дізнаємось, які параметри можуть бути корисними для роботи з текстовим документом Aspose.Wordsй Будь ласка, зауважте, що це не повний список доступних варіантів, але тільки приклад роботи з деякими з них.

Додати бі-прямий Марки

Ви можете використовувати add_bidi_marks Введіть номер мобільного, який Ви вказали при укладаннi договору з банком - для ідентифікації. Aspose.Words вставки Unicode Character ‘RIGHT-TO-LEFT MARK’ (U+200F) перед кожним двостороннім Run у тексті. Ця опція відповідає параметру “Додати двосторонні позначки” у діалоговому вікні перетворення файлів MS Word, коли ви експортуєте у формат Plain Text. Зауважте, що мова йде про діалог тільки в тому випадку, якщо будь-які з арабських або івритових мов редагування додаються в MS Word.

Приклад наступного коду показує, як використовувати add_bidi_marks майно. Значення за замовчуванням цього майна False:

# For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Python-via-.NET
doc = aw.Document()
builder = aw.DocumentBuilder(doc)
builder.writeln("Hello world!")
builder.paragraph_format.bidi = True
builder.writeln("שלום עולם!")
builder.writeln("مرحبا بالعالم!")
saveOptions = aw.saving.TxtSaveOptions()
saveOptions.add_bidi_marks = True
doc.save(docs_base.artifacts_dir + "WorkingWithTxtSaveOptions.add_bidi_marks.txt", saveOptions)

Визначте елементи списку під час завантаження TXT

Aspose.Words може імпортувати список елементу текстового файлу як номери списку або звичайний текст у його типовій моделі об’єкта документа. Про нас detect_numbering_with_whitespaces майно дозволяє вказати, як зареєстровані елементи списку визнаються, коли документ імпортується зі звичайного формату тексту:

  • Ім’я * Якщо цей варіант встановлюється True, У списку також використовуються білі простори: алгоритм розпізнавання списку для кількості арабських стилів (1., 1.1.2.) використання як білих просторів, так і точок ().
  • Ім’я * Якщо цей варіант встановлюється False, Алгоритм розпізнавання списків виявляє пункти списку, коли кінцеві числа списку з точки зору, правою дужкою або символами кулі (наприклад, “*”, “-” або “o”).

Приклад коду показує, як використовувати цю властивість:

# For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Python-via-.NET
# Create a plaintext document in the form of a string with parts that may be interpreted as lists.
# Upon loading, the first three lists will always be detected by Aspose.words,
# and List objects will be created for them after loading.
textDoc = """Full stop delimiters:\n
1. First list item 1\n
2. First list item 2\n
3. First list item 3\n\n
Right bracket delimiters:\n
1) Second list item 1\n
2) Second list item 2\n
3) Second list item 3\n\n
Bullet delimiters:\n
• Third list item 1\n
• Third list item 2\n
• Third list item 3\n\n
Whitespace delimiters:\n
1 Fourth list item 1\n
2 Fourth list item 2\n
3 Fourth list item 3"""
# The fourth list, with whitespace inbetween the list number and list item contents,
# will only be detected as a list if "DetectNumberingWithWhitespaces" in a LoadOptions object is set to true,
# to avoid paragraphs that start with numbers being mistakenly detected as lists.
loadOptions = aw.loading.TxtLoadOptions()
loadOptions.detect_numbering_with_whitespaces = True
# Load the document while applying LoadOptions as a parameter and verify the result.
doc = aw.Document(io.BytesIO(textDoc.encode("utf-8")), loadOptions)
doc.save(docs_base.artifacts_dir + "WorkingWithTxtLoadOptions.detect_numbering_with_whitespaces.docx")

Ручка Провідні та підйомні місця Під час завантаження TXT

Ви можете контролювати спосіб обробки провідних і причепів при завантаженні TXT файл. Провідні простори можуть бути оброблені, збережені або перетворені в відступ і причепні приміщення можуть бути оброблені або збережені.

Наприклад, наступний код показує, як обрізати провідні та причіпні місця при імпорті TXT файл:

# For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Python-via-.NET
textDoc = " Line 1 \n" + " Line 2 \n" + " Line 3 "
loadOptions = aw.loading.TxtLoadOptions()
loadOptions.leading_spaces_options = aw.loading.TxtLeadingSpacesOptions.TRIM
loadOptions.trailing_spaces_options = aw.loading.TxtTrailingSpacesOptions.TRIM
f = io.BytesIO(textDoc.encode("utf-8"))
doc = aw.Document(f, loadOptions)
doc.save(docs_base.artifacts_dir + "WorkingWithTxtLoadOptions.handle_spaces_options.docx")

Видалити документ Налаштування тексту

Aspose.Words Послуги document_direction нерухомість TxtLoadOptions клас для виявлення текстового напрямку (RTL / LTR) в документі. Це майно встановлює або отримує текстові напрямки документа, що надаються в DocumentDirection заохочення. Значення за замовчуванням зліва направо.

Приклад наступного коду показує, як виявити текстовий напрямок документа при імпорті файлу TXT:

# For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Python-via-.NET
loadOptions = aw.loading.TxtLoadOptions()
loadOptions.document_direction = aw.loading.DocumentDirection.AUTO
doc = aw.Document(docs_base.my_dir + "Hebrew text.txt", loadOptions)
paragraph = doc.first_section.body.first_paragraph
print(paragraph.paragraph_format.bidi)
doc.save(docs_base.artifacts_dir + "WorkingWithTxtLoadOptions.document_text_direction.docx")

Експорт заголовка та нижній колонтитул у вихідному TXT

Якщо ви хочете експортувати заголовок і нижній колонтитул у вихідному документі TXT, ви можете використовувати export_headers_footers_mode майно. Ця властивість вказує на те, як заголовки та нижній колонтитули експортуються в звичайний формат тексту.

Приклад коду показує, як експортувати заголовки та нижній колонтитул до звичайного формату тексту:

doc = aw.Document(docs_base.my_dir + "Document.docx")

options = aw.saving.TxtSaveOptions()
options.save_format = aw.SaveFormat.TEXT

# All headers and footers are placed at the very end of the output document.
options.export_headers_footers_mode = aw.saving.TxtExportHeadersFootersMode.ALL_AT_END
doc.save(docs_base.artifacts_dir + "WorkingWithTxtSaveOptions.export_headers_footers_mode_A.txt", options)

# Only primary headers and footers are exported at the beginning and end of each section.
options.export_headers_footers_mode = aw.saving.TxtExportHeadersFootersMode.PRIMARY_ONLY
doc.save(docs_base.artifacts_dir + "WorkingWithTxtSaveOptions.export_headers_footers_mode_B.txt", options)

# No headers and footers are exported.
options.export_headers_footers_mode = aw.saving.TxtExportHeadersFootersMode.NONE
doc.save(docs_base.artifacts_dir + "WorkingWithTxtSaveOptions.export_headers_footers_mode_C.txt", options)

Виявлення експортного списку на виході TXT

Aspose.Words Введення TxtListIndentation клас, який дозволяє визначити, як рівень списку відступаються при експорті до звичайного текстового формату. Під час роботи TxtSaveOption, Про нас list_indentation майно надається, щоб вказати характер, який буде використовуватися для рівнів відступу і підрахунку, вказавши, скільки символів використовувати як відступ на один рівень списку. Значення за замовчуванням для властивості персонажа ‘\0’ вказує на те, що немає відступу. Для підрахунку майна, значення за замовчуванням 0, що означає відсутність відступу.

Використання символів вкладки

Приклад коду показує, як експортувати рівні списку за допомогою символів вкладки:

# For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Python-via-.NET
doc = aw.Document()
builder = aw.DocumentBuilder(doc)
# Create a list with three levels of indentation.
builder.list_format.apply_number_default()
builder.writeln("Item 1")
builder.list_format.list_indent()
builder.writeln("Item 2")
builder.list_format.list_indent()
builder.write("Item 3")
saveOptions = aw.saving.TxtSaveOptions()
saveOptions.list_indentation.count = 1
#saveOptions.list_indentation.character = '\t'
doc.save(docs_base.artifacts_dir + "WorkingWithTxtSaveOptions.use_tab_character_per_level_for_list_indentation.txt", saveOptions)

Використання космічних символів

Приклад коду показує, як експортувати рівні списку за допомогою символів простору:

# For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Python-via-.NET
doc = aw.Document()
builder = aw.DocumentBuilder(doc)
# Create a list with three levels of indentation.
builder.list_format.apply_number_default()
builder.writeln("Item 1")
builder.list_format.list_indent()
builder.writeln("Item 2")
builder.list_format.list_indent()
builder.write("Item 3")
saveOptions = aw.saving.TxtSaveOptions()
saveOptions.list_indentation.count = 3
#saveOptions.list_indentation.character = ' '
doc.save(docs_base.artifacts_dir + "WorkingWithTxtSaveOptions.use_space_character_per_level_for_list_indentation.txt", saveOptions)