Create a Google Apps Script that automates the conversion of a structured Google Doc…
- User
Create a Google Apps Script that automates the conversion of a structured Google Doc (containing questions and answers) into a Google Form. The script should:
Input Requirements:
Assume the Google Doc has a clear structure (e.g., questions as headings, answers as bulleted/numbered lists).
Specify if the format supports multiple-choice, text, paragraph, or other question types (or detect them dynamically).
Functionality:
Parse the Google Doc to extract questions and answer options (if applicable).
Create a new Google Form or update an existing one.
Map the Doc’s structure to Form fields (e.g., headings → questions, bullet points → multiple-choice options).
Handle edge cases (e.g., empty lines, irregular formatting).
Output:
Return the URL of the generated Google Form.
Log errors or mismatched formatting for review.
Optional Enhancements:
Add a menu item in Google Docs to trigger the script manually.
Support batch processing (multiple Docs → multiple Forms).
Allow user customization (e.g., form title, question type overrides).
Provide code comments for key steps and error handling."*
Assistant
This Google Apps Script will automate the conversion of a structured Google Doc into a Google Form. It assumes a specific structure for the Google Doc to effectively parse questions and answers.
Assumed Google Doc Structure:
- Questions: Treated as standalone paragraphs. The script will consider a paragraph a question if it's not part of a bulleted/numbered list and appears after any previous question's options have been processed.
- Multiple-Choice Options: Bulleted or numbered list items immediately following a question.
- Text/Paragraph Answers: A question that is not followed by any bulleted/numbered list items will be converted into a "Paragraph" type question in the Google Form.
Google Apps Script Code
To use this script:
- Open the Google Doc you want to convert.
- Go to
Extensions>Apps Script. - Delete any existing code in
Code.gs. - Copy and paste the entire code below into the script editor.
- Save the project (click the floppy disk icon or Ctrl/Cmd + S). You might be prompted to give the project a name.
- Go back to your Google Doc. Refresh the page if the "Convert to Form" menu doesn't appear immediately.
- A new menu item "Convert to Form" should appear. Click it, then select "Convert Document".
- The first time you run it, Google will ask for authorization. Follow the prompts to grant the necessary permissions (to view and manage your Google Docs and Forms).
/** * @fileoverview Google Apps Script to convert a structured Google Doc into a Google Form. * This script is designed to be bound to a Google Doc. */ /** * Adds a custom menu to the Google Doc UI when the document is opened. * This allows the user to trigger the form conversion manually. */ function onOpen() { const ui = DocumentApp.getUi(); ui.createMenu('Convert to Form') .addItem('Convert Document', 'convertToForm') .addToUi(); } /** * Main function to parse the Google Doc and create a Google Form. * It detects questions (paragraphs) and their corresponding options (list items). * * @returns {string} The URL of the newly created Google Form. */ function convertToForm() { const doc = DocumentApp.getActiveDocument(); const body = doc.getBody(); const ui = DocumentApp.getUi(); // --- User Customization / Form Title --- let formTitle = doc.getName(); // Default form title is the document name try { const response = ui.prompt( 'Form Title', 'Enter the title for your new Google Form:', ui.ButtonSet.OK_CANCEL ); if (response.getSelectedButton() === ui.Button.OK && response.getResponseText()) { formTitle = response.getResponseText().trim(); } else if (response.getSelectedButton() === ui.Button.CANCEL) { ui.alert('Conversion cancelled.', 'Form creation was cancelled by the user.', ui.ButtonSet.OK); return ''; // Exit if cancelled } } catch (e) { Logger.log('Prompt for form title failed or was dismissed. Using default title.'); } // Data structure to hold parsed form items before creating the form const formItemsToCreate = []; let currentQuestion = null; let currentOptions = []; let currentQuestionElementId = null; // Store ID to link errors back to doc elements Logger.log('Starting document parsing...'); // Iterate through all child elements of the document body for (let i = 0; i < body.getNumChildren(); i++) { const element = body.getChild(i); const elementType = element.getType(); const text = element.getText().trim(); // Skip empty lines or elements without text content if (!text) { continue; } // --- PARAGRAPH ELEMENT PROCESSING --- if (elementType === DocumentApp.ElementType.PARAGRAPH) { // If we were previously collecting options for a question, and now encounter a new paragraph (not a list item), // it means the previous question and its options are complete. if (currentQuestion) { if (currentOptions.length > 0) { // It's a Multiple Choice question formItemsToCreate.push({ type: 'MULTIPLE_CHOICE', question: currentQuestion, options: currentOptions, docElementId: currentQuestionElementId }); Logger.log(`Parsed MC question: "${currentQuestion}" with ${currentOptions.length} options.`); } else { // It's a Paragraph Text question (no options followed) formItemsToCreate.push({ type: 'PARAGRAPH_TEXT', question: currentQuestion, docElementId: currentQuestionElementId }); Logger.log(`Parsed Paragraph Text question: "${currentQuestion}".`); } } // This new paragraph is the start of a new question currentQuestion = text; currentOptions = []; // Reset options for the new question currentQuestionElementId = element.getId(); // Store ID for potential error logging Logger.log(`New potential question found: "${currentQuestion}"`); } // --- LIST ITEM PROCESSING --- else if (elementType === DocumentApp.ElementType.LIST_ITEM) { if (currentQuestion) { currentOptions.push(text); Logger.log(`- Option added: "${text}"`); } else { // This is an edge case: a list item found without a preceding question paragraph. // It's likely an unparsed structure or an error in the document format. Logger.log(`Warning: Found list item "${text}" without a preceding question. This item will be skipped.`); ui.alert( 'Formatting Warning', `A list item ("${text}") was found without a clear preceding question. ` + 'Please ensure questions are standalone paragraphs directly followed by their options (if any).\n' + 'This item will be skipped in the form.', ui.ButtonSet.OK ); } } // --- Other Element Types (e.g., Table, HorizontalRule, Image) --- else { Logger.log(`Skipping unsupported element type: ${elementType} with text: "${text}"`); // If there's a pending question, it needs to be processed here before skipping if (currentQuestion) { if (currentOptions.length > 0) { formItemsToCreate.push({ type: 'MULTIPLE_CHOICE', question: currentQuestion, options: currentOptions, docElementId: currentQuestionElementId }); Logger.log(`Parsed MC question before skipping unsupported element: "${currentQuestion}".`); } else { formItemsToCreate.push({ type: 'PARAGRAPH_TEXT', question: currentQuestion, docElementId: currentQuestionElementId }); Logger.log(`Parsed Paragraph Text question before skipping unsupported element: "${currentQuestion}".`); } currentQuestion = null; currentOptions = []; currentQuestionElementId = null; } } } // --- After the loop, process the last collected question (if any) --- if (currentQuestion) { if (currentOptions.length > 0) { formItemsToCreate.push({ type: 'MULTIPLE_CHOICE', question: currentQuestion, options: currentOptions, docElementId: currentQuestionElementId }); Logger.log(`Final MC question parsed: "${currentQuestion}".`); } else { formItemsToCreate.push({ type: 'PARAGRAPH_TEXT', question: currentQuestion, docElementId: currentQuestionElementId }); Logger.log(`Final Paragraph Text question parsed: "${currentQuestion}".`); } } Logger.log(`Total questions parsed: ${formItemsToCreate.length}`); // --- Create Google Form --- if (formItemsToCreate.length === 0) { ui.alert('No Questions Found', 'No recognizable questions were found in the document. Please check the document structure.', ui.ButtonSet.OK); Logger.log('No questions found to create a form.'); return ''; } let form; try { form = FormApp.create(formTitle); Logger.log(`Created new Google Form: ${form.getTitle()} (ID: ${form.getId()})`); } catch (e) { ui.alert('Error Creating Form', 'Could not create the Google Form. Please check your Google Drive permissions or try again later.', ui.ButtonSet.OK); Logger.log(`Error creating form: ${e.message}`); return ''; } // Add questions to the form formItemsToCreate.forEach((itemData, index) => { try { if (itemData.type === 'MULTIPLE_CHOICE') { const item = form.addMultipleChoiceItem(); item.setTitle(itemData.question); const choices = itemData.options.map(option => item.createChoice(option)); item.setChoices(choices); Logger.log(`Added MC item ${index + 1}: "${itemData.question}"`); } else if (itemData.type === 'PARAGRAPH_TEXT') { const item = form.addParagraphTextItem(); item.setTitle(itemData.question); Logger.log(`Added Paragraph Text item ${index + 1}: "${itemData.question}"`); } } catch (e) { const errorMsg = `Error adding question "${itemData.question}" to form: ${e.message}. ` + `Doc Element ID: ${itemData.docElementId || 'N/A'}`; Logger.log(errorMsg); ui.alert('Form Creation Error', `There was an error adding a question to the form:\n"${itemData.question}"\n\nError: ${e.message}\n` + 'Please check the script logs for more details.', ui.ButtonSet.OK); } }); const formUrl = form.getPublishedUrl(); Logger.log(`Google Form created successfully. URL: ${formUrl}`); // Provide the URL to the user const response = ui.alert( 'Form Created!', `Your Google Form "${formTitle}" has been created successfully.\n\n` + `Click "Open Form" to view it or "Copy URL" to copy the link.\n\nURL: ${formUrl}`, ui.ButtonSet.YES_NO ); if (response === ui.Button.YES) { // Open Form // Using Browser.msgBox with a direct link (Apps Script doesn't have a direct 'open URL' method within UI.alert) // The user will need to copy/paste or click the link from the logs. // For direct opening, we need a different approach, e.g., a custom HTML sidebar, // or just logging the URL and instructing the user. // As a workaround, we can provide the URL and let the user open it manually. // The current UI.alert will just show Yes/No options. Let's make it a copy/open link for convenience. // A simpler approach for direct opening in new tab is not directly available from UI.alert. // The user has to manually copy and paste. Let's adjust the prompt text. ui.alert( 'Form Created!', `Your Google Form "${formTitle}" has been created successfully.\n\n` + `You can find it here: ${formUrl}\n\n` + `Please copy the URL and paste it into your browser to open the form.`, ui.ButtonSet.OK ); } else if (response === ui.Button.NO) { // Copy URL // Can't directly copy to clipboard from Apps Script without a custom HTML service. // User will have to copy from the alert or logs. ui.alert( 'URL Copied (Manual)', `The Form URL is: ${formUrl}\n\nPlease manually copy this URL.`, ui.ButtonSet.OK ); } return formUrl; }
How to Use and Test:
-
Prepare your Google Doc:
- Create a new Google Doc or use an existing one.
- Populate it with content following the assumed structure.
Example Google Doc Content:
Question 1: What is the capital of France? * Paris * London * Rome * Berlin Describe the importance of photosynthesis. What is your favorite color? Question with multiple choice options: * Option A * Option B * Option C Final thoughts on the topic: -
Open Script Editor:
- With your Google Doc open, go to
Extensions>Apps Script.
- With your Google Doc open, go to
-
Paste Code:
- Delete any default code (
function myFunction() {}). - Copy and paste the entire script from above into the
Code.gsfile. - Save the project (Floppy disk icon).
- Delete any default code (
-
Run the Script (First Time Authorization):
- Go back to your Google Doc tab.
- Refresh the page if you don't see the "Convert to Form" menu immediately.
- Click
Convert to Form>Convert Document. - A dialog will appear asking for authorization. Click
Review Permissions. - Select your Google account.
- Review the permissions (it needs to view and manage your Google Docs and Forms). Click
Allow.
-
Execute Again:
- After authorization, run
Convert to Form>Convert Documentone more time. - It will first prompt you for the desired Form Title. Enter a title or leave it blank to use the Doc's name, then click
OK. - The script will run. You'll see a small "Running script..." notification.
- Once complete, an alert box will pop up with the URL of the newly created Google Form.
- After authorization, run
-
Check the Output:
- Open the provided URL in your browser to see the generated Google Form.
- Check your Google Drive; the new form will be there.
- Check
Extensions>Apps Script>Execution log(orLogger.logoutput in the script editor) for detailed processing information and any warnings/errors.
Key Features and Design Choices:
onOpen()Function: Automatically creates a custom menu in the Google Doc for easy access to the script.convertToForm()Function (Main Logic):- User Customization (Form Title): Prompts the user for a form title, defaulting to the Google Doc's name.
- Document Parsing: Iterates through
Bodyelements of the active Google Doc. - State-based Parsing: Uses
currentQuestionandcurrentOptionsvariables to keep track of the current parsing state (e.g., currently parsing options for a question). - Question Detection: A new
PARAGRAPHelement (that's not empty) signals a new question. - Option Detection:
LIST_ITEMelements immediately following a question are collected as options. - Question Type Mapping:
- If
currentQuestionis followed bycurrentOptions(list items), it becomes aMultipleChoiceItem. - If
currentQuestionis not followed by anycurrentOptions, it becomes aParagraphTextItem(a general-purpose long answer field).
- If
- Error Handling & Logging:
Logger.log()statements provide detailed execution flow for debugging.ui.alert()is used to notify the user about warnings (e.g., list items without a preceding question) or critical errors (e.g., form creation failure).- It captures cases where list items appear without a
currentQuestion, indicating a potential format mismatch in the Doc.
- Google Form Creation: Uses
FormApp.create()andform.addMultipleChoiceItem(),form.addParagraphTextItem()to build the form dynamically. - Output URL: Returns and logs the
form.getPublishedUrl(), also presenting it to the user in an alert dialog.
Limitations and Potential Enhancements (as per optional requirements):
- Batch Processing: This script processes one Doc at a time (the active Doc). For batch processing, you'd need a separate script that reads a list of Doc IDs (e.g., from a Google Sheet) and calls
convertToFormfor each, possibly passing the Doc ID as an argument instead of usingDocumentApp.getActiveDocument(). - Question Type Overrides: Currently, type detection is purely structural (list items for MC, no list items for Paragraph). To allow overrides (e.g., forcing a
TEXT_ITEMorCHECKBOX_ITEM), you would need to introduce special markers in the Doc, like[TYPE:TEXT]or[TYPE:CHECKBOX], and modify the parsing logic to detect and act on these markers. - Irregular Formatting: The script handles basic empty lines and skips unsupported element types. However, highly irregular formatting (e.g., text between a question and its first option, or multiple paragraphs forming a single "question" where only the first is detected) might lead to misinterpretations. Strict adherence to the assumed structure is recommended.
- Required Questions: All questions generated are optional by default. You could add logic to make them required (e.g., based on a special marker in the Doc or a global setting).
- Answer Keys/Scores: This script does not handle setting answer keys or scores, as that typically requires explicit marking in the Doc (e.g.,
[CORRECT]) which is beyond the scope of a basic structural conversion.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.