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:
- Open Your Google Doc:
- Open the Google Doc you want to split.
- 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.
- Click on
- Add the Script:
- In the script editor, delete any existing code.
- Paste the script code provided above.
- Save the Script:
- Click the floppy disk icon or press
Ctrl + S
(Windows) orCmd + S
(Mac). - Name your script project if prompted.
- Click the floppy disk icon or press
- Authorize the Script:
- Click the
Run
button (triangle icon) to execute thesplitDocByHeading
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 thenGo to Project Name (unsafe)
to proceed. - Click
Allow
to grant the necessary permissions.
- Click
- Click the
- 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.
- After authorization, run the script again by clicking the
- Locate the New Documents:
- In your Google Drive, find a folder named
Split Documents
. - Open the folder to access the newly created documents.
- In your Google Drive, find a folder named
Important Notes:
- Folder Location:
- The
Split Documents
folder is created in your main Drive directory. You can move it elsewhere if needed.
- The
- 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.
- If you prefer a different folder name, replace
- Handle Additional Element Types:
- Extend the
createDocument
function’sswitch
statement to handle otherElementType
cases as needed.
- Extend the
Feel free to let me know if you have any questions or need further assistance!
