文本文档

文本文档是com.sun.star.text.TextDocument服务。
文本文档对象通过thiscomponent或者stardesktop.currentcomponent获得。

文本文档的核心是文本。它由按段落以及其他文本内容的字符串组成。
文档创建所有文本内容,但段落除外。文本内容可以是表格、字段、绘图形状、文字框以及图形对象等。文本内容插入到文本中。之后,可以从文本获得这些文本内容,但绘图形状除外,绘图形状在DrawPage中。
位于文字之上的即是 DrawPage。它包含绘图形状。我们可以将其想象为包含内容的透明图层,它可以影响图层下面的文字,例如,强制文字环绕 DrawPage 上的内容。但是,文字也可以贯穿 DrawPage 内容,因此,这里面的变化是很多的。
 

一、文本


文本是com.sun.star.text.Text服务。文本对象通过文本文档对象的Text属性获得。
文本对象的主要用途是包含文本内容、创建文本游标以在文本中移动、插入文本和删除文本。
com.sun.star.text.Text服务的主要接口
com.sun.text.XText
com.sun.text.XSimpleText
com.sun.text.XTextRange
 

Functions from XText
void insertTextContent(
[in] com::sun::star::text::XTextRange xRange,
[in] com::sun::star::text::XTextContent xContent,
[in] boolean bAbsorb) 
插入文本内容对象
If the bAbsorb is True, the text in the text range is overwritten; otherwise, the text content is inserted after the text range.
 
void removeTextContent(
[in] com::sun::star::text::XTextContent xContent)
删除文本内容对象
Functions from XSimpleText
com::sun::star::text::XTextCursor createTextCursor()
com::sun::star::text::XTextCursor createTextCursorByRange([in] com::sun::star::text::XTextRange aTextPosition)Return a TextCursor that is located at the specified TextRange.
void insertString(
[in] com::sun::star::text::XTextRange xRange,
[in] string aString,
[in] boolean bAbsorb)
Insert a string of characters into the text at the specified text range. Each CR(ASCII 13) inserts a new paragraph and each LF(ASCII 10) inserts a new line.
If the bAbsorb is True, the text in the range is overwritten; otherwise, the text characters are inserted after the text range.
 
void insertControlCharacter(
[in] com::sun::star::text::XTextRange xRange,
[in] short nControlCharacter,
[in] boolean bAbsorb) 
Insert a control character(such as a paragraph break or a hard space) into the text. The nControlCharacter is a value from the constant group com.sun.star.text.ControlCharacter:
  • PARAGRAPH_BREAK = 0–Start a new paragraph.
  • LINE_BREAK = 1–Start a new line in a paragraph.
  • HARD_HYPHEN = 2–Insert a dash that will not hyphenate.
  • SOFT_HYPHEN = 3–Define a preferred hyphenation point if the word must be split at the end of a line.
  • HARD_SPACE = 4–Insert a space that prevents two words from splitting at a line break.
  • APPEND_PARAGRAPH = 5–Append a new paragraph.
If the bAbsorb is True, the text in the text range is overwritten; otherwise, the control character is inserted after the text range.
 
Functions from XTextRange
XText getText()Return the XText interface that contains the text range.
XTextRange getStart()A text range has a start and end position. The getStart() method returns a text range that contains only the start position of this text range.
XTextRange getEnd()A text range has a start and end position. The getEnd() method returns a text range that contains only the end position of this text range.
string getString()Return a string in this text range. Strings in Basic are limited to 64KB in size, but text ranges and text objects are not; use this with care.
void setString([in] string aString)the whole string of characters of this piece of text is replaced.
A text range has a start and end position. The setString() method replaces all of the text between the start and end positions with the argument string. All styles are removed and all text in this text range is replaced.


TextRange叫做文本范围。主要用途是定义文本的起始位置和结束位置。文本范围的开始位置和结束位置可能相同,当相同时,TextRange标记文本中的位置;如果不相同,它们表示选择了一部分文本。

getString方法返回文本的所有字符串。表格中每个单元格作为单个段落返回。
setString重新设置字符串,表格也会删除

odoc = ThisComponent
otext = odoc.Text
MsgBox otext.getString(), 0, "Document Text String"
otext.setString("This is text to set")


只在小文本文档上使用getString。因为basic字符串限制为64KB字符,在大文档上失败。
getString和setString对象方法是有限的,因为Basic字符串有大小限制,并且不包含格式信息。由于这些限制,通常使用其他方法来获得 并设置文本。通常,大型或复杂的文档最好使用getText方法,因为它们支持复杂文档的任意大小和模块化管理。

getStart和getEnd对象方法都返回一个文本范围
可以用insertString插入文本。
insertControlCharacter插入控制代码
在某些情况下,并不需要修改文档的实际文本,而是需要修改其结构。为此,libreOffice提供了控制代码。这些代码可插入到文本中并影响其结构。以下控制代码:
PARAGRAPH_BREAK
段落分隔符。
LINE_BREAK
段落内的换行符。
SOFT_HYPHEN
可能的音节划分点。
HARD_HYPHEN
必需的音节划分点。
HARD_SPACE
在对齐文本中不能扩展或压缩的受保护空格。
 

Sub InsertSimpleText
oText = ThisComponent.Text
oText.insertString(oText.getStart(), "Text object start." & CHR$(13), False)
oText.InsertControlCharacter(oText.getEnd(), com.sun.star.text.ControlCharacter.APPEND_PARAGRAPH, False)
End Sub



二、文本内容


文本包含一系列文本内容。
文本内容是com.sun.star.text.TextContent服务。
文本内容分两类:
插入文本中的,包括段落、表格、字段
悬浮在文本之上的,包括图像、形状、文本框

 

三、段落


虽然文本包含一系列文本内容,但是段落是最主要的文本内容,因此下面专门介绍段落。
段落同时支持com.sun.star.text.Paragraph服务和com.sun.star.text.TextContent服务。
由于既没有命名这些段落,也没有为其创建索引,因此无法直接访问各个段落。不过,可以借助Enumeration对象按顺序遍历这些段落。
但是Enumeration它不仅返回段落,而且还返回表格,所以应检查返回的对象。
示例

odoc = ThisComponent
otext = odoc.Text
Enum = otext.createEnumeration
While Enum.hasMoreElements
     TextElement = Enum.nextElement
     If TextElement.supportsService("com.sun.star.text.TextTable") Then
         MsgBox "The current block contains a table."
     elseIf TextElement.supportsService("com.sun.star.text.Paragraph") Then
         MsgBox "The current block contains a paragraph."
     End If
Wend



段落的String属性表示段落中的文本:

odoc = ThisComponent
otext = odoc.Text
Enum = otext.createEnumeration
While Enum.hasMoreElements
     TextElement = Enum.nextElement
     If TextElement.supportsService("com.sun.star.text.Paragraph") Then
         TextElement.String= Replace(TextPortion.String, "you", "U")
         TextElement.String= Replace(TextPortion.String, "too", "2")
         TextElement.String= Replace(TextPortion.String, "for", "4")
     EndIf
Wend



段落部分
段落是由各个段落部分组成的。段落部分是com.sun.star.text.TextPortion服务。
每个段落部分都包含自己的格式。例如,如果段落中心包含以粗体打印的词,则在libreOffice中要用三个段落部分来表示:粗体类型前面的部分,然后是粗体词,最后是粗体类型后面的部分。
如果使用段落的String属性更改段落文本,那么首先删除旧的段落部分,然后插入新的段落部分。这样一来,旧段落部分的格式就会丢失。
为防止出现这种情况,用户可以访问段落部分,而不是整个段落。段落使用Enumeration对象遍历段落部分。
以下示例将使用一个双循环,来遍历文本文档的所有段落及其包含的段落部分,并应用上一示例中的替换过程:

odoc = ThisComponent
otext = odoc.Text
Enum1 = otext.createEnumeration
While Enum1.hasMoreElements
     TextElement = Enum1.nextElement
     If TextElement.supportsService("com.sun.star.text.Paragraph") Then
         Enum2 = TextElement.createEnumeration
         While Enum2.hasMoreElements
             TextPortion = Enum2.nextElement
             MsgBox "'" & TextPortion.String & "'"
             TextPortion.String= Replace(TextPortion.String, "you", "U")
             TextPortion.String= Replace(TextPortion.String, "too", "2")
             TextPortion.String= Replace(TextPortion.String, "for", "4")
         Wend
     End If
Wend


示例代码使用段落部分的String属性来修改内容。所做的更改与上一示例中对段落的更改相同。不过,由于段落部分是直接编辑的,因此在替换字符串时会保留段落部分的格式。
 

四、格式


有两种方法设置文本格式:
1.直接为文本指定格式。这称为直接格式设置。用户可以使用鼠标指定直接格式。例如,可以设置文本中的某个词为粗体。
2.使用样式设置文本格式。这称为间接格式设置。样式是包含多个格式的列表,为文本设置样式,相当于一次设置多个格式。同时,当修改样式后,libreOffice将更改所有使用该样式的文本的格式。

 

支持字符和段落属性的服务说明
com.sun.star.text.TextCursor如果折叠,则CharacterProperties指光标右侧的位置。
com.sun.star.text.Paragraph
com.sun.star.text.TextPortion
com.sun.star.text.TextTableCursor
com.sun.star.text.Shape
com.sun.star.table.CellRange在文本表中。
com.sun.star.text.TextDocument该模型提供了适用于整个文档的字符属性。它们是:CharFontName、CharFontStyleName、CharFontFamily、CharFontCharSet、CharFontPitch和它们的亚洲对应物CharFontStyleNameAsian、CharFontFamilyAsian、CharFontCharSetAsian、CharFontPitchAsian。


字符属性
针对单个字符的格式称为字符属性。这些属性包括字体、字号、颜色等。
com.sun.star.style.CharacterProperties服务提供字符属性。
 

com.sun.star.style.CharacterProperties提供西文文本中的字符属性
CharFontNamestring - 此属性指定西文文本中字体的名称。
CharFontStyleNamestring - 此属性包含字体风格的名称。
CharFontFamilyshort - 此属性包含在com.sun.star.awt.FontFamily中指定的字体族。
可能的值为:DONTKNOW, DECORATIVE, MODERN, ROMAN, SCRIPT, SWISS, and SYSTEM.
CharFontCharSetshort - 此属性包含在com.sun.star.awt.CharSet中指定的字符集。
可能的值为:DONTKNOW, ANSI MAC, IBMPC_437, IBMPC_850, IBMPC_860, IBMPC_861, IBMPC_863, IBMPC_865, and SYSTEM SYMBOL。
CharFontPitchshort - This property contains the font pitch that is specified in com.sun.star.awt.FontPitch. The word font pitch refers to characters per inch, but the possible values are DONTKNOW, FIXED and VARIABLE. VARIABLE points to the difference between proportional and unproportional fonts.
short -此属性包含在。字体间距是指每英寸的字符数,但可能的值是DONTKNOW、FIXED和VARIABLE。VARIABLE指出了比例字体和非比例字体之间的区别。
CharColorlong - 此属性包含ARGB表示法中的文本颜色值。ARGB有四个字节,分别表示alpha、red、绿色和blue。在十六进制表示法中,这可以方便地使用:0xAARRGGBB. AA(Alpha)可以是00或省略。
CharEscapement[optional] short - Property which contains the relative value of the raisement or lowerment of characters for superscript or subscript styling. Would typically be a positive value for superscript, and a negative value for subscript.
[optional] short -包含用于上标或下标样式的字符的提升或降低的相对值的属性。对于上标通常为正值,对于下标通常为负值。
CharHeightfloat - 此值字符的高度。单位是点
CharUnderlineshort - This property contains the value for the character underline that is specified in com.sun.star.awt.FontUnderline. A lot of underline types are available. Some possible values are SINGLE, DOUBLE, and DOTTED.
short -此属性包含在com.sun.星星.awt.FontUnderline中指定的字符下划线的值。有很多下划线类型可用。一些可能的值是SINGLE、DOUBLE和DOTTED。
CharWeightfloat - 此属性包含字体粗细的值,参见com.sun.star.awt.FontWeight。
常见的是BOLD and NORMAL
CharPosturelong - This property contains the posture of the font as defined in com.sun.star.awt.FontSlant. The most common values are ITALIC and NONE.
long -此属性包含字体的姿态,如com.sun.星星.awt.FontSlant中定义的。最常见的值是ITALIC和NONE。
CharAutoKerning[optional] boolean - Property to determine whether the kerning tables from the current font are used.
[optional] boolean -确定是否使用当前字体中的字距调整表的属性。
CharBackColor[optional] long - Property which contains the text background color in ARGB: 0xAARRGGBB.
[optional] long -包含ARGB: 0xAARRGGBB中文本背景颜色的属性。
CharBackTransparent[optional] boolean - Determines if the text background color is set to transparent.
[optional] boolean -确定文本背景色是否设置为透明。
CharCaseMap[optional] short - Property which contains the value of the case-mapping of the text for formatting and displaying. Possible CaseMaps are NONE, UPPERCASE, LOWERCASE, TITLE, and SMALLCAPS as defined in the constants group com.sun.star.style.CaseMap. (optional)
[optional] short -包含用于格式化和显示的文本的大小写映射的值的属性。可能的CaseMap是NONE、UPPERCASE、LOWERCASE、TITLE和SMALLCAPS,如常量组com.sun.星星.style.CaseMap中定义的。(可选)
CharCrossedOut[optional] boolean - This property is true if the characters are crossed out.
[optional] boolean -如果字符被划掉,则此属性为true。
CharFlash[optional] boolean - If this optional property is true , then the characters are flashing
[optional] boolean -如果此可选属性为true,则字符闪烁
CharStrikeout[optional] short - Determines the type of the strikethrough of the character as defined in com.sun.star.awt.FontStrikeout. Values are NONE, SINGLE, DOUBLE, DONTKNOW, BOLD, and SLASH X.
[optional] short -确定字符的删除线类型,如com.sun.星星.awt.FontStrikeout中定义的。值为NONE、SINGLE、DOUBLE、DONTKNOW、BOLD和SLASH X。
CharWordMode[optional] boolean - If this property is true , the underline and strike-through properties are not applied to white spaces.
[optional] boolean -如果此属性为true,则下划线和删除线属性不应用于白色。
CharKerning[optional] short - Property which contains the value of the kerning of the characters.
[optional] short -包含字符间距值的属性。
CharLocalestruct com.sun.star.lang.Locale. 包含字符的区域设置(语言和国家)
CharKeepTogether[optional] boolean - Property which marks a range of characters to prevent it from being broken into two lines.
[optional] boolean -标记字符范围以防止其被分成两行的属性。
CharNoLineBreak[optional] boolean - Property which marks a range of characters to ignore a line break in this area.
[optional] boolean -标记字符范围以忽略此区域中的换行符的属性。
CharShadowed[optional] boolean - True if the characters are formatted and displayed with a shadow effect. (optional)
[optional] boolean -如果字符被格式化并以阴影效果显示,则为True。(可选)
CharFontType[optional] short - Property which specifies the fundamental technology of the font as specified in com.sun.star.awt.FontType. Possible values are DONTKNOW, RASTER, DEVICE, and SCALABLE.
[optional] short -指定字体的基本技术的属性,如在com.sun.星星.awt.FontType中指定的。可能的值包括DONTKNOW、RASTER、DEVICE和SCALABLE。
CharStyleName[optional] string - 指定字体样式的名称。
CharContoured[optional] boolean - True if the characters are formatted and displayed with a contour effect.
[optional] boolean -如果字符被格式化并以轮廓效果显示,则为True。
CharCombineIsOn[optional] boolean - True if text is formatted in two lines.
[optional] boolean -如果文本格式为两行,则为True。
CharCombinePrefix[optional] string - Contains the prefix string (usually parenthesis) before text that is formatted in two lines.
[optional] string -包含两行格式的文本前的前缀字符串(通常是括号)。
CharCombineSuffix[optional] string - Contains the suffix string (usually parenthesis) after text that is formatted in two lines.
[optional] string -在两行格式的文本后包含后缀字符串(通常是括号)。
CharEmphasis[optional] short - Contains the font emphasis value com.sun.star.text.FontEmphasis.
[optional] short -包含字体强调值com.sun.星星.text.FontEmphasis。
CharRelief[optional] short - Contains the relief value as FontRelief.
[optional] short -包含作为FontRelief的浮雕值。
RubyText[optional] string - Contains the text that is set as ruby.
[optional] string -包含设置为ruby的文本。
RubyAdjust[optional] short - Determines the adjustment of the ruby text as RubyAdjust.
[optional] short -将ruby文本的调整确定为RubyAdjust。
RubyCharStyleName[optional] string - Contains the name of the character style that is applied to RubyText (optional).
[optional] string -包含应用于RubyText的字符样式的名称(可选)。
RubyIsAbove[optional] boolean - Determines whether the ruby text is printed above/left or below/right of the text (optional) .
[optional] boolean -确定ruby文本是打印在文本的上方/左侧还是下方/右侧(可选)。
CharRotation[optional] short - 确定字符的旋转角度。
CharRotationIsFitToLine[optional] short - Determines whether the text formatting tries to fit rotated text into the surrounded line height.
[optional] short -确定文本格式是否尝试将旋转的文本调整到被包围的行高。
CharScaleWidth[optional] short - 确定字符缩放的百分比值。
HyperLinkURL[optional] string - 如果设置了URL,则包含超链接的URL。
HyperLinkTarget[optional] string - 包含超链接的目标名称(如果设置了目标)。
HyperLinkName[optional] string - 如果设置了名称,则包含超链接的名称。
VisitedCharStyleName[optional] string - 包含已访问超链接的字符样式名称。
UnvisitedCharStyleName[optional] string - 包含未访问的超链接的字符样式名称。
CharEscapementHeight[optional] byte - This is the relative height of subscript or superscript characters in units of percent. A value of 100 would be the original height of the characters.
[optional] byte -这是下标或上标字符的相对高度,以百分比为单位。值100将是字符的原始高度。
CharNoHyphenation[optional] boolean - True if the word can be hyphenated at the character.
[optional] boolean -如果单词可以在字符处连字符,则为True。
CharUnderlineColorColor - Gives the color of the underline for that character.
颜色 -提供该字符的下划线颜色。
CharUnderlineHasColorboolean - True if the CharunderlineColor is used for an underline
boolean -如果CharunderlineColor用于下划线,则为True
CharStyleNames[optional] sequence<string> - 指定应用于字体的所有样式的名称。
CharHidden[optional] boolean - 如果字符不可见,则为True
TextUserDefinedAttributes[optional] XNameContainer - This property stores xml attributes. They will be saved to and restored from automatic styles inside xml files.
[optional] XNameContainer-此属性存储xml属性。它们将保存到xml文件中的自动样式中,并从其中恢复。



段落属性
不针对单个字符而是针对整个段落的格式称为段落属性。包括段落与页面边缘之间的距离以及行间距等。
com.sun.star.style.ParagraphProperties服务提供段落属性。
 

Properties of 的性质 com.sun.star.style.ParagraphProperties
ParaAdjustlong - Determines the adjustment of a paragraph.
long -确定段落的调整。
ParaLineSpacing[optional] struct com.sun.star.style.LineSpacing -确定段落的行距。
ParaBackColor[optional] long - 包含段落背景颜色。
ParaBackTransparent[optional] boolean - 如果段落背景颜色设置为透明,则此值为true。
ParaBackGraphicURL[optional] string - 包含段落背景图形的链接值。
ParaBackGraphicFilter[optional] string - 包含段落背景图形的图形过滤器的名称。
ParaBackGraphicLocation[optional] long - 包含背景图形的位置值。根据com.sun.star.style.GraphicLocation
ParaLastLineAdjustshort - 确定最后一行的调整。
ParaExpandSingleWord[optional] boolean - 确定是否拉伸单个单词。
ParaLeftMarginlong - 确定段落的左边距,单位为1/100 mm。
ParaRightMarginlong - 以1/100 mm为单位确定段落的右边距。
ParaTopMarginlong - 以1/100 mm为单位确定段落的上边距。
ParaBottomMarginlong - 以1/100 mm为单位确定段落的底部边距。
ParaLineNumberCount[optional] boolean - 确定段落是否包含在行号中。
ParaLineNumberStartValue[optional] boolean - 包含行号的起始值。
ParaIsHyphenation[optional] boolean - 防止段落被连字符连接。
PageDescName[optional] string - 如果设置了这个属性,它会在它所属的段落之前创建一个分页符,并将值指定为要使用的新页面样式表的名称。
PageNumberOffset[optional] short -如果在段落中设置了分页符属性,则该属性包含页码的新值。
PageStyleName[optional] string - 包含页面样式名称。
ParaRegisterModeActive[optional] boolean - 确定是否将寄存器模式应用于段落。
ParaTabStops[optional] sequence < com.sun.star.style.TabStop >. Specifies the positions and kinds of the tab stops within this paragraph.
[optional] sequence < com.sun.star.style.TabStop >.指定此段落中制表位的位置和种类。
ParaStyleName[optional] string - 包含当前段落样式的名称。
DropCapFormat[optional] struct com.sun.star.style.DropCapFormat specifies whether the first characters of the paragraph are displayed in capital letters and how they are formatted.
[optional] structcom.sun.星星.style.DropCapFormat指定段落的第一个字符是否以大写字母显示以及如何格式化。
DropCapWholeWord[optional] boolean - Specifies if the property DropCapFormat is applied to the whole first word.
[optional] boolean -指定属性DropCapFormat是否应用于整个第一个单词。
ParaKeepTogether[optional] boolean - Setting this property to true prevents page or column breaks between this and the following paragraph.
[optional] boolean -将此属性设置为true可防止在此段落和下一段落之间出现分页或分栏。
ParaSplit[optional] boolean - 将此属性设置为false可防止段落被拆分为两个页面或两列。
NumberingLevel[optional] short - 指定段落的编号级别。
NumberingRulescom.sun.star.container.XIndexReplace包含应用于此段落的编号规则。
NumberingStartValue[optional] short - Specifies the start value for numbering if a new numbering starts at this paragraph.
[optional] short -指定如果新编号从此段落开始,则编号的起始值。
ParaIsNumberingRestart[optional] boolean - 确定编号规则是否重新开始,从当前段落开始计数。
NumberingStyleName[optional] string - 指定编号的样式名称。
ParaOrphans[optional] byte - 指定如果段落分布在多个页面上,则必须位于页面底部的段落的最小行数。
ParaWidows[optional] byte - 指定如果段落分布在多个页面上,则必须位于页面顶部的段落的最小行数。
ParaShadowFormat[optional] struct com.sun.star.table.ShadowFormat. Determines the type, color, and size of the shadow.
[optional] structcom.sun.星星.table.ShadowFormat.确定阴影的类型、颜色和大小。
ParaIsHangingPunctuation[optional] boolean -确定是否允许挂起标点符号。
ParaIsCharacterDistance[optional] boolean -确定是否设置了亚洲文本、西方文本或复杂文本之间的距离。
ParaIsForbiddenRules[optional] boolean -确定是否考虑文本行开头或结尾处禁用字符的规则。



如果需要更改页面样式,则必须设置段落属性PageDescName。这将在光标位置强制插入分页符,新页面将使用请求的页面样式。属性PageNumberOffset必须设置为以新的页数开始。
如果需要不更改所用样式的分页符(或分栏符),则设置属性BreakType

NONE No column or page break is applied.
This value specifies that a location is not yet assigned.
COLUMN_BEFORE A column break is applied before the object to which it belongs.
<p>This implies that the object to which it belongs is the
first in its column.</p>
COLUMN_AFTER A column break is applied after the object to which it belongs.
<p>This implies that the object to which it belongs is the last
in its column.</p>
COLUMN_BOTH A column break is applied before and after the object to which it belongs.
<p>This implies that this object is the only one in its column.</p>
PAGE_BEFORE A page break is applied before the object to which it belongs.
<p>This implies that the object to which it belongs is the
first on its page. </p>
PAGE_AFTER A page break is applied after the object to which it belongs.
<p>This implies that the object to which it belongs is the last
on its page.</p>
PAGE_BOTH A page break is applied before and after the object to which it belongs.
<p>This implies that this object is the only one on its page.</p>


 

分页说明
BreakTypecom.sun.star.style.BreakType
可能的值为NONE、COLUMN_BEFORE、COLUMN_AFTER、COLUMN_BOTH、PAGE_BEFORE、PAGE_AFTER和PAGE_BOTH。
设置属性将强制在当前文本光标位置、段落或文本表处插入分页符或分栏符。
 



删除所有强制分页符

Sub removeHardPageBreaks
    doc = ThisComponent
    paragraphs = doc.Text
    for each para in paragraphs
        para.BreakType = 0
    next para
End Sub





删除所有分页符

Sub removePageBreaks
    doc = ThisComponent
    paragraphs = doc.Text
    for each para in paragraphs
        para.pagedescname = ""
    next para
End Sub




示例:简单的HTML导出
创建一个简单的HTML文件。为此,将在元素 <P> 中记录每个段落。在导出以粗体类型显示的段落部分时,将使用元素 <B> 标记这些部分。

Filename ="c:\text.html"
FileNo = Freefile
Open Filename For Output As #FileNo
Print #FileNo, "<HTML><BODY>"
Doc = StarDesktop.CurrentComponent
Enum1 = Doc.Text.createEnumeration
While Enum1.hasMoreElements
     TextElement = Enum1.nextElement
     If TextElement.supportsService("com.sun.star.text.Paragraph") Then
         Enum2 = TextElement.createEnumeration
         CurLine ="<P>"
         While Enum2.hasMoreElements
             TextPortion = Enum2.nextElement
             If TextPortion.CharWeight= com.sun.star.awt.FontWeight.BOLD THEN
                 CurLine = CurLine & "<B>" & TextPortion.String & "</B>"
             Else
                 CurLine = CurLine & TextPortion.String
             End If
         Wend
         CurLine = CurLine & "</P>"
         Print #FileNo, CurLine
     End If
Wend
Print #FileNo, "</BODY></HTML>"
Close #FileNo





字符和段落属性的默认值
直接格式设置的优先级始终高于间接格式设置。换句话说,使用样式设置格式比直接在文本中设置格式的优先级低。
很难确定文档的某个部分的格式是直接还是间接设置的。
getPropertyState方法可以检查某个格式是如何设置的。该方法将属性名称作为参数,并返回一个常量。
有以下几种常量:
com.sun.star.beans.PropertyState.DIRECT_VALUE
直接在文本中定义属性(直接格式设置)
com.sun.star.beans.PropertyState.DEFAULT_VALUE
通过样式定义属性(间接格式设置)
com.sun.star.beans.PropertyState.AMBIGUOUS_VALUE
属性不明确。例如,在查询段落的粗体类型属性时,如果段落既包括粗体的词,又包括正常字体的词,则会出现这种状态。

搜索通过直接格式设置设为粗体的段落部分。如果找到相应的段落部分,就使用setPropertyToDefault方法删除直接格式,并为段落部分指定MyBold字符样式。

Doc = StarDesktop.CurrentComponent
Enum1 = Doc.Text.createEnumeration
While Enum1.hasMoreElements
     TextElement = Enum1.nextElement
     If TextElement.supportsService("com.sun.star.text.Paragraph") Then
         Enum2 = TextElement.createEnumeration
         While Enum2.hasMoreElements
             TextPortion = Enum2.nextElement
             If TextPortion.CharWeight= com.sun.star.awt.FontWeight.BOLD _
             AND TextPortion.getPropertyState("CharWeight") = _
             com.sun.star.beans.PropertyState.DIRECT_VALUE Then
                 TextPortion.setPropertyToDefault("CharWeight")
                 TextPortion.CharStyleName="MyBold"
             End If
         Wend
     End If
Wend




五、文本游标


文本游标是com.sun.star.text.TextCursor服务。
因为它继承了XTextRange接口,所以可以表示位置。可以按字符、单词、句子而非段落部分浏览。
不应将文本游标与可见光标相混淆。它们完全是两回事。以程序控制的方式更改文本游标的位置不会对可见光标带来任何影响。甚至可以为同一文档打开几个文本游标,并在不同位置中相互独立地使用这些对象。
文本游标通过文本对象的createTextCursor函数创建: 

Doc = StarDesktop.CurrentComponent
Cursor = TextDocument.Text.createTextCursor()




主要接口如下:
com.sun.star.text.XTextCursor
com.sun.star.text.XWordCursor
com.sun.star.text.XSentenceCursor
com.sun.star.text.XParagraphCursor
 

 Public Member Functions inherited from XTextCursor
void collapseToStart()设置end为start
void collapseToEnd()设置start为end
boolean isCollapsed()如果start等于end,则返回True。
boolean goLeft([in] short nCount,
[in] boolean bExpand)
向左跳Count个字符。
boolean goRight([in] short nCount,
[in] boolean bExpand)
向右跳Count个字符。
void gotoStart([in] boolean bExpand)跳至文本文档开头。
void gotoEnd([in] boolean bExpand)跳至文本文档结尾。
void gotoRange(
[in] com::sun::star::text::XTextRange xRange,
[in] boolean bExpand)
 
跳至指定的TextRange。
Protected Member Functions from XWordCursor
boolean isStartOfWord()如果TextCursor位于词的开头,则返回True。
boolean isEndOfWord()如果TextCursor位于词的结尾,则返回True。
boolean gotoNextWord([in] boolean bExpand)跳至下一个词的开头。
boolean gotoPreviousWord([in] boolean bExpand)跳至上一个词的开头。
boolean gotoEndOfWord([in] boolean bExpand)跳至当前词的结尾。
boolean gotoStartOfWord([in] boolean bExpand)跳至当前词的开头。
 Protected Member Functions inherited from XSentenceCursor
boolean isStartOfSentence()如果TextCursor位于句子的开头,则返回True。
boolean isEndOfSentence()如果TextCursor位于句子的结尾,则返回True。
boolean gotoNextSentence([in] boolean Expand)跳至下一个句子的开头。
boolean gotoPreviousSentence([in] boolean Expand)跳至上一个句子的开头。
boolean gotoStartOfSentence([in] boolean Expand)跳至当前句子的开头。
boolean gotoEndOfSentence([in] boolean Expand)跳至当前句子的结尾。
Protected Member Functions from XParagraphCursor
boolean isStartOfParagraph()如果TextCursor位于段落的开头,则返回True。
boolean isEndOfParagraph()如果TextCursor位于段落的结尾,则返回True。
boolean gotoStartOfParagraph([in] boolean bExpand)跳至当前段落的开头。
boolean gotoEndOfParagraph([in] boolean bExpand)跳至当前段落的结尾。
boolean gotoNextParagraph([in] boolean bExpand)跳至下一个段落的开头。
boolean gotoPreviousParagraph([in] boolean bExpand)跳至上一个段落的开头。


文本根据句尾符号划分为句子。例如,将句点解释为表示句子结尾的符号。
Expand表示是否选择经过的区域,也就是start是否不等于end。此外,所有浏览方法都会返回一个参数,表示浏览是否成功

遍历段落

oCursor = ThisComponent.Text.createTextCursor()
oCursor.gotoStart(False)
Do
     oCursor.gotoEndOfParagraph(True)
Loop While oCursor.gotoNextParagraph(False)



统计

Sub CountWordSentPar
oCursor = ThisComponent.Text.createTextCursor()
oCursor.gotoStart(False)
Do
     nPars = nPars + 1
Loop While oCursor.gotoNextParagraph(False)
oCursor.gotoStart(False)
Do
     nSentences = nSentences + 1
Loop While oCursor.gotoNextSentence(False)
oCursor.gotoStart(False)
Do
     nWords = nWords + 1
Loop While oCursor.gotoNextWord(False)
MsgBox "Paragraphs: " & nPars & CHR$(10) &_
"Sentences: " & nSentences & CHR$(10) &_
"Words: " & nWords & CHR$(10), 0, "Doc Statistics"
End Sub




检索和修改文本
如果文本游标选择了文本,则可通过文本游标的String属性获取此文本。

Doc = StarDesktop.CurrentComponent
Cursor = Doc.Text.createTextCursor
Do
     Cursor.gotoEndOfWord(True)
     MsgBox Cursor.String
     Proceed = Cursor.gotoNextSentence(False)
     Cursor.gotoNextWord(False)
Loop While Proceed




修改每个句子的第一个词:

Doc = StarDesktop.CurrentComponent
Cursor = Doc.Text.createTextCursor
Do
     Cursor.gotoEndOfWord(True)
     Cursor.String = "Ups"
     Proceed = Cursor.gotoNextSentence(False)
     Cursor.gotoNextWord(False)
Loop While Proceed


如果选择了文本,则会将其替换为新文本。如果没有选择,则在当前位置插入该文本。


搜索文本
SearchDescriptor是com.sun.star.util.SearchDescriptor服务。
可通过文档的createSearchDescriptor方法创建该服务对象
SearchDescriptor服务提供了以下属性:
SearchDesc.searchString
要搜索的文本
SearchBackwards(Boolean)
在文本中向后搜索,而不是向前搜索。
SearchCaseSensitive(Boolean)
在搜索时区分大小写字符。
SearchRegularExpression(Boolean)
按照正则表达式搜索。
SearchStyles(Boolean)
在文本中搜索指定的段落样式。
SearchWords(Boolean)
仅搜索完整的词。
SearchSimilarity(Boolean)
执行类似搜索(或“模糊匹配”)。可以搜索与搜索表达式类似但不完全相同的字符串
SearchSimilarityAdd(Short)
可以为类似搜索添加的字符数。
SearchSimilarityExchange(Short)
可以作为类似搜索一部分替换的字符数。
SearchSimilarityRemove(Short)
可以作为类似搜索一部分删除的字符数。
SearchSimilarityRelax(Boolean)
同时考虑搜索表达式中的所有偏差规则。

准备好SearchDescriptor后,使用文档的findFirst和findNext方法开始搜索:

Found = Doc.findFirst(SearchDesc)
Do While Found
     Found = Doc.findNext( Found.End, SearchDesc)
Loop




示例:类似搜索
以下示例说明了如何在文本中搜索 "turnover" 一词,并将搜索结果设置为粗体格式。示例中使用了类似搜索,这样不仅可以查找 "turnover" 一词,而且还可以查找复数形式 "turnovers" 以及略有偏差的内容(如 "turnover's")。找到的表达式与搜索表达式最多有两个字母不同:

Doc = StarDesktop.CurrentComponent
SearchDesc = Doc.createSearchDescriptor
SearchDesc.SearchString="turnover"
SearchDesc.SearchSimilarity = True
SearchDesc.SearchSimilarityAdd = 2
SearchDesc.SearchSimilarityExchange = 2
SearchDesc.SearchSimilarityRemove = 2
SearchDesc.SearchSimilarityRelax = False
Found = Doc.findFirst(SearchDesc)
Do While Found
     Found.CharWeight = com.sun.star.awt.FontWeight.BOLD
     Found = Doc.findNext( Found.End, SearchDesc)
Loop




替换文本
ReplaceDescriptor,它支持com.sun.star.util.ReplaceDescriptor服务。ReplaceDescriptor也支持所有SearchDescriptor属性。
以下示例说明了如何使用ReplaceDescriptors

Dim BritishWords(5) As String
Dim USWords(5) As String
BritishWords() = Array("colour", "neighbour", "centre", "behaviour", _
"metre", "through")
USWords() = Array("color", "neighbor", "center", "behavior", _
"meter", "thru")
Doc = StarDesktop.CurrentComponent
Replace = Doc.createReplaceDescriptor
For O = 0 To 5
     Replace.SearchString = BritishWords(I)
     Replace.ReplaceString = USWords(I)
     Doc.replaceAll(Replace)
Next n


用于搜索和替换的表达式是使用ReplaceDescriptors的SearchString和ReplaceString属性设置的。实际替换过程最终是使用文档对象的replaceAll方法实现的,该方法替换搜索表达式的所有实例。


示例:使用正则表达式搜索和替换文本
libreOffice的替换功能在与正则表达式结合使用时尤其有效。这些表达式提供了使用占位符和特殊字符定义变量搜索表达式的选项,而不是使用固定值进行定义。
libreOffice联机帮助部分中详细介绍了libreOffice支持的正则表达式。下面是几个示例:

 

  • 搜索表达式中的句点表示任意字符。因此,搜索表达式sh.rt可以表示shirt和short。
  • 字符 ^ 标记段落的开头。因此,可以使用搜索表达式 ^Peter查找位于段落开头的名字Peter的所有实例。
  • 字符 $ 标记段落的结尾。因此,可以使用搜索表达式Peter$ 查找位于段落结尾的名字Peter的所有实例。
  • 字符 * 表示前面的字符可以重复出现若干次。可以将其与句点一起使用以作为任意字符的占位符。例如,temper.*e表达式可以表示表达式temperance和temperature。

以下示例说明了如何借助正则表达式 ^$ 删除文本文档中的所有空行:

Doc = StarDesktop.CurrentComponent
Replace = Doc.createReplaceDescriptor
Replace.SearchRegularExpression = True
Replace.SearchString = "^$"
Replace.ReplaceString = ""
Doc.replaceAll(Replace)




格式
文本游标包含字符属性和段落属性,所以能使用文本游标设置选择文本的格式
以下示例遍历整个文档,并将每个句子的第一个词设置为粗体格式。

Doc = StarDesktop.CurrentComponent
Cursor = Doc.Text.createTextCursor
Do
     Cursor.gotoEndOfWord(True)
     Cursor.CharWeight = com.sun.star.awt.FontWeight.BOLD
     Proceed = Cursor.gotoNextSentence(False)
     Cursor.gotoNextWord(False)
Loop While Proceed

setAllPropertiesToDefault ()
setPropertiesToDefault ([in] sequence< string > aPropertyNames) 
Sub deledirectformat
odoc = thiscomponent
otext = odoc.Text
oCursor = otext.createTextCursor()
Do
ocursor.gotoendofparagraph(true)
ocursor.setAllPropertiesToDefault
Loop While ocursor.gotonextparagraph(false)
End Sub




六、控制器


控制器负责用户和文档交互。
控制器对象是com.sun.star.text.TextDocumentView服务。
控制器对象通过文档对象的currentController获得。
控制器的主要接口:
com.sun.star.frame.XController
com.sun.star.view.XSelectionSupplier
com.sun.star.text.XTextViewCursorSupplier

getselection()返回当前选择的对象
oselect = ThisComponent.CurrentController.getselection()



oView = ThisComponent.getCurrentController () 
fnd = ThisComponent.findAll (oSearch)
oView.select (fnd)


 


sub FindText
    dim oDoc as object
    dim oSearch as object
    dim oResult as object
    dim oCursor as object
    dim dispatcher as object
    oDoc = thiscomponent
    oSearch = oDoc.createSearchDescriptor()
    with
        oSearch
        .SearchString = "xx"
        .SearchRegularExpression = false
        .SearchCaseSensitive = true
    end with
    oResult = oDoc.findFirst(oSearch)
    if isnull(oResult) then
        msgbox "Not Found", 64, "Title"
        dispatcher = createUnoService("com.sun.star.frame.DispatchHelper")
        dispatcher.executeDispatch(oDoc.CurrentController.Frame, ".uno:PrintPreview", "", 0, Array())
    else
        oCursor = oDoc.CurrentController.ViewCursor
        oCursor.gotoRange(oResult, false)
        msgbox "Found", 64, "Title"
    end if
end sub




Searching selected text or a specified range
https://ask.libreoffice.org/t/writer-macro-search-in-selection/46148

The trick to searching a specified range of text is to notice that you can use any text range, including a text cursor, in the findNext routine. After each call to findNext(), check the end points of the find to see if the search went too far. You may, therefore, constrain a search to any text range. The primary purpose of the findFirst method is to obtain the initial text range for the findNext routine. You can use the selected text framework very easily to search a range of text.
Listing 365. Iterate through all occurrences of text between two cursors.
​​​​​​​

Sub SearchSelectedWorker(oLCursor, oRCursor, oText, oDescriptor)
    If oText.compareRegionEnds(oLCursor, oRCursor) <= 0 Then
        Exit Sub
    end if
    oLCursor.goRight(0, False)
    oFound = oDoc.findNext(oLCursor, oDescriptor)
    Do While Not IsNull(oFound)
        REM See if we searched past the end
        If -1 = oText.compareRegionEnds(oFound, oRCursor) Then
            Exit Do
        end if
        Print oFound.getString()
        oFound = ThisComponent.findNext(oFound.End, oDescriptor)
    Loop
End Sub


The text object cannot compare two regions unless they both belong to that text object. Text that resides in a different frame, section, or even a text table, uses a different text object than the main document text object. As an exercise, investigate what happens if the found text is in a different text object than the text object that contains oRCursor in Listing 365. Is the code in Listing 365 robust?

 

七、可视光标


可视光标与文本游标不同。可视光标是人能看到的,文本游标是不显示的,人看不到。
可视光标知道数据是如何显示的,但不知道数据本身。文本游标知道数据,但不知道如何显示的。例如,可视光标不知道单词或段落,文本游标不知道行、屏幕或页面。

可视光标是com.sun.star.text.TextViewCursor服务。
通过文档对象的currentController获得可视光标对象。
ovcursor = ThisComponent.currentController.getViewCursor()

主要接口如下:
com.sun.star.text.XTextViewCursor
com.sun.star.text.XPageCursor
com.sun.star.view.XScreenCursor
com.sun.star.view.XViewCursor
com.sun.star.view.XLineCursor
 

Public Member Functions from XTextViewCursor
boolean isVisible()
void setVisible([in] boolean bVisible)shows or hides this cursor for the user. More...
com::sun::star::awt::Point getPosition()
Public Member Functions inherited from XTextCursor
void collapseToStart()sets the end of the position to the start. More...
void collapseToEnd()sets the start of the position to the end. More...
boolean isCollapsed()determines if the start and end positions are the same. More...
boolean goLeft([in] short nCount,
[in] boolean bExpand)
moves the cursor the specified number of characters to the left. More...
boolean goRight([in] short nCount,
[in] boolean bExpand)
moves the cursor the specified number of characters to the right. More...
void gotoStart([in] boolean bExpand)moves the cursor to the start of the text. More...
void gotoEnd([in] boolean bExpand)moves the cursor to the end of the text. More...
void gotoRange([in] com::sun::star::text::XTextRange xRange,
[in] boolean bExpand)
moves or expands the cursor to a specified TextRange. More...
Public Member Functions inherited from XPageCursor
boolean jumpToFirstPage()moves the cursor to the first page. More...
boolean jumpToLastPage()moves the cursor to the last page. More...
boolean jumpToPage([in] short nPage)moves the cursor to the specified page. More...
short getPage()
boolean jumpToNextPage()moves the cursor to the next page. More...
boolean jumpToPreviousPage()moves the cursor to the previous page. More...
boolean jumpToEndOfPage()moves the cursor to the end of the current page. More...
boolean jumpToStartOfPage()moves the cursor to the start of the current page. More...
Public Member Functions inherited from XScreenCursor
boolean screenDown()scrolls the view forward by one visible page. More...
boolean screenUp()

Sub ScrollDownOneScreen
    ThisComponent.currentController.getViewCursor().screenDown()
End Sub

Sub InsertControlCharacterAtCurrentCursor
    oViewCursor = ThisComponent.CurrentController.getViewCursor()
    oViewCursor.getText.insertString(oViewCursor.getStart(), CHR$(257), False)
End Sub




格式
给所有页应用默认页面样式

Sub ChangePageStyle
    oVC = ThisComponent.CurrentController.getViewCursor
    oVC.JumpToFirstPage
    Do
        oVC.PageDescName = "Standard"
    Loop While oVC.JumpToNextPage
End Sub




段落根据页边距分成多行。调整页边距,行会发生变化。 此外,复制出来的文本不包含分页符。
要想使视图光标和文本光标保持同步,可视光标和文本游标都需要在文本中移动。

示例Add line breaks in a paragraph.

Sub LineBreaksInParagraph
    oText = ThisComponent.Text
    oViewCursor = ThisComponent.CurrentController.getViewCursor()
    oTextCursor = oText.createTextCursorByRange(oViewCursor)
    oSaveCursor = oText.createTextCursorByRange(oViewCursor)
    If NOT oTextCursor.isStartOfParagraph() Then
         oTextCursor.gotoStartOfParagraph(False)
         oViewCursor.gotoRange(oTextCursor, False)
    End If
    Do While True
         oViewCursor.gotoEndOfLine(false)
         oTextCursor.gotoRange(oViewCursor, False)
         If oTextCursor.isEndOfParagraph() Then
             Exit Do
         end if
         oText.insertControlCharacter(oViewCursor,_
             com.sun.star.text.ControlCharacter.LINE_BREAK, false)
    Loop
    oViewCursor.gotoRange(oSaveCursor, False)
End Sub


 

八、其他文本内容


之前说过,文本内容分两类,一类是插入文本流中的,一类是悬浮于文本之上的。
(一)插入文本中的
com.sun.star.text.TextContent服务提供了以下属性:
 

属性说明
AnchorType确定TextContent对象的锁定类型
com.sun.star.text.TextContentAnchorType
  • AT_PARAGRAPH–0 The anchor is set at the top left position of the paragraph. The object moves if the paragraph moves.
  • AS_CHARACTER–1 The text content object is anchored as a character. The size of the object influences the height of the text line and the object can move as a character if the surrounding text moves.
  • AT_PAGE–2 The text content object is anchored to the page. The object does not move even if the text content around it changes.
  • AT_FRAME–3 The text content object is anchored to a text frame.
  • AT_CHARACTER–4 The text content object is anchored to a character. The object moves if the character moves.
AnchorTypesTextContent对象支持的所有AnchorType
TextWrap确定TextContent对象周围文本的环绕类型
com.sun.star.text.WrapTextMode
  • NONE–0无环绕
  • THROUGHT–1贯穿环绕
  • PARALLEL–2平行环绕Text flows to the left and right of the object.
  • DYNAMIC–3最佳环绕
  • LEFT–4左边环绕
  • RIGHT–5右边环绕



使用文档对象的createInstance方法创建新的TextContent对象。
使用文本对象的insertTextContent方法插入对象。
使用文本对象的removeTextContent方法删除对象。
使用文本对象的setstring("")删除所有文本内容。
虽然文本内容插入文本对象中,但是获得文本内容对象的方法却在文档对象中。



1.表格
表格同时支持com.sun.star.text.TextTable服务和com.sun.star.text.TextContent服务。
创建表格,使用initialize设置行数和列数,使用insertTextContent插入到文本中。
 

Doc = StarDesktop.CurrentComponent
Cursor = Doc.Text.createTextCursor()
Table = Doc.createInstance("com.sun.star.text.TextTable")
Table.initialize(5, 4)
Doc.Text.insertTextContent(Cursor, Table, False)




使用文档对象的getTextTables方法获得表格:

Doc = StarDesktop.CurrentComponent
TextTables = Doc.getTextTables()
For I = 0 to TextTables.count - 1
     Table = TextTables(I)
     ' Editing table
Next I




编辑表格
com.sun.star.text.TextTable服务中属性:
BackColor(Long)
表格的背景颜色。
BottomMargin(Long)
下边距,以百分之一毫米为单位。
LeftMargin(Long)
左边距,以百分之一毫米为单位。
RightMargin(Long)
右边距,以百分之一毫米为单位。
TopMargin(Long)
上边距,以百分之一毫米为单位
RepeatHeadline(Boolean)
在每个页面上重复表格标题。
Width(Long)
表格的绝对宽度,以百分之一毫米为单位。



表格包含一个行的列表。行列表是com.sun.star.table.TableRows服务。其主要接口是com.sun.star.table.XtableRows。
行的列表包含多个行。行是com.sun.star.text.TextTableRow服务。
这些行又包含不同的单元格。严格地说,libreOffice中并没有表格列。这些列是通过将行依次上下排列而隐式生成的。不过,为了简化对表格的访问,libreOffice提供了一些可使用列进行操作的方法。
com.sun.star.table.XtableRows的主要方法:
getByIndex(Integer)
返回指定索引的行对象。
getCount()
返回行对象的数目。
insertByIndex(Index, Count)
从表格中的Index位置开始插入Count个行。
removeByIndex(Index, Count)
从表格中的Index位置开始删除Count个行。
getByIndex和getCount方法可用于所有表格,而insertByIndex和removeByIndex方法只能用于不包含合并单元格的表格。


com.sun.star.text.TextTableRow服务提供了以下属性:
BackColor(Long)
行的背景颜色。
Height(Long)
行高度,以百分之一毫米为单位。
IsAutoHeight(Boolean)
根据内容动态调整表格高度。
VertOrient(const)
文本框的垂直方向,即有关表格中的文本垂直方向的详细信息(与com.sun.star.text.VertOrientation一致的值)


以下示例说明了如何检索表格的行并设置其格式。

Doc = StarDesktop.CurrentComponent
Cursor = Doc.Text.createTextCursor()
Table = Doc.createInstance("com.sun.star.text.TextTable")
Table.initialize(5, 4)
Doc.Text.insertTextContent(Cursor, Table, False)
Rows = Table.getRows
For I = 0 To Rows.getCount() - 1
     Row = Rows.getByIndex(I)
     Row.BackColor = &HFF00FF
Next






访问列的方式与访问行的方式相同,即对Column对象使用getByIndex、getCount、insertByIndex和removeByIndex方法,可通过getColumns访问该对象。不过,只能在不包含合并单元格的表格中使用这些方法。在libreOffice Basic中,不能按列设置单元格格式。为执行此操作,必须使用为单个单元格设置格式的方法。


单元格
libreOffice文档的每个单元格都具有唯一的名称。如果libreOffice光标位于单元格中,则可以在状态栏中看到该单元格的名称。左上角的单元格通常称为A1,右下角的单元格通常称为Xn,其中X表示列的字母,n表示行的编号。单元格对象是通过表格对象的getCellByName() 方法提供的。
以下示例说明了一个循环,它遍历表格的所有单元格,并在单元格中输入相应的行号和列号。

Doc = StarDesktop.CurrentComponent
Cursor = Doc.Text.createTextCursor()
Table = Doc.createInstance("com.sun.star.text.TextTable")
Table.initialize(5, 4)
Doc.Text.insertTextContent(Cursor, Table, False)
Rows = Table.getRows
Cols = Table.getColumns
For RowIndex = 1 To Rows.getCount()
     For ColIndex = 1 To Cols.getCount()
         CellName = Chr(64 + ColIndex) & RowIndex
         Cell = Table.getCellByName(CellName)
         Cell.String = "row: " & CStr(RowIndex) + ", column: " & CStr(ColIndex)
     Next
Next




单元格与标准文本类似。它支持createTextCursor方法。
CellCursor = Cell.createTextCursor()
因此,自动提供了为单个字符和段落设置格式的所有选项。
以下示例将搜索文本文档中的所有表格,并通过相应的段落属性对所有包含数值的单元格应用右对齐格式。

Doc = StarDesktop.CurrentComponent
TextTables = Doc.getTextTables()
For I = 0 to TextTables.count - 1
     Table = TextTables(I)
     CellNames = Table.getCellNames()
     For J = 0 to UBound(CellNames)
         Cell = Table.getCellByName(CellNames(J))
         If IsNumeric(Cell.String) Then
             CellCursor = Cell.createTextCursor()
             CellCursor.paraAdjust = com.sun.star.style.ParagraphAdjust.RIGHT
         End If
     Next
Next




2.字段
文本字段是com.sun.star.text.TextField,除了提供纯文本以外,它们还提供其他逻辑。

Doc = StarDesktop.CurrentComponent
Cursor = Doc.Text.createTextCursor()
DateTimeField = Doc.createInstance("com.sun.star.text.TextField.DateTime")
DateTimeField.IsFixed = False
DateTimeField.IsDate = True
Doc.Text.insertTextContent(Cursor, DateTimeField, False)


本示例在当前文本文档开头插入包含当前日期的文本字段。IsDate属性的True值导致仅显示日期,而不显示时间。IsFixed的False值确保在打开文档时自动更新日期。


除了插入文本字段以外,在文档中搜索字段也是一项非常重要的任务。以下示例说明了如何通过循环遍历文本文档的所有文本字段,并检查其相关类型。

Doc = StarDesktop.CurrentComponent
TextFieldEnum = Doc.getTextFields.createEnumeration
While TextFieldEnum.hasMoreElements()
TextField = TextFieldEnum.nextElement() 
If TextField.supportsService("com.sun.star.text.TextField.DateTime") Then
     MsgBox "Date/time"
ElseIf TextField.supportsService("com.sun.star.text.TextField.Annotation") Then
     MsgBox "Annotation"
Else
     MsgBox "unknown"
End If 
Wend




页数、字数和字符数
 

  • com.sun.star.text.TextField.PageCount
  • com.sun.star.text.TextField.WordCount
  • com.sun.star.text.TextField.CharacterCount

返回文本的页数、字数或字符数。它们支持以下属性:
NumberingType(const)
编号格式(与com.sun.star.style.NumberingType中的常量一致的准则)。
当前页面
可以使用com.sun.star.text.TextField.PageNumber文本字段在文档中插入当前页码。可以指定以下属性:
NumberingType(const)
编号格式(与com.sun.star.style.NumberingType中的常量一致的准则)。
Offset(short)
添加到页码的偏移(也可以指定负数)。
以下示例说明了如何在文档页脚中插入页码。

Doc = StarDesktop.CurrentComponent 
PageNumber = Doc.createInstance("com.sun.star.text.TextField.PageNumber")
PageNumber.NumberingType = com.sun.star.style.NumberingType.ARABIC 
PageStyles = Doc.StyleFamilies.getByName("PageStyles") 
StdPage = PageStyles("Default")
StdPage.FooterIsOn = True 
FooterCursor = StdPage.FooterTextLeft.Text.createTextCursor()
StdPage.FooterTextLeft.Text.insertTextContent(FooterCursor, PageNumber, False)


本示例首先创建com.sun.star.text.TextField.PageNumber服务的对象。由于页眉和页脚行是页面样式的一部分,因此,要获得页面样式,设置页面样式显示页脚,应将FooterIsOn设置为True。然后,在左侧页脚行的文本对象中插入该字段。


注释
可以通过文本中的小黄色符号来查看注释字段 (com.sun.star.text.TextField.Annotation)。单击此符号即可打开一个文本字段,可以在其中记录有关文本当前位置的注释。注释字段具有以下属性。
Author(String)
作者姓名。
Content(String)
注释文本。
Date(Date)
编写注释的日期。
日期/时间
日期/时间字段 (com.sun.star.text.TextField.DateTime) 表示当前日期或当前时间。它支持以下属性:
IsFixed(Boolean)
如果为True,则插入时间详细信息保持不变;如果为False,则每次打开文档时都会更新这些信息。
IsDate(Boolean)
如果为True,该字段将显示当前日期,否则显示当前时间。
DateTimeValue(struct)
字段的当前内容(com.sun.star.util.DateTime结构)
NumberFormat(const)
描述时间或日期所用的格式。
章节名称/编号
可通过com.sun.star.text.TextField.Chapter类型的文本字段提供当前章节的名称。可以使用以下两个属性定义该格式。
ChapterFormat(const)
确定是否描述章节名称或章节编号(与com.sun.star.text.ChapterFormat一致)
Level(Integer)
确定要显示章节名称和/或章节编号的章节级别。值0表示可用的最高级别。


3.书签
书签(com.sun.star.text.Bookmark服务)是TextContent对象。

Doc = StarDesktop.CurrentComponent
Cursor = Doc.Text.createTextCursor()
Bookmark = Doc.createInstance("com.sun.star.text.Bookmark")
Bookmark.Name = "My bookmarks"
Doc.Text.insertTextContent(Cursor, Bookmark, True)


本示例创建了一个Cursor,它标记了书签的插入位置,然后又标记了实际的书签对象 (Bookmark)。接下来,为书签指定了名称,并通过insertTextContent将其插入到文档中的光标位置。
文本的书签是通过称为Bookmarks的列表进行访问的。可以按编号或名称来访问书签。


以下示例说明了如何在文本中查找书签,以及如何在书签位置插入文本。

Doc = StarDesktop.CurrentComponent
Bookmark = Doc.Bookmarks.getByName("My bookmarks")
Cursor = Doc.Text.createTextCursorByRange(Bookmark.Anchor)
Cursor.String = "Here is the bookmark"


本示例使用getByName方法按名称查找所需的书签。然后,createTextCursorByRange调用创建了一个Cursor,它位于书签的锁定位置中。接下来,光标将所需的文本插入到该位置。


(二)悬浮于文本之上的
悬浮于文本之上的统称为形状。
形状对象是独立于普通文本流的文本内容。周围的文本可以环绕它们。锚定到文本中的段落或字符。锚定允许形状对象在用户书写时跟随段落和字符。目前有两种不同的形状对象,基本框架和绘图形状

1.基本框架
基本框架是com.sun.star.text.BaseFrame服务。
它包括服务com.sun.star.text.BaseFrameProperties和com.sun.star.text.TextContent
包括接口com.sun.star.drawing.XShape
属性是在com.sun.star.text.BaseFrameProperties服务中定义的。
主要属性包括:
BackColor(Long)
背景颜色。
BottomMargin(Long)
下边距,以百分之一毫米为单位。
LeftMargin(Long)
左边距,以百分之一毫米为单位。
RightMargin(Long)
右边距,以百分之一毫米为单位。
TopMargin(Long)
上边距,以百分之一毫米为单位
Height(Long)
高度,以百分之一毫米为单位。
Width(Long)
宽度,以百分之一毫米为单位。
HoriOrient(const)
水平方向(与com.sun.star.text.HoriOrientation一致)。
VertOrient(const)
垂直方向(与com.sun.star.text.VertOrientation一致)。

有三种BaseFrame,分别是文本框,图片,嵌入对象
(1)文本框
com.sun.star.text.TextFrame
文本框基本上由标准文本组成,但可以将其放在页面上的任意位置,而不是包含在文本流中。
通过文档的getTextFrames()方法获得。

 

Doc = StarDesktop.CurrentComponent
Cursor = Doc.Text.createTextCursor()
Frame = Doc.createInstance("com.sun.star.text.TextFrame")
Doc.Text.insertTextContent(Cursor, Frame, False)




以下示例创建一个文本框:
Doc = StarDesktop.CurrentComponent
Cursor = Doc.Text.createTextCursor()
Cursor.gotoNextWord(False)
Frame = Doc.createInstance("com.sun.star.text.TextFrame")
Frame.Width = 3000
Frame.Height = 1000
Frame.AnchorType = com.sun.star.text.TextContentAnchorType.AS_CHARACTER
Frame.TopMargin = 0
Frame.BottomMargin = 0
Frame.LeftMargin = 0
Frame.RightMargin = 0
Frame.BorderDistance = 0
Frame.HoriOrient = com.sun.star.text.HoriOrientation.NONE
Frame.VertOrient = com.sun.star.text.VertOrientation.LINE_TOP
Doc.Text.insertTextContent(Cursor, Frame, False)
本示例创建了一个TextCursor以作为文本框的插入标记。它位于文本的第一个词和第二个词之间。文本框是使用Doc.createInstance创建的。文本框对象的属性被设置为所需的起始值。
此处,应注意AnchorType属性和VertOrient属性之间的交互。AnchorType接受AS_CHARACTER值。因此,文本框将直接插入到文本流中,其行为与字符类似。例如,如果遇到换行符,文本框将移到下一行。VertOrient属性的LINE_TOP值可确保文本框上边缘的高度与字符上边缘的高度相同。
在完成初始化后,将使用insertTextContent插入到文本文档中。

要编辑文本框的内容,用户可以使用TextCursor。

Doc = StarDesktop.CurrentComponent
Cursor = Doc.Text.createTextCursor()
Frame = Doc.createInstance("com.sun.star.text.TextFrame")
Frame.Width = 3000
Frame.Height = 1000 
Doc.Text.insertTextContent(Cursor, Frame, False)
FrameCursor = Frame.createTextCursor()
FrameCursor.charWeight = com.sun.star.awt.FontWeight.BOLD
FrameCursor.paraAdjust = com.sun.star.style.ParagraphAdjust.CENTER
FrameCursor.String = "This is a small Test!"


本示例创建了一个文本框,将其插入到当前文档中,然后为该文本框打开了TextCursor。此光标用于将文本框中的字体设置为粗体,并将段落方向设置为居中。最后,为该文本框指定了字符串 "This is a small test!"。


(2)图片
TextGraphicObjects是位图或矢量图像,其格式由内部支持。
TextGraphicObject目前只能插入链接,不支持图形嵌入。

图片列表对象com.sun.star.text.TextGraphicObjects
获得图片列表对象方法graphs=doc.getGraphicObjects()

图片对象com.sun.star.text.TextGraphicObject
获得图片对象graph=graphs.getByIndex(0)

 

Sub InsertGraphicObject(oDoc, sURL$)
    oText = oDoc.getText()
    oCursor = oText.createTextCursor()
    oCursor.goToStart(FALSE)
    oGraph = oDoc.createInstance("com.sun.star.text.TextGraphicObjects")
    With oGraph
        .GraphicURL = sURL
        .AnchorType = com.sun.star.text.TextContentAnchorType.AS_CHARACTER
        .Width = 6000
        .Height = 8000
    End With
    oText.insertTextContent( oCursor, oGraph, False )
End Sub





(3)嵌入对象
TextEmbeddedObjects是包含文档类型的区域,而不是它们所嵌入的文档,例如图表、公式、内部文档或OLE对象 
getTextEmbeddedObjects() 




2.绘制形状
是可以插入到文本中的各种绘图形状,例如矩形和椭圆。他们是com.sun.star.text.Shape服务。com.sun.star.text.Shape包括com.sun.star.drawing.Shape,但是添加了与文本相关的多个属性。此外,绘图形状支持接口com.sun.star.text.XTextContent,以便可以将它们插入到XText中。 
主要接口com.sun.star.drawing.XShape
有如下形状
com.sun.star.drawing.EllipseShape 表示圆和椭圆。
com.sun.star.drawing.RectangleShape 表示框。
com.sun.star.drawing.TextShape 表示文字框。
com.sun.star.drawing.CaptionShape 表示标签
com.sun.star.drawing.MeasureShape 表示轴。
com.sun.star.drawing.ConnectorShape 表示可以“粘”到其他形状以绘制两者之间连接线的线条。
com.sun.star.drawing.LineShape 表示线条和箭头。
com.sun.star.drawing.PolyLineShape 表示由直线构成的敞口形状。
com.sun.star.drawing.PolyPolygonShape 表示由一个或多个多边形构成的形状。
com.sun.star.drawing.ClosedBezierShape 表示闭合的贝赛尔曲线形状。
com.sun.star.drawing.PolyPolygonBezierShape 表示多个多边形和贝赛尔曲线形状构成的组合形状。

形状存储在绘图页中。 绘图页是com.sun.star.drawing.GenericDrawPage服务。
绘图页不仅包含绘图形状,而且包含 BaseFrame对象。
绘图页通过文档对象的getdrawpage方法获得

odoc = thiscomponent
otext = odoc.Text
odp = odoc.drawpage



绘图页的主要接口是com.sun.star.drawing.XDrawPage
方法add和remove添加和移除形状

 

方法说明
getPosition()com.sun.star.awt.Point结构,该结构包含两个长整型值X,Y表示左上角

以1/100 mm为单位获取形状的当前位置。
 
setPosition(Point) 以1/100 mm为单位设置形状的当前位置。
getSize() com.sun.star.awt.Size结构,其中包含两个长整型值Width and Height

以1/100 mm为单位获取形状的当前大小。
 
setSize(Size)以1/100 mm为单位设置形状的当前大小。
getShapeType() 表示形状类型的字符串。


 

sub drawshapes()
    oDoc = thiscomponent
    oPage = odoc.drawpage
    oShape = oDoc.createInstance("com.sun.star.drawing.RectangleShape")
    oPage.add(oShape)
    oShape.setString("rectangle")
    pos = oshape.position
    pos.x = 100
    pos.y = 100
    oshape.position = pos
    sz = oshape.size
    sz.width = 10000
    sz.height = 10000
    oshape.size = sz
    oShape.AnchorType = com.sun.star.text.TextContentAnchorType.AT_PAGE
    oShape.Surround = com.sun.star.text.WrapTextMode.DYNAMIC
    oShape.Shadow = True

    oShape = oDoc.createInstance("com.sun.star.drawing.TextShape")
    oPage.add(oShape)
    oShape.setString("text")
    pos = oshape.position
    pos.x = 10000
    pos.y = 10000
    oshape.position = pos
    sz = oshape.size
    sz.width = 10000
    sz.height = 10000
    oshape.size = sz
    oShape.AnchorType = com.sun.star.text.TextContentAnchorType.AT_PAGE
    oShape.Surround = com.sun.star.text.WrapTextMode.DYNAMIC
End sub


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值