将gdoc转换成图片 [英] Convert a gdoc into image

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

问题描述

有没有一种方法可以从Google文档创建图像(例如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.

Ty

推荐答案

此答案如何?

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

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

不幸的是,在当前阶段,Google文档不能直接导出为PNG图像.因此,需要考虑解决方法. Google文档可以转换为PDF.此答案使用此.解决方法是,我建议使用一个 ConvertAPI 的外部API.我认为使用外部API可使脚本变得简单. API的这种方法(PDF到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天全站免登陆