Keeping your Google Docs well-organized and visually appealing can be a challenging task, especially when dealing with large documents. One common formatting requirement is to resize H3 headings and add horizontal lines above them for better separation and clarity. Instead of manually editing each heading, you can automate this process using Google Apps Script. In this blog post, we’ll walk you through a script that resizes all H3 headings and adds a horizontal line above them, ensuring a cleaner and more structured document.
Here’s the complete resizeH3AndAddHorizontalLine
function:
function resizeH3AndAddHorizontalLine() {
// Get the active document
var doc = DocumentApp.openById(DOCID);
var body = doc.getBody();
// Get all the paragraphs in the document
var paragraphs = body.getParagraphs();
// Loop from the last paragraph to the first
for (var i = paragraphs.length - 1; i >= 0; i--) {
var paragraph = paragraphs[i];
// Check if the paragraph is an H3
if (paragraph.getHeading() === DocumentApp.ParagraphHeading.HEADING3) {
// Resize the H3 element
paragraph.setFontSize(16); // Set the desired font size
// Add a horizontal line above the H3 element
body.insertHorizontalRule(i);
}
}
}
Step-by-Step Guide
Step 1: Open Google Apps Script
- Open your Google Doc.
- Click on
Extensions
>Apps Script
.
Step 2: Add the Script
- Delete any existing code in the script editor and replace it with the provided code.
- Replace
DOCID
with the ID of your Google Doc. - Save the script with a descriptive name, such as
ResizeH3AndAddHorizontalLine
.
Step 3: Run the Script
- Click the play button (Run) to execute the script.
- Grant the necessary permissions if prompted.
How It Works
- Access the Document: The script starts by getting the active Google Doc and its body using
DocumentApp.openById(DOCID)
. - Get Paragraphs: It retrieves all the paragraphs in the document body.
- Iterate from End to Start: The script loops through the paragraphs starting from the last to the first.
- Identify H3 Headings: It checks if a paragraph is an H3 heading.
- Resize H3 Elements: If an H3 heading is found, the script sets its font size to 16.
- Add Horizontal Line: The script inserts a horizontal line above the H3 element without needing to adjust the index because it iterates from the end to the start.
Benefits
- Efficiency: Automates the repetitive task of resizing headings and adding horizontal lines.
- Consistency: Ensures consistent formatting throughout your document.
- Time-Saving: Reduces the time spent on manual editing, allowing you to focus on more important tasks.
Conclusion
Using Google Apps Script to automate tasks in Google Docs can significantly enhance your productivity. The resizeH3AndAddHorizontalLine
function is a simple yet effective script that helps you maintain a well-organized and visually appealing document effortlessly. Feel free to customize and expand this script to suit your specific needs.