How do I convert PDF to PNG images from the command line using Ghostscript?

1. A simple script (it does not set width for images)

gswin64c \
	-dBATCH \
	-dNOPAUSE \
	-dSAFER \
	-o %03d.png \
	-r600\
	-sDEVICE=png16m \
	input.pdf

2. A complex script (it allows to specify the width for the images)

export LC_ALL=C
input_pdf="test.pdf"
output_prefix="page"
desired_width_px=1000
# Check for Ghostscript
if command -v gs >/dev/null 2>&1; then
    GS_COMMAND="gs"
elif command -v gswin64c >/dev/null 2>&1; then
    GS_COMMAND="gswin64c"
else
    echo "Error: Ghostscript is not installed. Please install 'gs' or 'gswin64c' and try again." >&2
    exit 1
fi
# Check for other required utilities
for cmd in pdfinfo awk; do
    if ! command -v "$cmd" >/dev/null 2>&1; then
        echo "Error: Utility '$cmd' is not installed. Please install it and try again." >&2
        exit 1
    fi
done
# Get total number of pages in PDF
num_pages=$(pdfinfo "$input_pdf" 2>/dev/null | awk '/^Pages:/ {print $2}' | tr -d '\r')
if [ -z "$num_pages" ]; then
    echo "Failed to determine the number of pages in the PDF file." >&2
    exit 1
fi
for (( page=1; page<=num_pages; page++ )); do
    # Get page information
    page_info=$(pdfinfo -f "$page" -l "$page" "$input_pdf" 2>/dev/null)
    # Extract page size line
    page_size_line=$(echo "$page_info" | awk '/^Page[^:]*size:/ {print}' | tr -d '\r')
    # Extract page width and height in points
    width_pts=$(echo "$page_size_line" | sed -n 's/.*size:[[:space:]]*\([0-9.]*\) x [0-9.]* pts.*/\1/p' | tr -d '\r')
    height_pts=$(echo "$page_size_line" | sed -n 's/.*size:[[:space:]]*[0-9.]* x \([0-9.]*\) pts.*/\1/p' | tr -d '\r')
    # Check that dimensions were correctly extracted
    if [ -z "$width_pts" ] || [ -z "$height_pts" ]; then
        echo "Failed to determine dimensions of page $page." >&2
        continue
    fi
    # Calculate required height in pixels to maintain aspect ratio
    height_px=$(awk "BEGIN { printf(\"%.0f\", $desired_width_px * $height_pts / $width_pts) }")
    # Convert page to PNG with specified dimensions
    "$GS_COMMAND" \
        -q \
        -dSAFER \
        -dBATCH \
        -dNOPAUSE \
        -sDEVICE=png16m \
        -dFirstPage="$page" \
        -dLastPage="$page" \
        -g${desired_width_px}x${height_px} \
        -dPDFFitPage \
        -o "${output_prefix}_$(printf '%03d' "$page").png" \
        "$input_pdf" \
        >/dev/null 2>&1
    # Check if Ghostscript command was successful
    if [ $? -ne 0 ]; then
        echo "Error processing page $page." >&2
    fi
done

How do I extract specific pages from a PDF file using Ghostscript from the command line?