How can I generate a multipage text document from a single page template in google-apps-script?
Asked Answered
O

3

10

I have to generate labels from a list of user data stored in a spreadsheet. Right now I get everything working nicely except that when I output more than 16 items (the number of labels per page) I have more than one document, each of them being a single page. Each doc has a unique name so it's not very hard to use but it's kind of boring to open so many documents to print them. Since I don't want to create a template of 500 items (or whatever number) I was wondering if I could repeat this single page template in a multi-page document to any extend so I get all the labels in one single document. This would be far more comfortable to print ;-) I couldn't find any clue up to now... any brilliant idea ? here is the code I use to generate the docs ( a bit long, sorry about that) :

and ... many thanks for any help.

function print(e){
  var app = UiApp.getActiveApplication();
  var selrangerow = sh.getActiveSelection().getRowIndex();
  var selrangeheight = sh.getActiveSelection().getNumRows();
  var selrangeend = selrangerow+selrangeheight-1
  var selrange = sh.getRange(selrangerow,1,selrangeheight,7).getValues();
  var feuilles = Math.ceil(selrangeheight/16);
  for (ff=1;ff<=feuilles*16;++ff){
  if(ff>selrange.length){selrange.push([" "," "," "," "," "," "," "])} ;// remplit selrange jusqu'à multiple de 16 (nbre de feuille)
  }
//Logger.log(selrange)
//Logger.log(e.parameter.mode) ;// gauche=true, centre = false
  if(e.parameter.mode=='false'){
  var doctemplate = DocsList.getFileById(labeltemplatedoc);// false >> centre
  }else{
  var doctemplate = DocsList.getFileById(labeltemplatedocleft);// true >> gauche
  }
//Logger.log("File name: " + doctemplate.getName()); 
  var FUS1=new Date().toString().substr(25,8);// FUS1 gets the GMT+0200 or GMT+0100 string
  if (FUS1!="GMT+0200"){FUS1="GMT+0100"};// and takes care of summer time !
    for(page=0;page<feuilles;++page){
      var today=Utilities.formatDate(new Date(),FUS1,"dd-MM-yyyy")+"__"+Utilities.formatDate(new Date(),FUS1,"HH:mm")
      if (Number(page+1)<10){var docnb="0"+Number(page+1)}else{var docnb=Number(page+1)}
      var docname="IMPRESSION_page_"+docnb+"_"+today;
      var docId=DocsList.copy(doctemplate,docname).getId();
//Logger.log(selrange)  
      var doc = DocumentApp.openById(docId);;
      var lib=["titre","nom","prénom","rue","code","ville","pays"]
        for(nn=1;nn<=16;++nn){
          for(ll=0;ll<lib.length;++ll){
            var olditem = ("#"+lib[ll]+nn+"#");
            var newitem = selrange[nn-1+page*16][ll];
             if (newitem!=""){newitem=newitem+" "}
//Logger.log(olditem + "   *"+newitem+"*")
              doc.replaceText(olditem,newitem);
         }
       }
      Utilities.sleep(300); // pause entre les feuilles
    } 
   app.getElementById("end").setText(feuilles+" feuille(s) se trouve(nt) dans vos documents Google prête(s) à être imprimée(s).");
    var doclist=DocsList.getRootFolder().getFilesByType("document",0,2000);
    var names = new Array();
      for (nn=0;nn<doclist.length;++nn){
        if(doclist[nn].getName().match("IMPRESSION_page_")=="IMPRESSION_page_"){
      names.push([doclist[nn].getName(),doclist[nn].getId()]);
      }
      }
    names.sort();
 for(nn=0;nn<names.length;++nn){
 app.getElementById("Dlb").addItem(names[nn][0])
 }
   app.getElementById("clock").setVisible(false);
   app.getElementById("Dlb").setVisible(true);
   return app
}
//
Ostap answered 21/5, 2012 at 21:10 Comment(0)
H
14

Well Serge, haven't you tried the appendParagraph and other appends of the DocumentBodySection?

I'd do it like this:

function mergeDocs() {
  var docIDs = ['list-of','documents','ids','you should have somehow'];
  var baseDoc = DocumentApp.openById(docIDs[0]);
  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("According to the doc this type couldn't appear in the body: "+type);
    }
  }
}
Hiatus answered 31/5, 2012 at 12:14 Comment(3)
Thanks Henrique, I thought that merging document would be a track to follow but I admit I'm not too comfortable with docs and elementType... With your code I'm sure I'll get what I wanted ;-)Ostap
This worked for Paragraphs and List Items, but the Table elements lost their formatting.Tolbutamide
Can't we have something simpler like target.editAsText().appendText(source.editAsText().copy()) ?Cristencristi
H
1

Your question sounds similar to one (Issue with creating an “old-fashioned” mail merge with Google Apps Script) that I asked a couple of weeks ago. The best way that I was told to create the document was to create the entire thing via script and to not use a document template.

Highclass answered 22/5, 2012 at 16:22 Comment(2)
Thanks for your answer but I don't think its possible to create a printable doc compatible with labels without using a template... measures have to be quite accurate to match the precut adesive sheets :-/. If you're right and that there is no other option I'll keep generating plenty of new sheets. Or maybe I could try to merge docs into one in a second step ?Ostap
@willw thank you for your answer: can you elaborate on what you mean by creating the entire combined document by script - do you have any code etc which helps does this?Kanishakanji
S
0

Working on something similar and also having issues with inline images and other formating details.

I'm thinking that a way around it, although not the cleanest solution may:

  • create a copy of the template document for each row of data
  • replace the markers with the row data for each copied document
  • merge the documents together for ease of printing
  • delete the copies made

I guess for a small amount of documents it may work but not sure how it would handle 500 cases as you mention above.

Sanbenito answered 4/5, 2021 at 14:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.