我想将Google Doc
文件保存为与当前文件位于同一pdf
文件夹中的Google Drive
。我知道我可以将文件下载为pdf
,但我必须将其上传到同一个Google Drive
文件夹中。我试图跳过上传步骤。
我已经创建了一个脚本来完成所有这些,但我无法将图像和绘图包含在生成的pdf
中。
这是我的代码:
function onOpen() {
// Add a custom menu to the spreadsheet.
var ui = DocumentApp.getUi();
var menu = ui.createAddonMenu();
menu.addItem('Save As PDF','saveToPDF')
.addToUi();
}
function saveToPDF(){
var currentDocument = DocumentApp.getActiveDocument();
var parentFolder = DriveApp.getFileById(currentDocument.getId()).getParents();
var folderId = parentFolder.next().getId();
var currentFolder = DriveApp.getFolderById(folderId);
var pdf = currentDocument.getAs('application/PDF');
pdf.setName(currentDocument.getName() + ".pdf");
// Check if the file already exists and add a datecode if it does
var hasFile = DriveApp.getFilesByName(pdf.getName());
if(hasFile.hasNext()){
var d = new Date();
var dateCode = d.getYear()+ "" + ("0" + (d.getMonth() + 1)).slice(-2) + "" + ("0" + (d.getDate())).slice(-2);
pdf.setName(currentDocument.getName() + "_" + dateCode +".pdf");
}
// Create the file (puts it in the root folder)
var file = DriveApp.createFile(pdf);
// Add to source document original folder
currentFolder.addFile(file);
// Remove the new file from the root folder
DriveApp.getRootFolder().removeFile(file);
}
是否有其他方法可以创建pdf
,保存到当前Google Drive
文件夹,而不会丢失图像?
更新
我刚刚测试并意识到,即使我以PDF格式导出,图像和图纸也不包含在内。必须有办法做到这一点。
更新2
我一直在测试更多,并学到了一些东西:
In line
,则会包含这些图片,但如果我使用的是Wrap text
或Break text
则不会。但是,如果我使用" Project Proposal"模板,它们在页脚中包含Break text
的图像,并导出到pdf
。我不能告诉他们为什么他们的形象有所不同。
我不想使用In line
,因为我希望图片触及页面的两侧,In line
将始终在图像的左侧留下至少1个像素。< / p>
答案 0 :(得分:1)
当然有。要使以下代码有效,您必须先启用Advanced Services in Appscript。这意味着在App Script和Google Dev Console中启用Drive API。
由于我们将其保存为PDF,因此我们确保MiMEtype等于application/pdf
,并确保文件的标题以'.pdf'结尾。现在我们已经启用了必要的权限,这应该可以无缝地工作。
执行并检查您的Google云端硬盘中的文件,在这种情况下,它是'myImage.pdf'。
function convertImageToPDF() {
//get URL of image
var image = UrlFetchApp.fetch('http://i.imgur.com/DS6bVac.png');
// grab its bytes and base64-encode them.
var base64 = Utilities.base64Encode(image.getBlob().getBytes());
var html = '<img src="data:image/png;base64,'+base64+'" />';
// create a blob, convert to PDF
var blob = Utilities.newBlob(html, MimeType.HTML);
//save to Google Drive
var file = {
title: 'myImage.pdf', //set Title
mimeType: 'application/pdf' //set MimeType
};
file = Drive.Files.insert(file,blob.getAs(MimeType.PDF));
Logger.log('ID: %s, File size (bytes): %s', file.id, file.fileSize);
}