PDF-cropping and printing (gs and lp) printing the wrong section, but works using GUI

36 Views Asked by At

I've written a small script - on MacOS - designed to do two fairly simple things - crop a PDF (a 4 x 6 shipping label) at a given file path, and then print it. I'm using ghostscript for the cropping, and the lp tool to print.

I have verified the crop box by opening the cropped PDF in MacOS Preview - and if I print using the Preview GUI, everything works as expected. However, printing the same file via lp results in a different area of the PDF being printed (I couldn't be sure, but it's as though it's counting the Y axis from the bottom left corner, rather than the top left).

I'd really like to get the printing via lp step working, since the whole point was to avoid the pointing and clicking to select paper sizes etc.

The printer is a Munbyn P130 (which appears in lpstat as ITPP130_Printer_1. The code is below - I've googled extensively and even asked ChatGPT to help, all to no real progress. I'd very much appreciate whatever help can be given!

#!/bin/bash

# Check if URL is provided
if [ "$#" -ne 1 ]; then
    echo "Usage: $0 <URL>"
    exit 1
fi

# Configuration
URL=$1
TEMP_DIR="/tmp"
PRINTER_NAME="ITPP130_Printer_1"  # Replace with your printer name
CROPPED_PDF_PATH="$TEMP_DIR/cropped.pdf"
DOWNLOADED_PDF_PATH="$TEMP_DIR/downloaded.pdf"

# Download the PDF
curl -o "$DOWNLOADED_PDF_PATH" "$URL"

# Check if download was successful
if [ ! -f "$DOWNLOADED_PDF_PATH" ]; then
    echo "Failed to download the PDF."
    exit 1
fi

# Crop the PDF (left-most 4" and uppermost 6")
# A4 size: 595 x 842 points
# Crop area: 4" x 6" -> 288 x 432 points
# Bottom Y-coordinate: 842 (total height) - 432 (crop height) = 410
# The crop box format is: [left bottom right top]
BOX="[20 410 318 832]"
gs -o $CROPPED_PDF_PATH -sDEVICE=pdfwrite -c "[/CropBox $BOX /PAGES pdfmark" -c "[/MediaBox $BOX /PAGES pdfmark" -f "$DOWNLOADED_PDF_PATH"

# Check if cropping was successful
if [ ! -f "$CROPPED_PDF_PATH" ]; then
    echo "Failed to crop the PDF."
    exit 1
fi

# Print the cropped PDF using lp
# lp -d "$PRINTER_NAME" -o PageSize=w288h432 "$CROPPED_PDF_PATH"
# Clean up: Delete the downloaded and generated files
#rm "$DOWNLOADED_PDF_PATH" "$CROPPED_PDF_PATH"

# Just open it and use GUI to print until the above works
open $CROPPED_PDF_PATH
0

There are 0 best solutions below