обернуть содержимое документа Google с помощью div и превратить в html-файл

Я пытаюсь превратить файл документов Google в html-файл. Я дал HTML-теги контенту через документы Google (h1, h2, p и т. д.), а затем загрузил его в виде HTML-файла, и он отлично работает.

У меня есть одна проблема: я хочу обернуть определенное содержимое в моем файле документа Google с помощью div, например, div для каждой главы. Прямо сейчас файл представляет собой просто список html-тегов (h1, p, h2 и т. д.), и мне нужно, чтобы он был более правильным иерархически.

Есть ли способ сделать это? Я пытался использовать разрыв страницы и другие подобные параметры, но он просто добавляет еще один элемент в список, а не оборачивает определенный контент в div, как я хочу. Решение javascript тоже будет хорошим.

Буду признателен за любую помощь, Спасибо! Нир


person nirshh5    schedule 01.03.2021    source источник


Ответы (1)


Вы можете попробовать этот подход на скрипте Google Apps. Это никоим образом не единственное решение. Это всего лишь простой код, который вы можете попробовать из многих возможных решений. Не стесняйтесь изменять, если это необходимо, в зависимости от вашего варианта использования.

Код:

function myFunction() {
  var doc = DocumentApp.getActiveDocument();
  var content = doc.getBody();
  var numChildren = content.getNumChildren();
  var output = [];
  // Send email to this address
  var sendTo = "[email protected]"; 

  output.push("<html><body>");
  for(var i=0; i < numChildren; i++){
    var item = content.getChild(i).asText();
    var text = item.getText();

    // Assuming that a chapter always starts in bold headers, we start the div there
    if(item.isBold()) {
      // Add opening div tags on every start of header, see doc format below
      output.push('<div>');
      output.push('<h1>' + text + '</h1>');
    }
    // If not bold, then that element is assumed as the content of the chapter
    else if (text){
      output.push('<p>' + text + '</p>');
    }
  }
  output.push("</body></html>");

  // Get all indices where div is (except the first) and reverse
  var indexes = getAllIndexes(output, "<div>");
  // Per div found, insert closing div tag </div> before it
  indexes.forEach(function(index){
    output.splice(index, 0, "</div>");
  });

  // Join output array and treat it as html
  var html = Utilities.newBlob(output.join(""), 'text/html', 'doc_to_html.html');
  // Send to your email (modify email above if needed) the converted file with div tags
  MailApp.sendEmail(sendTo, "Attached html-converted document", "file is attached below", {name: 'doc-to-html', attachments: [html], noReply: true});
}

function getAllIndexes(arr, val) {
    var indexes = [], i = -1;
    while ((i = arr.indexOf(val, i+1)) != -1){
        indexes.push(i);
    }
    // Remove the first index (we don't need to add closing divs before the first div)
    indexes.shift();
    // Return reversed indices since we will add from the end since we are inserting closing div tags (</div>)
    // Inserting from the start will change the indices of those succeeding opening div tags (<div>) we need to close
    return indexes.reverse();
}

Эл. адрес:

выход1

HTML-вложение:

выход2

Примечание:

  • Предполагалось, что каждая глава имеет один заголовок в начале (здесь мы вставляем <div>) и абзац/ы под ним. Закрывающие теги div </divs> вставляются перед каждым найденным тегом <div>.
person NaziA    schedule 01.03.2021