Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save themacmarketer/d5c93ec1de469cce1f281e66d34603ae to your computer and use it in GitHub Desktop.
Save themacmarketer/d5c93ec1de469cce1f281e66d34603ae to your computer and use it in GitHub Desktop.
docId will be broken up into individual docs, saved into the same folder as docId
//docId will be broken up into individual docs, saved into the same folder as docId
function extractLecturesToDocs() {
const docId = "98989qeWT71TOm9PvG3TzWWlEscDfMkbO4A0LQBV8V5t4"; // Correct document ID
const sourceDoc = DocumentApp.openById(docId);
const body = sourceDoc.getBody();
const elements = body.getParagraphs();
const folder = DriveApp.getFileById(docId).getParents().next(); // Get parent folder directly as a Folder object
let currentDoc = null;
let currentBody = null;
let textBuffer = "";
let headingText = "";
Logger.log("Starting document processing...");
elements.forEach(function (element) {
if (element.getHeading() === DocumentApp.ParagraphHeading.HEADING1) {
if (currentDoc) {
// Save what's been gathered so far to the current document
currentBody.setText(textBuffer);
currentBody.insertParagraph(0, headingText).setHeading(DocumentApp.ParagraphHeading.HEADING1);
currentDoc.saveAndClose();
Logger.log("Document saved and closed: " + currentDoc.getName());
// Move the document to the designated folder, ensuring document name is valid
try {
DriveApp.getFileById(currentDoc.getId()).moveTo(folder);
} catch (e) {
Logger.log("Error moving document: " + e.toString());
}
textBuffer = ""; // Clear the buffer
}
// Start a new document
headingText = element.getText();
if (!headingText) {
headingText = "Untitled Document"; // Default name if heading is empty
}
currentDoc = DocumentApp.create(headingText);
currentBody = currentDoc.getBody();
textBuffer = ""; // Start fresh text buffer
Logger.log("Starting new document: " + currentDoc.getName());
} else if (currentBody) {
textBuffer += element.getText() + "\n"; // Continue buffering text
}
});
// Handle the last document if it exists
if (currentDoc) {
currentBody.setText(textBuffer);
currentBody.insertParagraph(0, headingText).setHeading(DocumentApp.ParagraphHeading.HEADING1);
currentDoc.saveAndClose();
Logger.log("Final document saved and closed: " + currentDoc.getName());
// Move the document to the designated folder
try {
DriveApp.getFileById(currentDoc.getId()).moveTo(folder);
} catch (e) {
Logger.log("Error moving final document: " + e.toString());
}
}
Logger.log("Document processing completed.");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment