如何使用Delphi

时间:2017-09-13 07:22:47

标签: delphi openoffice-writer

我正在使用在公认的解决方案中提到的方法 How to Search and Replace in odt Open Office document? 使用Delphi搜索和替换odt文档中的文本

现在我的要求是用图像替换文本。 例如,我的odt文件将标记为&#34; SHOW_CHART = ID&#34;,我将从DB中检索给定ID作为图像文件的图表,然后将其替换为&#34; SHOW_CHART = ID&#34;。< / p>

所以我的问题是如何将文件中的图像插入到ODT文档中。 我发现另一个链接提出相同的问题,但使用java。 How to insert an image in to an openoffice writer document with java? 但我不懂java。

1 个答案:

答案 0 :(得分:4)

以下代码改编自Andrew Pitonyak's Macro Document的清单5.24。

ServiceManager := CreateOleObject('com.sun.star.ServiceManager');
Desktop := ServiceManager.createInstance('com.sun.star.frame.Desktop');
NoParams := VarArrayCreate([0, -1], varVariant);
Document := Desktop.loadComponentFromURL('private:factory/swriter', '_blank', 0, NoParams);
Txt := Document.getText;
TextCursor := Txt.createTextCursor;
{TextCursor.setString('Hello, World!');}
Graphic := Document.createInstance('com.sun.star.text.GraphicObject');
Graphic.GraphicURL := 'file:///C:/path/to/my_image.jpg';
Graphic.AnchorType := 1; {com.sun.star.text.TextContentAnchorType.AS_CHARACTER;}
Graphic.Width := 6000;
Graphic.Height := 8000;
Txt.insertTextContent(TextCursor, Graphic, False);

有关在Pascal中使用OpenOffice的更多信息位于https://www.freepascal.org/~michael/articles/openoffice1/openoffice.pdf

修改

此代码以SHOW_CHART=123SHOW_CHART=456为例。然后它找到这些字符串并用相应的图像替换它们。

Txt.insertString(TextCursor, 'SHOW_CHART=123' + #10, False);
Txt.insertString(TextCursor, 'SHOW_CHART=456' + #10, False);
SearchDescriptor := Document.createSearchDescriptor;
SearchDescriptor.setSearchString('SHOW_CHART=[0-9]+');
SearchDescriptor.SearchRegularExpression := True;
Found := Document.findFirst(SearchDescriptor);
While Not (VarIsNull(Found) or VarIsEmpty(Found) or VarIsType(Found,varUnknown)) do
begin
    IdNumber := copy(String(Found.getString), Length('SHOW_CHART=') + 1);
    Found.setString('');
    Graphic := Document.createInstance('com.sun.star.text.GraphicObject');
    If IdNumber = '123' Then
        Graphic.GraphicURL := 'file:///C:/path/to/my_image123.jpg'
    Else
        Graphic.GraphicURL := 'file:///C:/path/to/my_image456.jpg';
    Graphic.AnchorType := 1; {com.sun.star.text.TextContentAnchorType.AS_CHARACTER;}
    Graphic.Width := 6000;
    Graphic.Height := 8000;
    TextCursor.gotoRange(Found, False);
    Txt.insertTextContent(TextCursor, Graphic, False);
    Found := Document.findNext(Found.getEnd, SearchDescriptor);
end;

编辑2

嵌入式在Andrew的文档清单5.26的下一节中进行了解释。

Bitmaps := Document.createInstance('com.sun.star.drawing.BitmapTable');
While...
    If IdNumber = '123' Then begin
        Bitmaps.insertByName('123Jpg', 'file:///C:/OurDocs/test_img123.jpg');
        Graphic.GraphicURL := Bitmaps.getByName('123Jpg');
    end Else begin
        Bitmaps.insertByName('456Jpg', 'file:///C:/OurDocs/test_img456.jpg');
        Graphic.GraphicURL := Bitmaps.getByName('456Jpg');
    end;