我在Google Docs上创建了一个新的文档文件,插入了一张图片,并且(没有插入链接图片的选项,对吗?)需要为它分配一个URL,以便图片可以被点击。
$docs_service = new Google_Service_Docs($client); $drive_service = new Google_Service_Drive($client); $document = new Google_Service_Docs_Document(array( 'title' => $file_name )); $document = $docs_service->documents->create($document); $requests[] = new Google_Service_Docs_Request(array( 'insertText' => array( 'location' => array( 'index' => 1, ), 'text' => "n".$text ) )); $requests[] = new Google_Service_Docs_Request(array( 'insertInlineImage' => array( 'uri' => 'https://example.com/img.jpg', 'location' => array( 'index' => 1, ), 'objectSize' => array( 'height' => array( 'magnitude' => 675, 'unit' => 'PT', ), 'width' => array( 'magnitude' => 360, 'unit' => 'PT', ), ) ) )); $batchUpdateRequest = new Google_Service_Docs_BatchUpdateDocumentRequest(array( 'requests' => $requests )); $response = $docs_service->documents->batchUpdate($document->getDocumentId(), $batchUpdateRequest); $doc = $docs_service->documents->get($document->getDocumentId(), ['fields' => 'body']);
但是我找不到正确的API函数。有一个类InlineImage的setLinkUrl方法,但是如何获取InlineImage的实例呢?
另一种方法是迭代文档
$doc = $docs_service->documents->get($document->getDocumentId(), ['fields' => 'body']); foreach ($doc->body->content as $content) { print_r($content); }
但是打印出来的内容没有任何有用的信息。
P粉0837850142023-07-22 12:15:36
在您展示的脚本中,使用Docs API创建了一个新的文档,并将图片放入了创建的新文档中。在这种情况下,您可以将请求正文修改如下,使用UpdateTextStyleRequest。
$requests[] = new Google_Service_Docs_Request(array( 'insertInlineImage' => array( 'uri' => 'https://example.com/img.jpg', 'location' => array( 'index' => 1, ), 'objectSize' => array( 'height' => array( 'magnitude' => 675, 'unit' => 'PT', ), 'width' => array( 'magnitude' => 360, 'unit' => 'PT', ), ) ) ));
$requests = [ new Google_Service_Docs_Request(array( 'insertInlineImage' => array( 'uri' => 'https://example.com/img.jpg', 'location' => array( 'index' => 1, ), 'objectSize' => array( 'height' => array( 'magnitude' => 675, 'unit' => 'PT', ), 'width' => array( 'magnitude' => 360, 'unit' => 'PT', ), ) ), )), new Google_Service_Docs_Request(array( 'updateTextStyle' => array( 'range' => array( 'startIndex' => 1, 'endIndex' => 2, ), 'textStyle' => array( 'link' => array( 'url' => 'https://www.google.com', // Please set your URL. ), ), 'fields' => 'link', ), )), ];
使用这个修改后的请求正文时, https://www.google.com
的超链接将被设置到在Google文档中插入的图片上。
例如,如果您想从文档中插入的图片中检索startIndex和endIndex,可以使用以下示例脚本:
$doc = $docs_service->documents->get($document->getDocumentId(), ['fields' => 'body']); foreach ($doc->body->content as $content) { if (array_key_exists('paragraph', $content)) { foreach ($content->paragraph->elements as $element) { if (array_key_exists('inlineObjectElement', $element)) { $startIndex = $element->startIndex; $endIndex = $element->endIndex; print_r(array($startIndex, $endIndex)); } } } }