Franco Vera
Franco Vera

Reputation: 67

Problem with Printing Google SheetsData from Google Apps Script

I'm trying to print a cell range from my Google Sheets using Google Apps Script that I have already set on a button in the sheet. However, I can't manage to create the PDF properly and print it. I try to download it, but it doesn't work either.

Here it's my code:

var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = spreadsheet.getSheetByName("Impresión de Etiquetas");
  var rangeToExport  = sheet.getRange("A16:G29");
  
  // Configurar la impresión de la hoja
  var gid = sheet.getSheetId();
  var options = {
    'size': 'A4',
    'portrait': true,
    'fitw': true,
    'sheetnames': false,
    'printtitle': false,
    'pagenum': 'UNDEFINED',
    'gridlines': true
  };

   // Obtener los valores del rango
  var values = rangeToExport.getValues();
  
  // Crear un archivo PDF a partir de los valores
  var pdfFile = DriveApp.createFile("ImpresionEtiquetas.pdf", values.join("\n"), "application/pdf");
  
  // Abre el PDF para imprimirlo manualmente
  var pdfUrl = pdfFile.getUrl();
  var htmlOutput = HtmlService.createHtmlOutput('<a href="' + pdfUrl + '" target="_blank">Haga clic aquí para abrir el PDF y luego imprímalo manualmente</a>');
  SpreadsheetApp.getUi().showModalDialog(htmlOutput, 'Impresión de Etiquetas.pdf');
}

The error here:

Translation: Could not get a preview of the file You may be offline or have limited connectivity. Try to download the document.

enter image description here

Upvotes: 0

Views: 168

Answers (1)

Serenity
Serenity

Reputation: 753

Recommendation:

As per replicating using your script, we found a workaround that when you click "Open to Google Docs" and go to your Drive then you can now preview the file. Also we notice that there's no formatting on your file.

I have created an alternative script for you that you can use:

function myFunction() {
      var ss = SpreadsheetApp.getActiveSpreadsheet();
      var sheet = ss.getSheetByName('Impresión de Etiquetas');
      var rangeToExport  = "A16:G29";
      var gid = ss.getSheetId();
      var ssId = ss.getId();
      var ssId = ss.getId();
      var fileName = sheet.getName();
      const url = "https://docs.google.com/spreadsheets/d/" 
      + ssId + "/export" +"?format=pdf&amp;" + "gid=" + gid + "&amp;range=" 
      + rangeToExport +"&amp;"
      + "size=a4&amp;" 
      + "fzr=true&amp;" 
      + "portrait=true&amp;" 
      + "fitw=true&amp;" 
      + "pageorder=1&amp;"
      + "gridlines=true&amp;" 
      + "printtitle=false&amp;" 
      + "sheetnames=false&amp;" 
      + "pagenum=false&amp;" 
      + "attachment=true";
      
    
      var htmlOutput = HtmlService.createHtmlOutput('<a href="' + url + '" target="_blank">Haga clic aquí para abrir el PDF y luego imprímalo manualmente</a>');
      SpreadsheetApp.getUi().showModalDialog(htmlOutput, 'Impresión de Etiquetas.pdf');
    }

References:

Upvotes: 1

Related Questions