- 您想要使用 Docs API 将水平线插入 Google 文档。
- 您想使用 php 来实现这一点。
- 您已经能够使用 Docs API 获取和放置 Google 文档的值。
我可以像上面那样理解。不幸的是,在现阶段,Google Docs API 中似乎还没有添加水平规则的方法,而“horizontalRule”可以通过以下方式检索:documents.get
。 Docs API 现在正在增长。所以这可能会在未来的更新中添加。
所以现阶段需要采用workaround来解决这个问题。
模式一:
在此模式中,使用由 Google Apps 脚本创建的 Web Apps 作为 API 将水平线添加到 Google 文档中。
Usage:
1. Set Web Apps Script:
请将以下脚本复制并粘贴到 Google Apps 脚本的脚本编辑器中。
function doGet(e) {
DocumentApp.openById(e.parameter.id).getBody().insertHorizontalRule(Number(e.parameter.index) - 1);
return ContentService.createTextOutput("Done");
}
2. 部署Web应用程序:
- 在脚本编辑器上,通过“发布”->“部署为 Web 应用程序”打开一个对话框。
- Select "Me" for “执行应用程序:”.
- Select "Anyone, even anonymous" for "Who has access to the app:".
- 此设置用于测试情况。
- 您还可以通过设置“仅我自己”而不是“任何人,甚至匿名”来使用访问令牌进行访问。
- 单击“部署”按钮作为新的“项目版本”。
- Automatically open a dialog box of "Authorization required".
- 单击“查看权限”。
- 选择自己的帐户。
- 单击“此应用程序未经验证”处的“高级”。
- 点击“转到###项目名称###(不安全)”
- 单击“允许”按钮。
- 单击“确定”。
- Copy the URL of Web Apps. It's like
https://script.google.com/macros/s/###/exec
.
- 当您修改 Google Apps 脚本时,请重新部署为新版本。这样,修改后的脚本就会反映到Web Apps中。请小心这一点。
3. 使用 Web 应用程序作为 API:
以下脚本适用于 PHP。请设置查询参数id
and index
. id
是 Google 文档 ID。什么时候index=1
设置后,水平线将插入到文档正文的顶部。在这种情况下,index
表示 Google 文档中的每一行。
$url = 'https://script.google.com/macros/s/###/exec?id=###&index=1';
$curl = curl_init();
$option = [
CURLOPT_URL => $url,
CURLOPT_CUSTOMREQUEST => 'GET',
CURLOPT_FOLLOWLOCATION => true,
];
curl_setopt_array($curl, $option);
$response = curl_exec($curl);
$result = json_decode($response, true);
curl_close($curl);
模式2:
我认为你的建议I'm also going to look at possible inserting a thin table with a top border line as a replacement for a horizontal rule.
也可以用作解决方法。为了实现这一点,脚本如下。
运行此脚本时,将在文档顶部创建仅包含顶部行的新表。在运行脚本之前,请先设置$documentId
。在这种情况下,请设置Google_Service_Docs::DOCUMENTS
到范围。
示例脚本:
$documentId = '###';
$index = 1;
$style = [
'width' => ['magnitude' => 0, 'unit' => 'PT'],
'dashStyle' => 'SOLID',
'color' => ['color' => ['rgbColor' => ['blue' => 1, 'green' => 1, 'red' => 1]]]
];
$requests = [
new Google_Service_Docs_Request([
'insertTable' => [
'location' => ['index' => $index],
'columns' => 1,
'rows' => 1
]
]),
new Google_Service_Docs_Request([
'updateTableCellStyle' => [
'tableCellStyle' => [
'borderBottom' => $style,
'borderLeft' => $style,
'borderRight' => $style,
],
'tableStartLocation' => ['index' => $index + 1],
'fields' => 'borderBottom,borderLeft,borderRight'
]
])
];
$batchUpdateRequest = new Google_Service_Docs_BatchUpdateDocumentRequest([
'requests' => $requests
]);
$result = $service->documents->batchUpdate($documentId, $batchUpdateRequest);
参考:
- Web Apps https://developers.google.com/apps-script/guides/web
- 插入水平规则() https://developers.google.com/apps-script/reference/document/paragraph#inserthorizontalrulechildindex
- 方法:documents.batchUpdate https://developers.google.com/docs/api/reference/rest/v1/documents/batchUpdate