English 中文(简体)
页: 1
原标题:Google Apps Script - Update PDF from Sheets and Keep Share Link and Permissions

我有一份备忘录,将谷歌透镜印成“人民抵抗力量”,并在我的驱动下予以挽救。 文字在这方面发挥了巨大作用。 面临的挑战是,我想要取代关于驾驶车的现有档案,保持战术上的联系,并保留许可,以便任何有链接的人都能查阅更新的档案。 下面是我的法典。 我如何调整,以便更新现有档案,而不是删除旧档案和提出新的档案?

function savePDF() {
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = spreadsheet.getSheetByName( sheet_name ); // Specifically target the sheet_name sheet
  var folderId =  my_google_drive_folder_id ;
  var pdfName =  filename.pdf ;

  // Determine the last non-empty cell in each column and row
  var dataRange = sheet.getDataRange();
  var lastRow = dataRange.getLastRow();
  var lastColumn = dataRange.getLastColumn();

  // Adjust print settings to fit the data range
  var range = sheet.getRange(1, 1, lastRow, lastColumn);
  sheet.setActiveRange(range);
  spreadsheet.setActiveSheet(sheet, true);

  var folder = DriveApp.getFolderById(folderId);
  var files = folder.getFilesByName(pdfName);

  // Delete the existing PDF in the folder
  while (files.hasNext()) {
    var file = files.next();
    folder.removeFile(file);
  }

  // Define PDF export URL with adjusted print range
  var url =  https://docs.google.com/spreadsheets/d/  + spreadsheet.getId() +  /export?exportFormat=pdf&format=pdf ;
  var options =  &size=letter  +
                 &portrait=true  +
                 &scale=2  +
                 &top_margin=0.25  +  &bottom_margin=0.75  +  &left_margin=0.25  +  &right_margin=0.25  +
                 &sheetnames=false&printtitle=false&pagenumbers=true&gridlines=false&fzr=true  +
                 &gid=  + sheet.getSheetId(); // Using the specific Sheet ID for exporting

  var token = ScriptApp.getOAuthToken();

  // Fetch the PDF
  var response = UrlFetchApp.fetch(url + options, {
    headers: {
       Authorization :  Bearer   + token
    }
  });

  // Convert to a blob and create new file in the drive folder
  var blob = response.getBlob().setName(pdfName);
  folder.createFile(blob);
  
  // Log a success message
  Logger.log( PDF updated and view permissions set in Google Drive folder! );
}

我也尝试了以下法典,但以下法典产生了腐败的国防军。

function updatePDF() {
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = spreadsheet.getSheetByName( sheet_name ); // Target specific sheet
  var folderId =  my_google_drive_folder_id ;
  var pdfName =  filename.pdf ;

  var folder = DriveApp.getFolderById(folderId);
  var files = folder.getFilesByName(pdfName);
  var existingFile = files.hasNext() ? files.next() : null;

  var url =  https://docs.google.com/spreadsheets/d/  + spreadsheet.getId() +  /export?exportFormat=pdf&format=pdf ;
  var options =  &size=letter  +
                 &portrait=true  +
                 &scale=2  +
                 &top_margin=0.25  +  &bottom_margin=0.75  +  &left_margin=0.25  +  &right_margin=0.25  +
                 &sheetnames=false&printtitle=false&pagenumbers=true&gridlines=false&fzr=true  +
                 &gid=  + sheet.getSheetId(); // Using the specific Sheet ID for exporting

  var token = ScriptApp.getOAuthToken();
  var headers = {
     Authorization :  Bearer   + token,
     muteHttpExceptions : true
  };
  var response = UrlFetchApp.fetch(url + options, { headers: headers });

  if (response.getResponseCode() == 200) {
    var blob = response.getBlob().setName(pdfName);

    // Create a new file and capture its ID
    var newFile = folder.createFile(blob);
    newFile.setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.VIEW);

    // Delete the old file if it exists
    if (existingFile) {
      existingFile.setTrashed(true);
    }

    Logger.log( PDF updated successfully and permissions are set. );
  } else {
    Logger.log( Failed to fetch the PDF:   + response.getContentText());
  }
}
问题回答

我认为你的目标如下。

  • You want to update the existing PDF file instead of creating a new PDF file using Google Apps Script.

在此情况下,如何使用快车道? 如果这反映在你的底稿中,则如下。

Modified script:

在您使用这一文字之前, 页: 1

function updatePDF() {
  var folderId =  17kuKOJApfPvN7vHPygLAfKkVKis6Xhfr ;
  var pdfName =  avail_inventory.pdf ;

  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = spreadsheet.getSheetByName( PDF_AVAIL_TOOL );
  var folder = DriveApp.getFolderById(folderId);
  var files = folder.getFilesByName(pdfName);
  var existingFileId = files.hasNext() ? files.next().getId() : Drive.Files.create({ name: pdfName, mimeType: MimeType.PDF, parents: [folderId] }).id;
  var url =  https://docs.google.com/spreadsheets/d/  + spreadsheet.getId() +  /export?exportFormat=pdf&format=pdf ;
  var options =  &size=letter  +
     &portrait=true  +
     &scale=2  +
     &top_margin=0.25  +  &bottom_margin=0.75  +  &left_margin=0.25  +  &right_margin=0.25  +
     &sheetnames=false&printtitle=false&pagenumbers=true&gridlines=false&fzr=true  +
     &gid=  + sheet.getSheetId(); // Using the specific Sheet ID for exporting
  var token = ScriptApp.getOAuthToken();
  var headers = {
     Authorization :  Bearer   + token,
     muteHttpExceptions : true
  };
  var response = UrlFetchApp.fetch(url + options, { headers: headers });
  if (response.getResponseCode() == 200) {
    var blob = response.getBlob().setName(pdfName);
    Drive.Files.update({}, existingFileId, blob);
    DriveApp.getFileById(existingFileId).setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.VIEW);
    Logger.log( PDF updated successfully and permissions are set. );
  } else {
    Logger.log( Failed to fetch the PDF:   + response.getContentText());
  }
}
  • When this script is run, when the file of var pdfName = avail_inventory.pdf ; is existing, the existing file is updated. When the file of var pdfName = avail_inventory.pdf ; does not exist, a new file is created.

Reference:





相关问题
How to use year counter google app script?

I need an urgent help i have data as follows in a google sheet i need to add a year counter to the column d as follows using google apps script

Google Spreadsheet multiple column filter using OR

I have a Google Spreadsheet with 3 columns that are either blank or have a value. I want to get the count of the number of rows that has A and either B or C populated. If I were writing a SQL query ...

Run Google Apps Script on Google-Spreadsheet event?

If I create a Google apps script, can I hook it up to Google spreadsheet to run based on an event, or must I manually invoke it? I don t know if Google Sheets supports any events. For example: a ...

How do I insert a row in to a Google spreadsheet using c#

I ve seen; Accessing Google Spreadsheets with C# using Google Data API and http://code.google.com/apis/spreadsheets/data/2.0/developers_guide_dotnet.html#CreatingRows However i m still having ...

using Zend_Gdata_Spreadsheets for public spreadsheets?

I have this code which is working, to load a Google Spreadsheet and load some data from it. If the spreadsheet in question is public, how do i modify the code to not require a username/password? $key=...

Programatically updating a Google spreadsheet

I ve got a pre-existing Google spreadsheet. Each month I update this document. I ve got a template workseet in the spreadseet that I d like to clone and then update. I d prefer to clone the ...

热门标签