我的 Google 文档中有一个包含一些文本和表格的文件。该文件的内容会不时手动更新。
我需要每月多次以 pdf 格式发送此文件。它是通过 Web UI(文件 - 下载 - pdf)手动完成的,然后通过电子邮件发送给我的用户。
我想消除这种人为干预,并创建一个 API 来下载此 pdf 并向我的用户提供端点。
这个用例可以使用 Google API(最好是 JavaScript)来完成吗?如果是的话,怎么办?
如有任何帮助,我们将不胜感激
要将 Google 文档下载为 PDF,您可以以 Google Developers 中的示例代码为基础,它使用 files.export 方法将文件下载为 PDF。这是示例:
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
/* Class to demonstrate use-case of drive's export pdf. */
public class ExportPdf {
/**
* Download a Document file in PDF format.
* @param realFileId file ID of any workspace document format file.
* @return byte array stream if successful, {@code null} otherwise.
* @throws IOException if service account credentials file not found.
*/
private static ByteArrayOutputStream exportPdf(String realFileId) throws IOException{
// Load pre-authorized user credentials from the environment.
// TODO(developer) - See https://developers.google.com/identity for
// guides on implementing OAuth2 for your application.
GoogleCredentials credentials = GoogleCredentials.getApplicationDefault().createScoped(Arrays.asList(DriveScopes.DRIVE_FILE));
HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(
credentials);
// Build a new authorized API client service.
Drive service = new Drive.Builder(new NetHttpTransport(),
GsonFactory.getDefaultInstance(),
requestInitializer)
.setApplicationName("Drive samples")
.build();
OutputStream outputStream = new ByteArrayOutputStream();
try {
service.files().export(realFileId, "application/pdf")
.executeMediaAndDownloadTo(outputStream);
return (ByteArrayOutputStream) outputStream;
} catch (GoogleJsonResponseException e) {
// TODO(developer) - handle error appropriately
System.err.println("Unable to export file: " + e.getDetails());
throw e;
}
}
}
如果您想自动发送带有附件的电子邮件,您可以使用 Google 开发者指南创建带附件的邮件作为基础,创建邮件后,您可以调整示例代码以进行发送邮件。
所有指南都有 Java 示例。如果您单击“在 GitHub 上查看”选项,您将被重定向到包含代码在线存储库的 GitHub。
** 参考:**
除了必需的软件包和
import
s/require
s 之外,假设您已经拥有安全代码,例如 authorize()
函数和朋友、Google 文档 FILENAME
和 const MIMETYPE = 'application/pdf'
,下面是Node.js 的核心功能,将 Google Docs 文档导出为 PDF 并将其保存在本地:
async function exportDocAsPDF(authClient) {
const drive = google.drive({version: 'v3', auth: authClient});
let res = await drive.files.list({
q: `name="${FILENAME}"`,
fields: 'files(id)',
pageSize: 1
});
const file = res.data.files[0];
console.log(`** Downloading '${FILENAME}'`);
const destPath = path.join(process.cwd(), `${FILENAME}.pdf`);
const fh = await fs.open(destPath, 'w');
const dest = fh.createWriteStream();
res = await drive.files.export({
fileId: file.id,
mimeType: MIMETYPE,
}, {responseType: 'stream'});
await res.data.pipe(dest);
}
authorize().then(exportDocAsPDF).catch(console.error);
我在一篇博客文章中写了有关此主题的文章,其中包含 Node.js 和 Python(2 和 3)中的版本。上面的示例是 CommonJS 版本,但帖子中还提供了现代 JS ECMAscript 模块。 (对于 Python 用户,还有 2 个版本,一个使用当前的身份验证库,另一个适用于依赖较旧的、已弃用的
oauth2client
库的用户。)有关错误修复和更新,请查看 所有 4 个示例的最新版本在他们的仓库中。