Skip to main content

Command Palette

Search for a command to run...

Unlock multiple pdf and merge them using bash script

Published
1 min read
M

To live in hearts we leave behind is not to die

#!/bin/bash

# Check for input files
if [ $# -eq 0 ]; then
  echo "Usage: $0 file1.pdf file2.pdf ..."
  exit 1
fi

# Read password securely
read -sp "Enter PDF password: " password
echo

# Create temporary directory
temp_dir=$(mktemp -d)

# Decrypt all PDFs
decrypted_files=()
for file in "$@"; do
  if [ ! -f "$file" ]; then
    echo "Error: $file not found!"
    exit 1
  fi

  output="$temp_dir/decrypted_$(basename "$file")"
  qpdf --decrypt --password="$password" "$file" "$output"
  decrypted_files+=("$output")
done

# Merge decrypted PDFs
pdftk "${decrypted_files[@]}" cat output "merged.pdf"

# Cleanup
rm -r "$temp_dir"
echo "Success! Merged PDF saved as 'merged.pdf'"

This automatically ask for password. You have to run the script with file-names separate by space.

Note: All pdf must be using same password. Ideal for bank statement whom are locked using same password by bank.