Labelary API returns blank pdf used with Google Apps Script

41 Views Asked by At

I am using Google Apps Scripts to create labels from my google sheets. I am sending requests to the Labelary API so they can turn my zpl code into pdf. But unfortunately the returned PDF is just blank when I open it.

This is my current implementation with a test function:

function testPdfConversion() {
  var zpl = "^xa^cfa,50^fo100,100^fdHello World^fs^xz"
  var labelPdf = convertToPdf(zpl.toString())
  DriveApp.getFoldersByName("Labels").next().createFile("Test.pdf", labelPdf.getAs('application/pdf').getDataAsString())
}

function convertToPdf(label) {
  const url = "http://api.labelary.com/v1/printers/8dpmm/labels/4x6/0/";

  const options = {
    'method': 'POST',
    'headers': { 'Accept': 'application/pdf', 'X-Linter': 'On'},
    'Content-Type': 'application/x-www-form-urlencoded',
    'payload': JSON.stringify(label)};

  const response = UrlFetchApp.fetch(url, options);
  return response;
}

This is just for testing, but it should create a label with 'Hello World' written on it and when I try it with curl it works. The content of both pdfs (curl and apps script) is almost the same.

Anyone got an idea what I did wrong?

1

There are 1 best solutions below

0
Tanaike On BEST ANSWER

I thought that from your script, the blob can be retrieved from the object returned by UrlFetchApp.fetch(url, options). So, how about the following modification?

Modified script:

In this modification, the function testPdfConversion() was modified.

function testPdfConversion() {
  var zpl = "^xa^cfa,50^fo100,100^fdHello World^fs^xz";
  var labelPdf = convertToPdf(zpl.toString());
  
  // I modified the below script.
  DriveApp.getFoldersByName("Labels").next().createFile(labelPdf.getBlob().setName("Test.pdf"));
}

function convertToPdf(label) {
  const url = "http://api.labelary.com/v1/printers/8dpmm/labels/4x6/0/";
  const options = {
    'method': 'POST',
    'headers': { 'Accept': 'application/pdf', 'X-Linter': 'On' },
    'Content-Type': 'application/x-www-form-urlencoded',
    'payload': JSON.stringify(label)
  };
  const response = UrlFetchApp.fetch(url, options);
  return response;
}

When I tested this script, it seems that a PDF file including "Hello World" is created in the folder of Labels.

References: