Поделиться через


Word.Paragraph class

Представляет один абзац в выделении, диапазоне, элементе управления содержимым или тексте документа.

Extends

Комментарии

[ Набор API: WordApi 1.1 ]

Свойства

alignment

Задает выравнивание абзаца. Возможные значения: left, centered, right и justified.

contentControls

Возвращает коллекцию объектов элементов управления содержимым в абзаце.

context

Контекст запроса, связанный с объектом . Это соединяет процесс надстройки с процессом ведущего приложения Office.

firstLineIndent

Задает значение (в пунктах) для первой строки или отступа. Для установки отступа первой строки укажите положительное значение и используйте отрицательное значение, чтобы задать выступ.

font

Возвращает формат текста абзаца. Используйте это свойство для получения и задания имени, размера, цвета и других свойств шрифта.

inlinePictures

Возвращает коллекцию объектов InlinePicture в абзаце. Коллекция не включает плавающие изображения.

leftIndent

Задает значение левого отступа (в пунктах) для абзаца.

lineSpacing

Задает междустрочный интервал (в точках) для указанного абзаца. В пользовательском интерфейсе Word это значение делится на 12.

lineUnitAfter

Указывает интервал в строках сетки после абзаца.

lineUnitBefore

Указывает интервал в строках сетки перед абзацем.

outlineLevel

Задает уровень структуры для абзаца.

parentContentControl

Возвращает элемент управления содержимым, содержащий абзац. Выдает ошибку ItemNotFound , если родительского элемента управления содержимым нет.

rightIndent

Задает значение отступа вправо (в пунктах) для абзаца.

spaceAfter

Задает интервал (в точках) после абзаца.

spaceBefore

Задает интервал (в пунктах) перед абзацем.

style

Задает имя стиля абзаца. Используйте это свойство для пользовательских стилей и локализованных имен стилей. Чтобы использовать встроенные стили, поддерживающие несколько языковых стандартов, применяйте свойство styleBuiltIn.

text

Возвращает текст абзаца.

Методы

clear()

Очищает содержимое объекта абзаца. Пользователь может отменить операцию для очищенного содержимого.

delete()

Удаляет абзац и его содержимое из документа.

getHtml()

Возвращает HTML-представление объекта абзаца. При отображении на веб-странице или в средстве просмотра HTML форматирование будет близко, но не точно совпадает с форматированием документа. Этот метод не возвращает один и тот же HTML-код для одного документа на разных платформах (Windows, Mac, Word в Интернете и т. д.). Если вам нужна точную точность или согласованность на разных платформах, используйте Paragraph.getOoxml() и преобразуйте возвращенный XML-код в HTML.

getOoxml()

Возвращает OOXML-представление объекта абзаца.

insertBreak(breakType, insertLocation)

Вставляет разрыв в указанном расположении в основном документе.

insertContentControl(contentControlType)

Заключает объект Paragraph в элемент управления содержимым.

insertFileFromBase64(base64File, insertLocation)

Вставляет документ в абзац в указанном расположении.

insertHtml(html, insertLocation)

Вставляет HTML в абзац в указанном расположении.

insertInlinePictureFromBase64(base64EncodedImage, insertLocation)

Вставляет рисунок в абзац в указанном расположении.

insertOoxml(ooxml, insertLocation)

Вставляет OOXML в абзац в указанном расположении.

insertParagraph(paragraphText, insertLocation)

Вставляет абзац в указанном расположении.

insertText(text, insertLocation)

Вставляет текст в абзац в указанном расположении.

load(options)

Добавляет в очередь команду для загрузки указанных свойств объекта. Перед чтением свойств требуется вызвать метод context.sync().

load(propertyNames)

Добавляет в очередь команду для загрузки указанных свойств объекта. Перед чтением свойств требуется вызвать метод context.sync().

load(propertyNamesAndPaths)

Добавляет в очередь команду для загрузки указанных свойств объекта. Перед чтением свойств требуется вызвать метод context.sync().

search(searchText, searchOptions)

Выполняет поиск с указанным SearchOptions в области объекта абзаца. Результат поиска — это коллекция объектов диапазона.

select(selectionMode)

Выбирает абзац и переходит к нему в пользовательском интерфейсе Word.

select(selectionModeString)

Выбирает абзац и переходит к нему в пользовательском интерфейсе Word.

set(properties, options)

Задает несколько свойств объекта одновременно. Можно передать обычный объект с соответствующими свойствами или другой объект API того же типа.

set(properties)

Задает несколько свойств объекта одновременно на основе существующего загруженного объекта.

toJSON()

Переопределяет метод JavaScript toJSON() , чтобы обеспечить более полезные выходные данные при передаче объекта API в JSON.stringify(). (JSON.stringifyв свою очередь вызывает toJSON метод переданного ему объекта.) В то время как исходный Word.Paragraph объект является объектом API, toJSON метод возвращает обычный объект JavaScript (типизированный как Word.Interfaces.ParagraphData), который содержит неглубокие копии всех загруженных дочерних свойств из исходного объекта.

track()

Отслеживает объект для автоматической корректировки с учетом окружающих изменений в документе. Этот вызов является сокращением для context.trackedObjects.add(thisObject). Если вы используете этот объект в вызовах .sync и вне последовательного выполнения пакета .run и получаете ошибку InvalidObjectPath при задании свойства или вызове метода для объекта, необходимо добавить объект в отслеживаемую коллекцию объектов при первом создании объекта. Если этот объект является частью коллекции, следует также отслеживать родительскую коллекцию.

untrack()

Освобождает память, связанную с этим объектом, если он ранее отслеживался. Этот вызов является сокращенным для context.trackedObjects.remove(thisObject). Наличие большого количества отслеживаемых объектов замедляет ведущее приложение, поэтому не забывайте освобождать любые добавленные объекты после завершения их использования. Вызов потребуется выполнить context.sync() до того, как выпуск памяти вступит в силу.

Сведения о свойстве

alignment

Задает выравнивание абзаца. Возможные значения: left, centered, right и justified.

alignment: Word.Alignment | "Mixed" | "Unknown" | "Left" | "Centered" | "Right" | "Justified";

Значение свойства

Word.Alignment | "Mixed" | "Unknown" | "Left" | "Centered" | "Right" | "Justified"

Комментарии

[ Набор API: WordApi 1.1 ]

Примеры

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/25-paragraph/paragraph-properties.yaml

await Word.run(async (context) => {
  // Center last paragraph alignment.
  context.document.body.paragraphs.getLast().alignment = "Centered";

  await context.sync();
});

contentControls

Возвращает коллекцию объектов элементов управления содержимым в абзаце.

readonly contentControls: Word.ContentControlCollection;

Значение свойства

Комментарии

[ Набор API: WordApi 1.1 ]

context

Контекст запроса, связанный с объектом . Это соединяет процесс надстройки с процессом ведущего приложения Office.

context: RequestContext;

Значение свойства

firstLineIndent

Задает значение (в пунктах) для первой строки или отступа. Для установки отступа первой строки укажите положительное значение и используйте отрицательное значение, чтобы задать выступ.

firstLineIndent: number;

Значение свойства

number

Комментарии

[ Набор API: WordApi 1.1 ]

font

Возвращает формат текста абзаца. Используйте это свойство для получения и задания имени, размера, цвета и других свойств шрифта.

readonly font: Word.Font;

Значение свойства

Комментарии

[ Набор API: WordApi 1.1 ]

inlinePictures

Возвращает коллекцию объектов InlinePicture в абзаце. Коллекция не включает плавающие изображения.

readonly inlinePictures: Word.InlinePictureCollection;

Значение свойства

Комментарии

[ Набор API: WordApi 1.1 ]

leftIndent

Задает значение левого отступа (в пунктах) для абзаца.

leftIndent: number;

Значение свойства

number

Комментарии

[ Набор API: WordApi 1.1 ]

Примеры

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/25-paragraph/paragraph-properties.yaml

await Word.run(async (context) => {
  // Indent the first paragraph.
  context.document.body.paragraphs.getFirst().leftIndent = 75; //units = points

  return context.sync();
});

lineSpacing

Задает междустрочный интервал (в точках) для указанного абзаца. В пользовательском интерфейсе Word это значение делится на 12.

lineSpacing: number;

Значение свойства

number

Комментарии

[ Набор API: WordApi 1.1 ]

Примеры

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/25-paragraph/paragraph-properties.yaml

await Word.run(async (context) => {
  // Adjust line spacing.
  context.document.body.paragraphs.getFirst().lineSpacing = 20;

  await context.sync();
});

lineUnitAfter

Указывает интервал в строках сетки после абзаца.

lineUnitAfter: number;

Значение свойства

number

Комментарии

[ Набор API: WordApi 1.1 ]

Примеры

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/25-paragraph/paragraph-properties.yaml

await Word.run(async (context) => {
  // Set the space (in line units) after the first paragraph.
  context.document.body.paragraphs.getFirst().lineUnitAfter = 1;

  await context.sync();
});

lineUnitBefore

Указывает интервал в строках сетки перед абзацем.

lineUnitBefore: number;

Значение свойства

number

Комментарии

[ Набор API: WordApi 1.1 ]

Примеры

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/25-paragraph/paragraph-properties.yaml

await Word.run(async (context) => {
  // Set the space (in line units) before the first paragraph.
  context.document.body.paragraphs.getFirst().lineUnitBefore = 1;

  await context.sync();
});

outlineLevel

Задает уровень структуры для абзаца.

outlineLevel: number;

Значение свойства

number

Комментарии

[ Набор API: WordApi 1.1 ]

parentContentControl

Возвращает элемент управления содержимым, содержащий абзац. Выдает ошибку ItemNotFound , если родительского элемента управления содержимым нет.

readonly parentContentControl: Word.ContentControl;

Значение свойства

Комментарии

[ Набор API: WordApi 1.1 ]

rightIndent

Задает значение отступа вправо (в пунктах) для абзаца.

rightIndent: number;

Значение свойства

number

Комментарии

[ Набор API: WordApi 1.1 ]

spaceAfter

Задает интервал (в точках) после абзаца.

spaceAfter: number;

Значение свойства

number

Комментарии

[ Набор API: WordApi 1.1 ]

Примеры

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/25-paragraph/paragraph-properties.yaml

await Word.run(async (context) => {
  // Set the space (in points) after the first paragraph.
  context.document.body.paragraphs.getFirst().spaceAfter = 20;

  await context.sync();
});

spaceBefore

Задает интервал (в пунктах) перед абзацем.

spaceBefore: number;

Значение свойства

number

Комментарии

[ Набор API: WordApi 1.1 ]

style

Задает имя стиля абзаца. Используйте это свойство для пользовательских стилей и локализованных имен стилей. Чтобы использовать встроенные стили, поддерживающие несколько языковых стандартов, применяйте свойство styleBuiltIn.

style: string;

Значение свойства

string

Комментарии

[ Набор API: WordApi 1.1 ]

Примеры

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/50-document/manage-styles.yaml

// Applies the specified style to a paragraph.
await Word.run(async (context) => {
  const styleName = $("#style-name-to-use").val() as string;
  if (styleName == "") {
    console.warn("Enter a style name to apply.");
    return;
  }

  const style: Word.Style = context.document.getStyles().getByNameOrNullObject(styleName);
  style.load();
  await context.sync();

  if (style.isNullObject) {
    console.warn(`There's no existing style with the name '${styleName}'.`);
  } else if (style.type != Word.StyleType.paragraph) {
    console.log(`The '${styleName}' style isn't a paragraph style.`);
  } else {
    const body: Word.Body = context.document.body;
    body.clear();
    body.insertParagraph(
      "Do you want to create a solution that extends the functionality of Word? You can use the Office Add-ins platform to extend Word clients running on the web, on a Windows desktop, or on a Mac.",
      "Start"
    );
    const paragraph: Word.Paragraph = body.paragraphs.getFirst();
    paragraph.style = style.nameLocal;
    console.log(`'${styleName}' style applied to first paragraph.`);
  }
});

text

Возвращает текст абзаца.

readonly text: string;

Значение свойства

string

Комментарии

[ Набор API: WordApi 1.1 ]

Примеры

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/25-paragraph/get-paragraph-on-insertion-point.yaml

await Word.run(async (context) => {
  // The collection of paragraphs of the current selection returns the full paragraphs contained in it.
  const paragraph: Word.Paragraph = context.document.getSelection().paragraphs.getFirst();
  paragraph.load("text");

  await context.sync();
  console.log(paragraph.text);
});

Сведения о методе

clear()

Очищает содержимое объекта абзаца. Пользователь может отменить операцию для очищенного содержимого.

clear(): void;

Возвращаемое значение

void

Комментарии

[ Набор API: WordApi 1.1 ]

Примеры

// Run a batch operation against the Word object model.
await Word.run(async (context) => {

    // Create a proxy object for the paragraphs collection.
    const paragraphs = context.document.body.paragraphs;

    // Queue a command to load the style property for all of the paragraphs.
    paragraphs.load('style');

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    await context.sync();

    // Queue a command to clear the contents of the first paragraph.
    paragraphs.items[0].clear();

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    await context.sync();
    console.log('Cleared the contents of the first paragraph.');
});

delete()

Удаляет абзац и его содержимое из документа.

delete(): void;

Возвращаемое значение

void

Комментарии

[ Набор API: WordApi 1.1 ]

Примеры

// Run a batch operation against the Word object model.
await Word.run(async (context) => {

    // Create a proxy object for the paragraphs collection.
    const paragraphs = context.document.body.paragraphs;

    // Queue a command to load the text property for all of the paragraphs.
    paragraphs.load('text');

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    await context.sync();

    // Queue a command to delete the first paragraph.
    paragraphs.items[0].delete();

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    await context.sync();
    console.log('Deleted the first paragraph.');
});

getHtml()

Возвращает HTML-представление объекта абзаца. При отображении на веб-странице или в средстве просмотра HTML форматирование будет близко, но не точно совпадает с форматированием документа. Этот метод не возвращает один и тот же HTML-код для одного документа на разных платформах (Windows, Mac, Word в Интернете и т. д.). Если вам нужна точную точность или согласованность на разных платформах, используйте Paragraph.getOoxml() и преобразуйте возвращенный XML-код в HTML.

getHtml(): OfficeExtension.ClientResult<string>;

Возвращаемое значение

Комментарии

[ Набор API: WordApi 1.1 ]

Примеры

// Run a batch operation against the Word object model.
await Word.run(async (context) => {

    // Create a proxy object for the paragraphs collection.
    const paragraphs = context.document.body.paragraphs;

    // Queue a command to load the style property for all of the paragraphs.
    paragraphs.load('style');

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    await context.sync();

    // Queue a set of commands to get the HTML of the first paragraph.
    const html = paragraphs.items[0].getHtml();

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    await context.sync();
    console.log('Paragraph HTML: ' + html.value);
});

getOoxml()

Возвращает OOXML-представление объекта абзаца.

getOoxml(): OfficeExtension.ClientResult<string>;

Возвращаемое значение

Комментарии

[ Набор API: WordApi 1.1 ]

Примеры

// Run a batch operation against the Word object model.
await Word.run(async (context) => {

    // Create a proxy object for the paragraphs collection.
    const paragraphs = context.document.body.paragraphs;

    // Queue a command to load the style property for the top 2 paragraphs.
    paragraphs.load({select: 'style', top: 2} );

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    await context.sync();

    // Queue a set of commands to get the OOXML of the first paragraph.
    const ooxml = paragraphs.items[0].getOoxml();

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    await context.sync();
    console.log('Paragraph OOXML: ' + ooxml.value);
});

insertBreak(breakType, insertLocation)

Вставляет разрыв в указанном расположении в основном документе.

insertBreak(breakType: Word.BreakType | "Page" | "Next" | "SectionNext" | "SectionContinuous" | "SectionEven" | "SectionOdd" | "Line", insertLocation: Word.InsertLocation.before | Word.InsertLocation.after | "Before" | "After"): void;

Параметры

breakType

Word.BreakType | "Page" | "Next" | "SectionNext" | "SectionContinuous" | "SectionEven" | "SectionOdd" | "Line"

Обязательно. Тип разрыва, который необходимо добавить в документ.

insertLocation

before | after | "Before" | "After"

Обязательно. Значение должно быть "До" или "После".

Возвращаемое значение

void

Комментарии

[ Набор API: WordApi 1.1 ]

Примеры

// Run a batch operation against the Word object model.
await Word.run(async (context) => {

    // Create a proxy object for the paragraphs collection.
    const paragraphs = context.document.body.paragraphs;

    // Queue a command to load the style property for the top 2 paragraphs.
    // We never perform an empty load. We always must request a property.
    paragraphs.load({select: 'style', top: 2} );

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    await context.sync();

    // Queue a command to get the first paragraph.
    const paragraph = paragraphs.items[0];

    // Queue a command to insert a page break after the first paragraph.
    paragraph.insertBreak(Word.BreakType.page, Word.InsertLocation.after);

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    await context.sync();
    console.log('Inserted a page break after the paragraph.');
});
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/25-paragraph/insert-line-and-page-breaks.yaml

Word.run(async (context) => {
  context.document.body.paragraphs.getFirst().insertBreak(Word.BreakType.line, "After");

  await context.sync();
  console.log("success");
});

insertContentControl(contentControlType)

Заключает объект Paragraph в элемент управления содержимым.

insertContentControl(contentControlType?: Word.ContentControlType.richText | Word.ContentControlType.plainText | Word.ContentControlType.checkBox | "RichText" | "PlainText" | "CheckBox"): Word.ContentControl;

Параметры

contentControlType

richText | plainText | checkBox | "RichText" | "PlainText" | "CheckBox"

Необязательный параметр. Тип элемента управления содержимым для вставки. Должен иметь значение "RichText", "PlainText" или "CheckBox". Значение по умолчанию — RichText.

Возвращаемое значение

Комментарии

[ Набор API: WordApi 1.1 ]

Примечание. Параметр contentControlType появился в WordApi 1.5. PlainText добавлена поддержка в WordApi 1.5. CheckBox добавлена поддержка в WordApi 1.7.

Примеры

// Run a batch operation against the Word object model.
await Word.run(async (context) => {

    // Create a proxy object for the paragraphs collection.
    const paragraphs = context.document.body.paragraphs;

    // Queue a command to load the style property for the top 2 paragraphs.
    // We never perform an empty load. We always must request a property.
    paragraphs.load({select: 'style', top: 2} );

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    await context.sync();

    // Queue a command to get the first paragraph.
    const paragraph = paragraphs.items[0];

    // Queue a command to wrap the first paragraph in a rich text content control.
    paragraph.insertContentControl();

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    await context.sync();
    console.log('Wrapped the first paragraph in a content control.');
});
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/10-content-controls/insert-and-change-content-controls.yaml

// Traverses each paragraph of the document and wraps a content control on each with either a even or odd tags.
await Word.run(async (context) => {
  let paragraphs = context.document.body.paragraphs;
  paragraphs.load("$none"); // Don't need any properties; just wrap each paragraph with a content control.

  await context.sync();

  for (let i = 0; i < paragraphs.items.length; i++) {
    let contentControl = paragraphs.items[i].insertContentControl();
    // For even, tag "even".
    if (i % 2 === 0) {
      contentControl.tag = "even";
    } else {
      contentControl.tag = "odd";
    }
  }
  console.log("Content controls inserted: " + paragraphs.items.length);

  await context.sync();
});

insertFileFromBase64(base64File, insertLocation)

Вставляет документ в абзац в указанном расположении.

insertFileFromBase64(base64File: string, insertLocation: Word.InsertLocation.replace | Word.InsertLocation.start | Word.InsertLocation.end | "Replace" | "Start" | "End"): Word.Range;

Параметры

base64File

string

Обязательно. Содержимое файла .docx в кодировке Base64.

insertLocation

replace | start | end | "Replace" | "Start" | "End"

Обязательно. Значение должно быть "Replace", "Start" или "End".

Возвращаемое значение

Комментарии

[ Набор API: WordApi 1.1 ]

Примечание. Вставка не поддерживается, если вставляемый документ содержит элемент ActiveX (вероятно, в поле формы). Рассмотрите возможность замены такого поля формы элементом управления содержимым или другим вариантом, подходящим для вашего сценария.

insertHtml(html, insertLocation)

Вставляет HTML в абзац в указанном расположении.

insertHtml(html: string, insertLocation: Word.InsertLocation.replace | Word.InsertLocation.start | Word.InsertLocation.end | "Replace" | "Start" | "End"): Word.Range;

Параметры

html

string

Обязательно. HTML-код, который необходимо вставить в абзац.

insertLocation

replace | start | end | "Replace" | "Start" | "End"

Обязательно. Значение должно быть "Replace", "Start" или "End".

Возвращаемое значение

Комментарии

[ Набор API: WordApi 1.1 ]

Примеры

// Run a batch operation against the Word object model.
await Word.run(async (context) => {

    // Create a proxy object for the paragraphs collection.
    const paragraphs = context.document.body.paragraphs;

    // Queue a command to load the style property for the top 2 paragraphs.
    // We never perform an empty load. We always must request a property.
    paragraphs.load({select: 'style', top: 2} );

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    await context.sync();

    // Queue a command to get the first paragraph.
    const paragraph = paragraphs.items[0];

    // Queue a command to insert HTML content at the end of the first paragraph.
    paragraph.insertHtml('<strong>Inserted HTML.</strong>', Word.InsertLocation.end);

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    await context.sync();
    console.log('Inserted HTML content at the end of the first paragraph.');
});

insertInlinePictureFromBase64(base64EncodedImage, insertLocation)

Вставляет рисунок в абзац в указанном расположении.

insertInlinePictureFromBase64(base64EncodedImage: string, insertLocation: Word.InsertLocation.replace | Word.InsertLocation.start | Word.InsertLocation.end | "Replace" | "Start" | "End"): Word.InlinePicture;

Параметры

base64EncodedImage

string

Обязательно. Вставляемый образ в кодировке Base64.

insertLocation

replace | start | end | "Replace" | "Start" | "End"

Обязательно. Значение должно быть "Replace", "Start" или "End".

Возвращаемое значение

Комментарии

[ Набор API: WordApi 1.1 ]

Примеры

// Run a batch operation against the Word object model.
await Word.run(async (context) => {

    // Create a proxy object for the paragraphs collection.
    const paragraphs = context.document.body.paragraphs;

    // Queue a command to load the style property for all of the paragraphs.
    paragraphs.load('style');

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    await context.sync();

    // Queue a command to get the first paragraph.
    const paragraph = paragraphs.items[0];

    const b64encodedImg = "iVBORw0KGgoAAAANSUhEUgAAAB4AAAANCAIAAAAxEEnAAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACFSURBVDhPtY1BEoQwDMP6/0+XgIMTBAeYoTqso9Rkx1zG+tNj1H94jgGzeNSjteO5vtQQuG2seO0av8LzGbe3anzRoJ4ybm/VeKEerAEbAUpW4aWQCmrGFWykRzGBCnYy2ha3oAIq2MloW9yCCqhgJ6NtcQsqoIKdjLbFLaiACnYyf2fODbrjZcXfr2F4AAAAAElFTkSuQmCC";

    // Queue a command to insert a base64 encoded image at the beginning of the first paragraph.
    paragraph.insertInlinePictureFromBase64(b64encodedImg, Word.InsertLocation.start);

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    await context.sync();
    console.log('Added an image to the first paragraph.');
});

insertOoxml(ooxml, insertLocation)

Вставляет OOXML в абзац в указанном расположении.

insertOoxml(ooxml: string, insertLocation: Word.InsertLocation.replace | Word.InsertLocation.start | Word.InsertLocation.end | "Replace" | "Start" | "End"): Word.Range;

Параметры

ooxml

string

Обязательно. OOXML, который будет вставлен в абзац.

insertLocation

replace | start | end | "Replace" | "Start" | "End"

Обязательно. Значение должно быть "Replace", "Start" или "End".

Возвращаемое значение

Комментарии

[ Набор API: WordApi 1.1 ]

insertParagraph(paragraphText, insertLocation)

Вставляет абзац в указанном расположении.

insertParagraph(paragraphText: string, insertLocation: Word.InsertLocation.before | Word.InsertLocation.after | "Before" | "After"): Word.Paragraph;

Параметры

paragraphText

string

Обязательно. Текст абзаца, который необходимо вставить.

insertLocation

before | after | "Before" | "After"

Обязательно. Значение должно быть "До" или "После".

Возвращаемое значение

Комментарии

[ Набор API: WordApi 1.1 ]

insertText(text, insertLocation)

Вставляет текст в абзац в указанном расположении.

insertText(text: string, insertLocation: Word.InsertLocation.replace | Word.InsertLocation.start | Word.InsertLocation.end | "Replace" | "Start" | "End"): Word.Range;

Параметры

text

string

Обязательно. Текст, который необходимо вставить.

insertLocation

replace | start | end | "Replace" | "Start" | "End"

Обязательно. Значение должно быть "Replace", "Start" или "End".

Возвращаемое значение

Комментарии

[ Набор API: WordApi 1.1 ]

Примеры

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/25-paragraph/insert-in-different-locations.yaml

await Word.run(async (context) => {
  // Replace the last paragraph.
  const range: Word.Range = context.document.body.paragraphs.getLast().insertText("Just replaced the last paragraph!", "Replace");
  range.font.highlightColor = "black";
  range.font.color = "white";

  await context.sync();
});

load(options)

Добавляет в очередь команду для загрузки указанных свойств объекта. Перед чтением свойств требуется вызвать метод context.sync().

load(options?: Word.Interfaces.ParagraphLoadOptions): Word.Paragraph;

Параметры

options
Word.Interfaces.ParagraphLoadOptions

Предоставляет параметры свойств объекта для загрузки.

Возвращаемое значение

load(propertyNames)

Добавляет в очередь команду для загрузки указанных свойств объекта. Перед чтением свойств требуется вызвать метод context.sync().

load(propertyNames?: string | string[]): Word.Paragraph;

Параметры

propertyNames

string | string[]

Строка с разделителями-запятыми или массив строк, указывающих свойства для загрузки.

Возвращаемое значение

load(propertyNamesAndPaths)

Добавляет в очередь команду для загрузки указанных свойств объекта. Перед чтением свойств требуется вызвать метод context.sync().

load(propertyNamesAndPaths?: {
            select?: string;
            expand?: string;
        }): Word.Paragraph;

Параметры

propertyNamesAndPaths

{ select?: string; expand?: string; }

propertyNamesAndPaths.select — это строка с разделителями-запятыми, указывающая загружаемые свойства, и propertyNamesAndPaths.expand строка с разделителями-запятыми, указывающая загружаемые свойства навигации.

Возвращаемое значение

search(searchText, searchOptions)

Выполняет поиск с указанным SearchOptions в области объекта абзаца. Результат поиска — это коллекция объектов диапазона.

search(searchText: string, searchOptions?: Word.SearchOptions | {
            ignorePunct?: boolean;
            ignoreSpace?: boolean;
            matchCase?: boolean;
            matchPrefix?: boolean;
            matchSuffix?: boolean;
            matchWholeWord?: boolean;
            matchWildcards?: boolean;
        }): Word.RangeCollection;

Параметры

searchText

string

Обязательно. Текст для поиска.

searchOptions

Word.SearchOptions | { ignorePunct?: boolean; ignoreSpace?: boolean; matchCase?: boolean; matchPrefix?: boolean; matchSuffix?: boolean; matchWholeWord?: boolean; matchWildcards?: boolean; }

Необязательный параметр. Параметры поиска.

Возвращаемое значение

Комментарии

[ Набор API: WordApi 1.1 ]

select(selectionMode)

Выбирает абзац и переходит к нему в пользовательском интерфейсе Word.

select(selectionMode?: Word.SelectionMode): void;

Параметры

selectionMode
Word.SelectionMode

Необязательный параметр. Режим выбора должен быть "Select", "Start" или "End". Значение по умолчанию — Select.

Возвращаемое значение

void

Комментарии

[ Набор API: WordApi 1.1 ]

Примеры

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/scroll-to-range.yaml

await Word.run(async (context) => {
  // If select is called with no parameters, it selects the object.
  context.document.body.paragraphs.getLast().select();

  await context.sync();
});

...

await Word.run(async (context) => {
  // Select can be at the start or end of a range; this by definition moves the insertion point without selecting the range.
  context.document.body.paragraphs.getLast().select(Word.SelectionMode.end);

  await context.sync();
});

select(selectionModeString)

Выбирает абзац и переходит к нему в пользовательском интерфейсе Word.

select(selectionModeString?: "Select" | "Start" | "End"): void;

Параметры

selectionModeString

"Select" | "Start" | "End"

Необязательный параметр. Режим выбора должен быть "Select", "Start" или "End". Значение по умолчанию — Select.

Возвращаемое значение

void

Комментарии

[ Набор API: WordApi 1.1 ]

set(properties, options)

Задает несколько свойств объекта одновременно. Можно передать обычный объект с соответствующими свойствами или другой объект API того же типа.

set(properties: Interfaces.ParagraphUpdateData, options?: OfficeExtension.UpdateOptions): void;

Параметры

properties
Word.Interfaces.ParagraphUpdateData

Объект JavaScript со свойствами, структурированными изоморфно по свойствам объекта, для которого вызывается метод .

options
OfficeExtension.UpdateOptions

Предоставляет возможность подавления ошибок, если объект свойств пытается задать какие-либо свойства, доступные только для чтения.

Возвращаемое значение

void

Примеры

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/90-scenarios/multiple-property-set.yaml

await Word.run(async (context) => {
  const paragraph: Word.Paragraph = context.document.body.paragraphs.getFirst();
  paragraph.set({
    leftIndent: 30,
    font: {
      bold: true,
      color: "red"
    }
  });

  await context.sync();
});

...

await Word.run(async (context) => {
  const firstParagraph: Word.Paragraph = context.document.body.paragraphs.getFirst();
  const secondParagraph: Word.Paragraph = firstParagraph.getNext();
  firstParagraph.load("text, font/color, font/bold, leftIndent");

  await context.sync();

  secondParagraph.set(firstParagraph);

  await context.sync();
});

set(properties)

Задает несколько свойств объекта одновременно на основе существующего загруженного объекта.

set(properties: Word.Paragraph): void;

Параметры

properties
Word.Paragraph

Возвращаемое значение

void

toJSON()

Переопределяет метод JavaScript toJSON() , чтобы обеспечить более полезные выходные данные при передаче объекта API в JSON.stringify(). (JSON.stringifyв свою очередь вызывает toJSON метод переданного ему объекта.) В то время как исходный Word.Paragraph объект является объектом API, toJSON метод возвращает обычный объект JavaScript (типизированный как Word.Interfaces.ParagraphData), который содержит неглубокие копии всех загруженных дочерних свойств из исходного объекта.

toJSON(): Word.Interfaces.ParagraphData;

Возвращаемое значение

track()

Отслеживает объект для автоматической корректировки с учетом окружающих изменений в документе. Этот вызов является сокращением для context.trackedObjects.add(thisObject). Если вы используете этот объект в вызовах .sync и вне последовательного выполнения пакета .run и получаете ошибку InvalidObjectPath при задании свойства или вызове метода для объекта, необходимо добавить объект в отслеживаемую коллекцию объектов при первом создании объекта. Если этот объект является частью коллекции, следует также отслеживать родительскую коллекцию.

track(): Word.Paragraph;

Возвращаемое значение

untrack()

Освобождает память, связанную с этим объектом, если он ранее отслеживался. Этот вызов является сокращенным для context.trackedObjects.remove(thisObject). Наличие большого количества отслеживаемых объектов замедляет ведущее приложение, поэтому не забывайте освобождать любые добавленные объекты после завершения их использования. Вызов потребуется выполнить context.sync() до того, как выпуск памяти вступит в силу.

untrack(): Word.Paragraph;

Возвращаемое значение