Adding Page Numbers to PDF using Google Apps Script

Gists

Adding Page Numbers to PDF using Google Apps Script

Description

This is a simple sample script for adding the page numbers to PDF data using Google Apps Script.

When you use this script, please copy and paste the following script to the script editor of Google Apps Script. And, please set the file ID of the PDF file.

Sample script

In this script, pdf-lib is used.

/**
 * ### Description
 * Add page numbers to PDF.
 *
 * @param {Object} blob PDF blob.
 * @param {Object} pageFormat Format of page number.
 * @returns {Blob} Updated PDF blob.
 */
async function addPageNumbers_(blob, pageFormat) {
  if (blob.getContentType() != MimeType.PDF) {
    throw new Error("Blob is not PDF.");
  }

  // Load pdf-lib
  const cdnjs = "https://cdn.jsdelivr.net/npm/pdf-lib/dist/pdf-lib.min.js";
  eval(
    UrlFetchApp.fetch(cdnjs)
      .getContentText()
      .replace(
        /setTimeout\(.*?,.*?(\d*?)\)/g,
        "Utilities.sleep($1);return t();"
      )
  );

  const data = new Uint8Array(blob.getBytes());
  const pdfData = await PDFLib.PDFDocument.load(data);
  const pdfDoc = await PDFLib.PDFDocument.create();
  (await pdfDoc.copyPages(pdfData, pdfData.getPageIndices())).forEach(
    (page, i) => {
      const { width } = page.getSize();
      const obj = { center: width / 2, left: 20, right: width - 20 };
      const pageFormatObj = { ...pageFormat };
      pageFormatObj.x = obj[pageFormat.x];
      page.drawText(`${i + 1}`, pageFormatObj);
      pdfDoc.addPage(page);
    }
  );
  const bytes = await pdfDoc.save();
  return Utilities.newBlob(
    [...new Int8Array(bytes)],
    MimeType.PDF,
    `new_${blob.getName()}`
  );
}

// Please run this function.
function sample1() {
  const fileId = "###"; // Please set the file ID of the PDF file.
  const pdfBlob = DriveApp.getFileById(fileId).getBlob(); // Of course, you can directly give the PDF blob.

  const pageFormat = { size: 10, x: "center", y: 10 };
  addPageNumbers_(pdfBlob, pageFormat).then((newBlob) =>
    DriveApp.createFile(newBlob)
  );
}

// This function is a simple demonstration script.
function sample2() {
  // Create a sample Google Document.
  const tempDoc = DocumentApp.create("tempDoc");
  const body = tempDoc.getBody();
  for (let p = 0; p < 5; p++) {
    body.appendParagraph(`sample text ${p + 1}`).appendPageBreak();
  }
  tempDoc.saveAndClose();
  const pdfBlob = tempDoc.getBlob();

  // Add page numbers.
  const pageFormat = { size: 10, x: "center", y: 10 };
  addPageNumbers_(pdfBlob, pageFormat).then((newBlob) =>
    DriveApp.createFile(newBlob)
  );
}
  • When you run the function sample1, the page numbers are added to the center of each page.
  • When you run the function sample2, a new Google Document is created including 5 pages. And, the page numbers are added to the center of each page.
  • In this sample, a simple format like { size: 10, x: "center", y: 10 } is used for the page numbers. Here, the page numbers are put to only “left”, “center”, and “right” of the bottom of the page. But, there are various parameters in DrawTextOptions. Ref So, when you want to customize more, please modify the script.

Leveraging Gemini 1.5 API for Automated Test Case Generation in Google Apps Script Reverse Engineering

Gists

Leveraging Gemini 1.5 API for Automated Test Case Generation in Google Apps Script Reverse Engineering

Abstract

This report examines leveraging Gemini 1.5 API with Google Apps Script to automate sample input creation during script reverse engineering. Traditionally, this process is manual and time-consuming, especially for functions with numerous test cases. Gemini 1.5 API’s potential to streamline development by automating input generation is explored through applying reverse engineering techniques to Google Apps Script samples.

Gemini API with JSON schema

Gists

Overview

These are sample scripts in Python and Node.js for controlling the output format of the Gemini API using JSON schemas.

Description

In a previous report, “Taming the Wild Output: Effective Control of Gemini API Response Formats with response_mime_type,” I presented sample scripts created with Google Apps Script. Ref Following its publication, I received requests for sample scripts using Python and Node.js. This report addresses those requests by providing sample scripts in both languages.

Updated: GAS Library - GeminiWithFiles

GeminiWithFiles was updated to v1.0.2.

  • v1.0.2 (May 7, 2024)

    1. For generating content, parts was added. From this version, you can select one of q, jsonSchema, and parts.
    2. From this version, systemInstruction can be used.
    3. In order to call the function call, toolConfig was added to the request body.

You can see the detail information here https://github.com/tanaikech/GeminiWithFiles

Inserting Animated GIFs over Cells on Google Sheets using Google Apps Script

Gists

Overview

This script demonstrates how to insert an animated GIF over cells in a Google Sheet using Google Apps Script.

Description

I recently received a request to create a Google Apps Script for inserting animated GIFs into cells on a Google Sheet. I previously published a sample script on my blog on June 6, 2017. Ref In that script, the animation GIF was inserted using a public link. This new script leverages data URLs, which simplifies the process for using GIFs stored in Google Drive. Since this approach might be helpful to others, I’m sharing it here.

Taming the Wild Output: Effective Control of Gemini API Response Formats with response_mime_type

Gists

Taming the Wild Output: Effective Control of Gemini API Response Formats with response_mime_type

Abstract

This report explores controlling output formats for the Gemini API. Traditionally, prompts dictated the format. A new property, “response_mime_type”, allows specifying the format (e.g., JSON) directly. Testing confirms this property improves control over output format, especially for complex JSON schemas. The recommended approach is to combine a detailed JSON schema with “response_mime_type” for clear and consistent outputs.

GAS Library - GeminiWithFiles

Overview

This is a Google Apps Script library for Gemini API with files.

A new Google Apps Script library called GeminiWithFiles simplifies using Gemini, a large language model, to process unstructured data like images and PDFs. GeminiWithFiles can upload files, generate content, and create descriptions from multiple images at once. This significantly reduces workload and expands possibilities for using Gemini.

Description

Recently, Gemini, a large language model from Google AI, has brought new possibilities to various tasks by enabling the use of unstructured data as structured data. This is particularly significant because a vast amount of information exists in unstructured formats like text documents, images, and videos.