0

I have an application in Apps Script which populates a template document with some data, exports it as a pdf, and emails it to some email address. The new Document Tabs feature in google docs for Workspace accounts has led to a page with the text 'Tab 1' being prepended to the pdf. The function below uses the Drive API to export the doc as a pdf. Two weeks ago this was actually my solution to this very issue, but for some reason it no longer omits the 'Tab 1' page. The Document Tabs feature cannot be disabled as of now.

If possible, I'd rather not use a 3rd party lib to allow for editing pdfs in Apps Script but so far that's the only solution I can think of. Here is the function which exports the google doc as a pdf. Any suggestions are appreciated.

function exportGoogleDocAsPdf(fileId, fileName) { const exportUrl = `https://www.googleapis.com/drive/v3/files/${fileId}/export?mimeType=application/pdf`; const token = ScriptApp.getOAuthToken(); const response = UrlFetchApp.fetch(exportUrl, { headers: { Authorization: `Bearer ${token}` } }); const pdfBlob = response.getBlob().setName(fileName); return pdfBlob; } 
1
  • Nvm. Asked this in the wrong place + found a solution. Delete Commented Dec 2, 2024 at 21:30

1 Answer 1

0

From my answer to a similar question in Stack Overflow:

The script below creates a PDF from the active document dab without the page with the document tab title. Please note the use of the parameter tab=${tab.getId()}.

function createPDFActiveTab() { const doc = DocumentApp.getActiveDocument(); const tab = doc.getActiveTab(); const url = `https://docs.google.com/document/d/${doc.getId()}/export?format=pdf&tab=${tab.getId()}`; const params = { headers: { "Authorization": 'Bearer ' + ScriptApp.getOAuthToken() } }; const response = UrlFetchApp.fetch(url, params); const blob = response.getBlob(); DriveApp.createFile(blob); } 

Please remember that the document structure has changed due to Document Tabs and the methods used to handle them. The details are explained in Work with tabs.

The above script uses UrlFetchApp because Class DocumentApp and the Advanced Documents Service don't include a method to retrieve a blob from a document tab. It's worth mentioning that there have been reports that this method might fail on some documents for no apparent reason. The first thing to do is to check that the authorization value was correctly set. A common pitfall is to omit the space between Bearer and the token. If you are sure that the script doesn't have any errors, something to try is to make a copy of the document and run the script on the copy.

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.