PHP调用Google Docs API创建文档时自定义配置未生效问题
问题原因
Google Docs API 的 documents.create 接口仅支持在创建文档时设置title属性,其余文档样式(包括背景色、页面尺寸、边距等documentStyle下的所有配置)在创建阶段传入会被直接忽略,这是API的官方设计限制,和代码写法无关,所以用API Explorer测试也会得到同样结果。
解决方法
- 第一步:先调用
documents.create创建仅设置标题的空白文档,获取生成的文档ID - 第二步:调用
documents.batchUpdate接口,提交updateDocumentStyle类型的请求,批量修改需要的所有文档样式参数,注意必须填写正确的fields参数明确指定要更新的字段,未被声明的字段不会被修改。
对应PHP实现代码参考:
// 第一步:先创建仅带标题的文档 $title = '5 - Testing'; $opcoes = ['title' => $title]; $documento = new Google_Service_Docs_Document($opcoes); try { $documento = $this->docService->documents->create($documento); $docId = $documento->getDocumentId(); } catch (Exception $e) { die($e); } // 第二步:调用batchUpdate修改文档样式 $requests = [ new Google_Service_Docs_Request([ 'updateDocumentStyle' => [ 'documentStyle' => [ 'background' => [ 'color' => [ 'color' => [ 'rgbColor' => [ 'red' => 1.0, 'green' => 0.0, 'blue' => 0.0 ] ] ] ], 'pageSize' => [ 'height' => ['magnitude' => 297 * 0.35146, 'unit' => 'PT'], 'width' => ['magnitude' => 210 * 0.35146, 'unit' => 'PT'], ], 'marginTop' => ['magnitude' => 27 * 0.35146, 'unit' => 'PT'], 'marginBottom' => ['magnitude' => 15 * 0.35146, 'unit' => 'PT'], 'marginLeft' => ['magnitude' => 25 * 0.35146, 'unit' => 'PT'], 'marginRight' => ['magnitude' => 15 * 0.35146, 'unit' => 'PT'], ], 'fields' => 'background,pageSize,marginTop,marginBottom,marginLeft,marginRight' ] ]) ]; $batchUpdateRequest = new Google_Service_Docs_BatchUpdateDocumentRequest(['requests' => $requests]); try { $response = $this->docService->documents->batchUpdate($docId, $batchUpdateRequest); } catch (Exception $e) { die($e); }
注意事项
fields参数必须和你要修改的字段完全对应,不能省略,也不能填错字段名,否则修改不会生效- 你原有代码里的尺寸单位、RGB数值的写法是正确的,直接迁移到batchUpdate的请求里即可
内容的提问来源于stack exchange,提问作者user2671169
相关产品推荐
相关产品推荐

