Google Apps Script: Convert Google Doc to Google Form
Below is a comprehensive script that automates the conversion of a structured Google Doc into a Google Form. The script includes error handling, logging, and optional enhancements.
/**
* Converts a structured Google Doc into a Google Form.
* Supports multiple-choice, text, and paragraph question types.
* Can be triggered manually from a custom menu in Google Docs.
*/
// Global variables
var LOG_SHEET_NAME = "ConversionLog";
var FORM_TITLE_PREFIX = "Form from Doc: ";
/**
* Main function to convert Google Doc to Google Form
* @param {string} docId - The ID of the Google Doc to convert
* @param {string} [formId] - Optional ID of an existing form to update
* @return {string} URL of the created/updated Google Form
*/
function convertDocToForm(docId, formId) {
try {
// Initialize logging
var logSheet = initializeLogging();
// Get the document and its content
var doc = DocumentApp.openById(docId);
var body = doc.getBody();
var docName = doc.getName();
// Create or open the form
var form = formId ?
FormApp.openById(formId) :
FormApp.create(FORM_TITLE_PREFIX + docName);
// Clear existing items if updating an existing form
if (formId) {
var items = form.getItems();
for (var i = items.length - 1; i >= 0; i--) {
items[i].setTitle(""); // Clear title first to avoid errors
form.deleteItem(items[i]);
}
}
// Process each paragraph in the document
var paragraphs = body.getParagraphs();
var currentQuestion = null;
var currentOptions = [];
var questionType = null;
for (var i = 0; i < paragraphs.length; i++) {
var paragraph = paragraphs[i];
var text = paragraph.getText().trim();
// Skip empty paragraphs
if (!text) continue;
// Detect question headings (assuming they're bold or larger font)
var isHeading = isQuestionHeading(paragraph);
if (isHeading) {
// If we have a current question pending, add it to the form first
if (currentQuestion) {
addQuestionToForm(form, currentQuestion, currentOptions, questionType);
currentOptions = [];
}
// Set the new question
currentQuestion = text;
questionType = detectQuestionType(paragraph);
}
// If not a heading, treat as answer option (for multiple choice)
else if (currentQuestion) {
// Check if this is a bullet point or numbered list
var listItem = isListItem(paragraph);
if (listItem) {
currentOptions.push(text);
}
// Otherwise, treat as additional question text (for text/paragraph questions)
else {
currentQuestion += "\n" + text;
}
}
}
// Add the last question if it exists
if (currentQuestion) {
addQuestionToForm(form, currentQuestion, currentOptions, questionType);
}
// Log successful conversion
logConversion(logSheet, docName, form.getPublishedUrl(), "Success");
return form.getPublishedUrl();
} catch (error) {
// Log error
var logSheet = initializeLogging();
logConversion(logSheet, docId, "", "Error: " + error.toString());
throw new Error("Conversion failed: " + error.toString());
}
}
/**
* Detects if a paragraph is a question heading
* @param {Paragraph} paragraph - The paragraph to check
* @return {boolean} True if it's likely a question heading
*/
function isQuestionHeading(paragraph) {
var attributes = paragraph.getAttributes();
var text = paragraph.getText().trim();
// Check for bold text or larger font size
if (attributes[DocumentApp.Attribute.BOLD] === true) return true;
if (attributes[DocumentApp.Attribute.FONT_SIZE] > 12) return true;
// Check if it ends with a question mark
if (text.endsWith("?")) return true;
// Check if it's a numbered question (e.g., "1. Question text")
if (/^\d+\.\s/.test(text)) return true;
return false;
}
/**
* Detects the question type based on paragraph attributes
* @param {Paragraph} paragraph - The paragraph containing the question
* @return {string} The detected question type
*/
function detectQuestionType(paragraph) {
// Default to text question
var type = FormApp.ItemType.TEXT;
// Check for specific patterns that might indicate other question types
var text = paragraph.getText().toLowerCase();
if (text.includes("multiple choice") || text.includes("select one")) {
type = FormApp.ItemType.MULTIPLE_CHOICE;
} else if (text.includes("paragraph") || text.includes("long answer")) {
type = FormApp.ItemType.PARAGRAPH_TEXT;
} else if (text.includes("checkbox") || text.includes("select all")) {
type = FormApp.ItemType.CHECKBOX;
}
return type;
}
/**
* Checks if a paragraph is a list item (bullet or numbered)
* @param {Paragraph} paragraph - The paragraph to check
* @return {boolean} True if it's a list item
*/
function isListItem(paragraph) {
var attributes = paragraph.getAttributes();
var listId = attributes[DocumentApp.Attribute.GLYPH_TYPE];
return listId !== DocumentApp.GlyphType.NORMAL;
}
/**
* Adds a question to the form with the appropriate type and options
* @param {Form} form - The Google Form to add to
* @param {string} question - The question text
* @param {Array} options - Array of answer options (for multiple choice)
* @param {string} type - The question type
*/
function addQuestionToForm(form, question, options, type) {
// Clean up the question text
question = question.replace(/^\d+\.\s/, ""); // Remove numbering if present
// Determine the question type if not specified
if (!type) {
type = options.length > 0 ?
FormApp.ItemType.MULTIPLE_CHOICE :
FormApp.ItemType.TEXT;
}
// Create the appropriate question item
var item;
switch (type) {
case FormApp.ItemType.MULTIPLE_CHOICE:
item = form.addMultipleChoiceItem();
item.setTitle(question);
item.setChoiceValues(options);
break;
case FormApp.ItemType.CHECKBOX:
item = form.addCheckboxItem();
item.setTitle(question);
item.setChoiceValues(options);
break;
case FormApp.ItemType.PARAGRAPH_TEXT:
item = form.addParagraphTextItem();
item.setTitle(question);
break;
case FormApp.ItemType.TEXT:
default:
item = form.addTextItem();
item.setTitle(question);
break;
}
// Set required based on question text
if (question.includes("(required)") || question.includes("*")) {
item.setRequired(true);
}
}
/**
* Initializes the logging sheet if it doesn't exist
* @return {Sheet} The logging sheet
*/
function initializeLogging() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var logSheet = ss.getSheetByName(LOG_SHEET_NAME);
if (!logSheet) {
logSheet = ss.insertSheet(LOG_SHEET_NAME);
logSheet.appendRow(["Timestamp", "Document Name", "Form URL", "Status"]);
}
return logSheet;
}
/**
* Logs a conversion attempt
* @param {Sheet} logSheet - The logging sheet
* @param {string} docName - Name of the document
* @param {string} formUrl - URL of the created form
* @param {string} status - Status message
*/
function logConversion(logSheet, docName, formUrl, status) {
logSheet.appendRow([
new Date(),
docName,
formUrl,
status
]);
}
/**
* Creates a custom menu in Google Docs for manual triggering
*/
function onOpen() {
var ui = DocumentApp.getUi();
ui.createMenu('Form Converter')
.addItem('Convert to Form', 'showConversionDialog')
.addToUi();
}
/**
* Shows a dialog to get user input for conversion
*/
function showConversionDialog() {
var html = HtmlService.createHtmlOutputFromFile('ConversionDialog')
.setWidth(400)
.setHeight(300);
DocumentApp.getUi().showModalDialog(html, 'Convert to Google Form');
}
/**
* Handles the form submission from the dialog
* @param {Object} formData - Data from the dialog form
*/
function handleDialogSubmit(formData) {
try {
var docId = DocumentApp.getActiveDocument().getId();
var formTitle = formData.formTitle || FORM_TITLE_PREFIX + DocumentApp.getActiveDocument().getName();
// Create a new form (we don't support updating existing forms in this simple dialog)
var form = FormApp.create(formTitle);
// Convert the document to form
var formUrl = convertDocToForm(docId);
// Return success message
return {
success: true,
message: "Form created successfully!",
url: formUrl
};
} catch (error) {
return {
success: false,
message: "Error creating form: " + error.toString()
};
}
}
HTML for Conversion Dialog (ConversionDialog.html)
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<style>
body {
font-family: Arial, sans-serif;
padding: 20px;
}
.form-group {
margin-bottom: 15px;
}
label {
display: block;
margin-bottom: 5px;
font-weight: bold;
}
input[type="text"] {
width: 100%;
padding: 8px;
box-sizing: border-box;
}
button {
background-color: #4285f4;
color: white;
border: none;
padding: 10px 15px;
border-radius: 4px;
cursor: pointer;
font-size: 14px;
}
button:hover {
background-color: #3367d6;
}
#status {
margin-top: 15px;
padding: 10px;
border-radius: 4px;
}
.success {
background-color: #d4edda;
color: #155724;
}
.error {
background-color: #f8d7da;
color: #721c24;
}
</style>
</head>
<body>
<h2>Convert Document to Form</h2>
<form id="conversionForm">
<div class="form-group">
<label for="formTitle">Form Title:</label>
<input type="text" id="formTitle" name="formTitle" placeholder="Enter form title">
</div>
<button type="button" id="submitBtn">Convert to Form</button>
</form>
<div id="status" style="display: none;"></div>
<script>
document.getElementById('submitBtn').addEventListener('click', function() {
var formTitle = document.getElementById('formTitle').value;
var statusDiv = document.getElementById('status');
// Show loading state
statusDiv.style.display = 'block';
statusDiv.className = '';
statusDiv.textContent = 'Converting document...';
google.script.run
.withSuccessHandler(function(response) {
if (response.success) {
statusDiv.className = 'success';
statusDiv.innerHTML = response.message + '<br><br><a href="' + response.url + '" target="_blank">Open Form</a>';
} else {
statusDiv.className = 'error';
statusDiv.textContent = response.message;
}
})
.withFailureHandler(function(error) {
statusDiv.className = 'error';
statusDiv.textContent = 'An error occurred: ' + error.message;
})
.handleDialogSubmit({formTitle: formTitle});
});
</script>
</body>
</html>
How to Use This Script
-
Setup:
- Open your Google Doc
- Go to Extensions > Apps Script
- Paste the main script code into the Code.gs file
- Create a new HTML file named "ConversionDialog" and paste the HTML code
- Save the project
-
Document Structure Requirements:
- Questions should be clearly marked as headings (bold, larger font, or ending with "?")
- Multiple-choice questions should have answer options as bullet points or numbered lists
- The script will automatically detect question types based on formatting and keywords
-
Running the Script:
- The script adds a custom menu "Form Converter" to your Google Doc
- Click "Convert to Form" to open the dialog
- Enter a title for your form and click the button to create it
-
Output:
- The script will create a new Google Form with your questions
- The form URL will be displayed in the dialog and logged in a spreadsheet
Supported Question Types
The script automatically detects and supports:
- Multiple-choice questions (with answer options as bullet points)
- Text questions (single-line answers)
- Paragraph questions (longer answers)
- Checkbox questions (multiple selections)
Error Handling
The script includes comprehensive error handling:
- Logs all conversion attempts with timestamps
- Handles empty lines and irregular formatting
- Provides feedback through the UI when run manually
Optional Enhancements Implemented
- Custom menu item in Google Docs
- User customization (form title)
- Logging system for tracking conversions
- Basic UI for manual triggering
You can extend this script further by adding more question type detection, supporting more complex document structures, or adding additional customization options.