Skip to content

AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents

1.4 KB
Raw Blame
import { PDFPage } from 'pdf-lib';

/**
 * Resolves which pages to apply the stamp to based on user input.
 */
export function getTargetPages(
  pages: PDFPage[],
  applyToAllPages: boolean = false,
  pageNumber?: number,
  itemName: string = 'Item'
): PDFPage[] {
  const totalPages = pages.length;

  if (applyToAllPages) {
    return [...pages];
  }

  if (pageNumber === undefined) {
    throw new Error(`Page Number is required when "Apply to All Pages" is not checked for ${itemName}.`);
  }

  const pageIndex = Number(pageNumber) - 1;
  
  if (pageIndex < 0 || pageIndex >= totalPages) {
    throw new Error(`You requested Page ${pageNumber} for ${itemName}, but this document only has ${totalPages} page(s).`);
  }

  return [pages[pageIndex]];
}

/**
 * Maps visual coordinates (Top/Left) to pdf-lib intrinsic coordinates based on page rotation.
 */
export function mapVisualToIntrinsic(
  vX: number,
  anchorY: number, 
  vWidth: number,
  vHeight: number,
  rotationAngle: number
) {
  let iX = vX;
  let iY = anchorY;
  let mappedRotation = 0;

  if (rotationAngle === 90) {
    iX = vHeight - anchorY; 
    iY = vX;
    mappedRotation = 90;
  } else if (rotationAngle === 180) {
    iX = vWidth - vX;
    iY = vHeight - anchorY;
    mappedRotation = 180;
  } else if (rotationAngle === 270) {
    iX = anchorY;
    iY = vWidth - vX;
    mappedRotation = -90;
  }

  return { iX, iY, mappedRotation };
}