将 gdoc 转换为图像 [英] Convert a gdoc into image

查看:22
本文介绍了将 gdoc 转换为图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法从谷歌文档创建图像(例如 png)?我的意思是图像,而不仅仅是 pdf.GetAS 仅创建 pdf,但如果 contentType 设置为 image/png 或其他等效格式,则会返回错误.我的(实际上是微不足道的)代码是

is there a way to create an image (e.g. a png) from a google document? I really mean an image, not just a pdf. GetAS only creates pdf, but returns an error if contentType is set to image/png or other equivalent formats. My (actually trivial) code is

function convertFile() {
var SOURCE_TEMPLATE = "1HvqYidpUpihzo_HDAQ3zE5ScMVsHG9NNlwPkN80GHK0";
var TARGET_FOLDER = "1Eue-3tJpE8sBML0qo6Z25G0D_uuXZjHZ";
var source = DriveApp.getFileById(SOURCE_TEMPLATE);
var targetFolder = DriveApp.getFolderById(TARGET_FOLDER);
var target = source.makeCopy(source,targetFolder);
var newFile = DriveApp.createFile(target.getAs('image/png'));
}

当我运行此代码时,我收到以下错误(我的翻译):

When I run this code, I get the following error (my translation):

不支持从 application/vnd.google-apps.document 到 image/png 的转换.

The conversion from application/vnd.google-apps.document to image/png is not supported.

推荐答案

这个答案怎么样?

makeCopy() 返回 File 对象.getAs() 不能用于此.这样,错误就发生了.

makeCopy() returns File object. getAs() cannot be used for this. By this, the error occurs.

很遗憾,在现阶段,Google Document 无法直接导出为 PNG 图片.所以需要想办法解决.谷歌文档可以转换为 PDF.这个答案使用这个.作为一种解决方法,我想建议使用外部 API,即 ConvertAPI.我认为使用外部 API,脚本变得简单.这是API的一种方法(PDF to PNG API),可以将PDF数据转换为PNG数据.

Unfortunately, in the current stage, Google Document cannot be directly exported as PNG images. So it is required to think of workarounds. Google Document can be converted to PDF. This answer uses this. As a workaround, I would like to propose to use an external API which is ConvertAPI. I thought that using the external API, the script becomes simple. This a method (PDF to PNG API) of API can be converted from PDF data to PNG data.

例如,当您尝试此操作时,您还可以使用免费包"进行测试.当您尝试使用免费套餐"时,请在免费套餐"注册并找回您的密钥.

When you try this, for example, you can also test this using "Free Package". When you try using "Free Package", please Sign Up at "Free Package" and retrieve your Secret key.

在运行此脚本之前,请检索您的密钥并进行设置.

Before you run this script, please retrieve your Secret key and set it.

var secretkey = "###";  // Please set your secret key.

var SOURCE_TEMPLATE = "1HvqYidpUpihzo_HDAQ3zE5ScMVsHG9NNlwPkN80GHK0";
var TARGET_FOLDER = "1Eue-3tJpE8sBML0qo6Z25G0D_uuXZjHZ";
var url = "https://v2.convertapi.com/convert/pdf/to/png?Secret=" + secretkey;
var options = {
  method: "post",
  payload: {File: DriveApp.getFileById(SOURCE_TEMPLATE).getBlob()},
}
var res = UrlFetchApp.fetch(url, options);
res = JSON.parse(res.getContentText());
res.Files.forEach(function(e) {
  var blob = Utilities.newBlob(Utilities.base64Decode(e.FileData), "image/png", e.FileName);
  DriveApp.getFolderById(TARGET_FOLDER).createFile(blob);
});

参考资料:

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆