Google Apps Script that will split your Google Doc into separate documents based on Heading 1

Below is a Google Apps Script that will split your Google Doc into separate documents based on Heading 1 (H1) tags, using the H1 text as the new document titles. The new documents will be saved in a folder within your Google Drive.

Script Code:

function splitDocByHeading() {
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();

// Create or get the 'Split Documents' folder in your Drive
var folders = DriveApp.getFoldersByName('Split Documents');
var folder;
if (folders.hasNext()) {
folder = folders.next();
} else {
folder = DriveApp.createFolder('Split Documents');
}

var numChildren = body.getNumChildren();

var currentHeadingText = null;
var elements = [];

for (var i = 0; i < numChildren; i++) {
var element = body.getChild(i);
var elementType = element.getType();

if (elementType == DocumentApp.ElementType.PARAGRAPH) {
var paragraph = element.asParagraph();
var heading = paragraph.getHeading();

if (heading == DocumentApp.ParagraphHeading.HEADING1) {
// If we have collected content, create a new document
if (currentHeadingText != null) {
createDocument(currentHeadingText, elements, folder);
elements = [];
}
// Start new collection
currentHeadingText = paragraph.getText();
elements.push(element);
} else {
// Collect elements under the current heading
if (currentHeadingText != null) {
elements.push(element);
}
}
} else {
// Collect other elements (tables, images, etc.)
if (currentHeadingText != null) {
elements.push(element);
}
}
}

// Create document for the last heading
if (currentHeadingText != null && elements.length > 0) {
createDocument(currentHeadingText, elements, folder);
}

DocumentApp.getUi().alert('Documents created and stored in the "Split Documents" folder.');
}

function createDocument(title, elements, folder) {
var newDoc = DocumentApp.create(title);
var newBody = newDoc.getBody();

for (var i = 0; i < elements.length; i++) {
var element = elements[i];
var type = element.getType();

switch (type) {
case DocumentApp.ElementType.PARAGRAPH:
newBody.appendParagraph(element.copy());
break;
case DocumentApp.ElementType.TABLE:
newBody.appendTable(element.copy());
break;
case DocumentApp.ElementType.LIST_ITEM:
newBody.appendListItem(element.copy());
break;
case DocumentApp.ElementType.INLINE_IMAGE:
newBody.appendImage(element.copy());
break;
default:
// Handle other types if necessary
break;
}
}

// Move the doc to the specified folder
DriveApp.getFileById(newDoc.getId()).moveTo(folder);
}

How to Use the Script:

  1. Open Your Google Doc:
    • Open the Google Doc you want to split.
  2. Access the Script Editor:
    • Click on Extensions in the top menu.
    • Select Apps Script. This will open a new tab with the Apps Script editor.
  3. Add the Script:
    • In the script editor, delete any existing code.
    • Paste the script code provided above.
  4. Save the Script:
    • Click the floppy disk icon or press Ctrl + S (Windows) or Cmd + S (Mac).
    • Name your script project if prompted.
  5. Authorize the Script:
    • Click the Run button (triangle icon) to execute the splitDocByHeading function.
    • A dialog will appear asking for authorization.
    • Follow the prompts:
      • Click Review Permissions.
      • Choose your Google account.
      • You may see a warning that the app isn’t verified. Click Advanced and then Go to Project Name (unsafe) to proceed.
      • Click Allow to grant the necessary permissions.
  6. Run the Script:
    • After authorization, run the script again by clicking the Run button.
    • The script will process your document and create new documents based on H1 headings.
    • A message will appear confirming that the documents have been created.
  7. Locate the New Documents:
    • In your Google Drive, find a folder named Split Documents.
    • Open the folder to access the newly created documents.

Important Notes:

  • Folder Location:
    • The Split Documents folder is created in your main Drive directory. You can move it elsewhere if needed.
  • Formatting:
    • The script attempts to preserve formatting, including text styles, lists, tables, and images.
  • Element Types:
    • The script handles paragraphs, tables, list items, and inline images. If your document contains other types of elements, you may need to modify the script to accommodate them.
  • Headings:
    • Only Heading 1 (H1) styles are used to split the document. Make sure your document uses H1 styles where you want the splits to occur.
  • Permissions:
    • This script requires access to your Google Docs and Drive to create new documents and folders.

Troubleshooting:

  • Authorization Errors:
    • Ensure you’ve granted all necessary permissions during the authorization step.
  • Script Doesn’t Run:
    • Check the Apps Script editor for any error messages.
    • Make sure you’ve saved the script and that it’s correctly pasted into the editor.
  • Elements Not Copied Correctly:
    • Some complex formatting or unsupported element types may not transfer perfectly. Review the new documents to confirm.

Customization:

  • Change Folder Name:
    • If you prefer a different folder name, replace 'Split Documents' in the script with your desired name.
  • Handle Additional Element Types:
    • Extend the createDocument function’s switch statement to handle other ElementType cases as needed.

Feel free to let me know if you have any questions or need further assistance!