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.

Batch Processing Powerhouse: Leverage Gemini 1.5 API and Google Apps Script for Efficient Content Workflows

Gists

Batch Processing Powerhouse: Leverage Gemini 1.5 API and Google Apps Script for Efficient Content Workflows

Abstract

A new Google Apps Script library, “GeminiWithFiles”, simplifies using the powerful Gemini 1.5 AI model. It lets users directly upload files for content generation or create descriptions for many images at once, making it much faster than prior methods. This is helpful for tasks involving large amounts of text or images.

Introduction

Recently, Gemini, a family of Google’s most capable AI models, has revolutionized various tasks by allowing unstructured data to be used as structured data. This breakthrough is particularly impactful for tasks involving large amounts of text or images.

Google OAuth Verification & Application Privacy Policy

Registered Application Name: Workspace & Gemini AI Orchestration Engine

Application Purpose & Core Functionality:

This web page serves as the official homepage and privacy compliance interface for the application "Workspace & Gemini AI Orchestration Engine". This specialized developer utility is designed to research, benchmark, and optimize advanced integrations between Google Workspace services, the Google Apps Script API, and Gemini AI models (via Google Vertex AI / Gemini API endpoints).

The application facilitates automated multi-agent scaffolding, programmatic script deployment, project resource management, and structural analysis of Google Apps Script projects. It allows developers and autonomous AI agents (operating via Model Context Protocol / MCP) to securely evaluate execution performance, implement high-performance batch requests, and test agent-to-agent (A2A) workflows within a controlled and structured environment.

Google User Data Policy Compliance Statements:

1. Data Access & Specific Usage

Our application explicitly requests access to specific Google user accounts through OAuth scopes required strictly for interacting with the Google Apps Script API and Google Workspace endpoints. This access is utilized solely to execute user-initiated or agent-orchestrated programmatic operations—such as creating, modifying, deploying, or benchmarking script projects and executing automated workflows. No background automated extraction occurs without explicit session initiation.

2. Data Storage & Zero-Retention Policy

Adhering to a strict Zero-Retention Model, this application does not store, log, or persist any personal data, OAuth tokens, script source codes, or Google account configurations on any external server, database, or persistent storage medium. All data processing and API responses are handled entirely in-memory or securely on the client side within the active session context, ensuring complete cryptographic transient isolation.

3. Data Sharing & Third-Party Non-Disclosure

We maintain absolute data privacy. No data accessed via Google OAuth scopes is shared, sold, rented, or transferred to third-party entities, advertising networks, or data brokers. All data transmissions are strictly point-to-point, encrypted in transit using industry-standard protocols, and limited entirely to the direct channel between the execution environment and Google's official API gateways.

For inquiries regarding this developer application, technical benchmarks, or verification compliance, please refer to the official documentation and repositories linked on this homepage (tanaikech.github.io).