mozilla/pdf.js · error · TypeError

First argument of printf must be a string

Error message

First argument of printf must be a string

What it means

Thrown by `Util.printf()` (src/scripting_api/util.js:70) as a `TypeError` when the first argument is present but not a string. The first argument is the format template containing `%d`, `%f`, `%s`, `%x` conversion specifiers; only strings can carry those specifiers.

Source

Thrown at src/scripting_api/util.js:70

  MILLISECONDS_IN_DAY = 86400000;

  MILLISECONDS_IN_WEEK = 604800000;

  constructor(data) {
    super(data);

    // used with crackURL
    this._externalCall = data.externalCall;
  }

  printf(...args) {
    if (args.length === 0) {
      throw new Error("Invalid number of params in printf");
    }

    if (typeof args[0] !== "string") {
      throw new TypeError("First argument of printf must be a string");
    }

    // eslint-disable-next-line regexp/no-misleading-capturing-group
    const pattern = /%(,[0-4])?([+ 0#]+)?(\d+)?(\.\d+)?(.)/g;
    const PLUS = 1;
    const SPACE = 2;
    const ZERO = 4;
    const HASH = 8;
    let i = 0;
    return args[0].replaceAll(
      pattern,
      function (_, nDecSep, cFlags, nWidth, nPrecision, cConvChar) {
        // cConvChar must be one of d, f, s, x
        if (
          cConvChar !== "d" &&
          cConvChar !== "f" &&
          cConvChar !== "s" &&
          cConvChar !== "x"

View on GitHub (pinned to 5903d58d58)

Solutions

  1. Ensure the first argument is always a string literal or `String(x)`.
  2. Coerce defensively: `util.printf(String(fmt), ...rest)`.
  3. Add a type check at the call site and bail out early if `fmt` is not a string.

Example fix

// before
util.printf(value, '%d'); // format string in the wrong slot
// after
util.printf('%d', value);
Defensive patterns

Strategy: type-guard

Validate before calling

function printfSafe(util, fmt, ...rest) {
  if (typeof fmt !== 'string') return String(fmt ?? '');
  return util.printf(fmt, ...rest);
}

Type guard

function isFormatString(args) {
  return args.length > 0 && typeof args[0] === 'string';
}

Prevention

When it happens

Trigger: Calling `util.printf(42, ...)`, `util.printf(someObject, ...)`, or passing a number that was meant to be the first converted value but landed in the format slot because the real format string was dropped.

Common situations: Argument-shift bugs where the format string was omitted but values were kept; building the format from a non-string concatenation that produced a number; mis-ordered variadic spreads.

Related errors


AI-assisted analysis of mozilla/pdf.js@5903d58d58 (2026-08-13). Data as JSON: /api/errors/9afaad6dec730c49. Report an issue: GitHub.