在word文档中添加多张图片

add multiple images in a word doc

我在数据库中存储了一些图像以及一个类型字段,可以说是 A 或 B。我正在尝试将它们添加到 word 模板,添加到我命名为 imgPlaceholder1 和 imgPlaceholder2 的字段中,具体取决于图像的类型。这是我当前的代码:

        $wordTable = new COM("Word.Application") or die("Unable to instanciate Word");
$wordTable->visible = 1;
$wordTable->Documents->Open("c:\template\file.doc");

    try {
        $query = "select id,path,type from uploads Where id = '$Id'";
        $action = mysql_query($query) or die(mysql_error());
            while($result = mysql_fetch_array($action)){
                $type=$result['type'];
                $path=$result['path'];
                if($type=='A'){
                    $wordTable->Selection->Find->ClearFormatting();
                    $wordTable->Selection->Find->Text = 'imgPlaceholder1';
                    $wordTable->Selection->Find->Execute();
                    $wordTable->Selection->InlineShapes->AddPicture($path,False,True);  
                }
                if($type=='B'){
                    $wordTable->Selection->Find->ClearFormatting();
                    $wordTable->Selection->Find->Text = 'imgPlaceholder2';
                    $wordTable->Selection->Find->Execute();
                    $wordTable->Selection->InlineShapes->AddPicture($path,False,True);  
                }
            }
     }
    catch (Exception $e)
        {
            echo $e->getMessage();
        }

现在,代码可以工作了,但是它做了一些奇怪的事情。它忽略类型并将所有内容拉入第一个占位符。我相信这是因为选择->查找->文本,但我不知道如何清除选择或强制它搜索新内容。 我也试过保存关闭文档,再插入第二种图片,结果还是一样。所有图像都在第一个占位符中。

自行解决。 这 3 条线不能彼此相距很远,否则它们会感到悲伤并停止工作:

$wordTable->Selection->Find->ClearFormatting();
$wordTable->Selection->Find->Text = '_fl_ImgTest_1');
$wordTable->Selection->Find->Execute();

然后你可以获得一些编码自由,最后添加:

$wordTable->Selection->InlineShapes->AddPicture($path,False,True); 

对要查找的第二个字符串重复该过程,它会起作用