ron
ron

Reputation: 43

Google App Script - merge multiple documents, remove all line breaks and sent as pdf by Email

Am using Google App Script and have successfully managed to merge multiple documents from one folder into one document and remove all line breaks while keeping all styling intact.

Where i need some help is, how to send the document by mail, after the removeMultipleLineBreaks(element) function has finished.

Can someone help me to archive this: (This is a Spreadsheet Script connected to a Form, Spreadsheet receives Form responses)

onFormSubmit trigger the mergeDocument. After merging all documents, removeMultipleLineBreaks and when finished, use the submitted Email from form to send a pdf version of the document to the user.

this is the Script code which is working.

function mergeGoogleDocs() {
// set folder ID were we should look for files to merge  
  var folder = DriveApp.getFolderById('0BwqMAWnXi8hMmljM3FZpaowb1'); 
  var docIDs = [];
  var files = folder.getFiles();

  while (files.hasNext()){
    file = files.next();
    docIDs.push(file.getId());
  }
// check if we have some ids  
  Logger.log(docIDs); 
// set document id of doc which will contain all merged documents  
  var baseDoc = DocumentApp.openById('0BwqMAWnXi8hMmljM3FZpaowb1');
// clear the whole document and start with empty page
  baseDoc.getBody().clear();
  var body = baseDoc.getActiveSection();

  for (var i = 1; i < docIDs.length; ++i ) {
    var otherBody = DocumentApp.openById(docIDs[i]).getActiveSection();    
    var totalElements = otherBody.getNumChildren();
    for( var j = 0; j < totalElements; ++j ) {
      var element = otherBody.getChild(j).copy();
      var type = element.getType();
      if( type == DocumentApp.ElementType.PARAGRAPH )
        body.appendParagraph(element);
      else if( type == DocumentApp.ElementType.TABLE )
        body.appendTable(element);
      else if( type == DocumentApp.ElementType.LIST_ITEM )
        body.appendListItem(element);
      else
        throw new Error("Unknown element type: "+type);
    }
  }
// after merging all docs, invoke function to remove all line breaks in the just merged document
  removeMultipleLineBreaks();
}


function removeMultipleLineBreaks(element) {
  if (!element) {
    // set document id of doc where to remove all line breaks 
    element = DocumentApp.openById('0BwqMAWnXi8hMmljM3FZpaowb1').getBody();
  }
  var parent = element.getParent();
  // Remove empty paragraphs
  if (element.getType() == DocumentApp.ElementType.PARAGRAPH 
      && element.asParagraph().getText().replace(/\s/g, '') == '') {
    if (!(parent.getType() == DocumentApp.ElementType.BODY_SECTION 
         && parent.getChildIndex(element) == parent.getNumChildren() - 1)) {
      element.removeFromParent();
    }
  // Remove duplicate newlines in text
  } else if (element.getType() == DocumentApp.ElementType.TEXT) {
    var text = element.asText();
    var content = text.getText();
    var matches;
    // Remove duplicate carriage returns within text.
    if (matches = content.match(/\r\s*\r/g)) {
      for (var i = matches.length - 1; i >= 0; i--) {
        var match = matches[i];
        var startIndex = content.lastIndexOf(match);
        var endIndexInclusive = startIndex + match.length - 1;
        text.deleteText(startIndex + 1, endIndexInclusive);
      }
    }
    // Grab the text again.
    content = text.getText();
    // Remove carriage returns at the end of the text.
    if (matches = content.match(/\r\s*$/)) {
      var match = matches[0];
      text.deleteText(content.length - match.length, content.length - 1);
    }
    // Remove carriage returns at the start of the text.
    if (matches = content.match(/^\s*\r/)) {
      var match = matches[0];
      text.deleteText(0, match.length - 1);
    }
  // Recursively look in child elements
  } else if (element.getNumChildren) {
    for (var i = element.getNumChildren() - 1; i >= 0; i--) {
      var child = element.getChild(i);
      removeMultipleLineBreaks(child);
    }
  }
}

Upvotes: 2

Views: 7695

Answers (2)

Alan Wells
Alan Wells

Reputation: 31300

Call the email function:

  }
  // after merging all docs, invoke function to remove all line breaks in the just merged document
  removeMultipleLineBreaks();

  //email document
  emailDocument();
}

The email function:

function emailDocument() {
  //Replace this email address with your own email address
  var email = "[email protected]"; 

  var fileToAttach = DriveApp.getFileById('Put your file ID here').getAs('application/pdf');

  var message = "This is a test message";
  var subject = "New Merged Document";

 // Send an email with an attachment: a file from Google Drive
 MailApp.sendEmail(email, subject, message, {
     attachments: [fileToAttach]
 });
}

Upvotes: 1

Heemps
Heemps

Reputation: 1

Append the following to your removeMultipleLineBreaks();

\\Save and close the document.
baseDoc.saveAndClose();

Call the SendAttachment function. SendAttachment();

function SendAttachment(){
\\Create the PDF
var pdf = DriveApp.getFileByID('your file ID').getAs("application/pdf");

\\Attach the PDF and send the email
var subject = "Insert Subject here");
var body = "Insert the HTML body here");

MailApp.sendEmail({
to: "insert primary recipient email address",
cc: "insert cc recipient email address",
replyTo: "insert the replyto email address",
subject: subject, 
htmlBody: body + "<br>",
attachments: pdf, 
});
}

Upvotes: 0

Related Questions