Skip to content

Instantly share code, notes, and snippets.

@Markus-de-Koster
Last active March 7, 2024 10:43
Show Gist options
  • Select an option

  • Save Markus-de-Koster/846cfabd89d3f319216ea6dba0c13bb0 to your computer and use it in GitHub Desktop.

Select an option

Save Markus-de-Koster/846cfabd89d3f319216ea6dba0c13bb0 to your computer and use it in GitHub Desktop.
Scanimage automated script for reading multiple pages and converting to PDF (linux)
#!/bin/bash
# Function to check if a command is available
check_command() {
if ! command -v "$1" &>/dev/null; then
echo "Command '$1' is required but not found. Please make sure it is installed and accessible in your PATH."
exit 1
fi
}
# Function to check if a scanner is connected
check_scanner() {
if ! scanimage --list-devices | grep -q "device"; then
echo "No scanner detected. Please make sure a scanner is connected and try again."
exit 1
fi
}
# Check for required commands
check_command "scanimage"
check_command "img2pdf"
check_command "pdfunite"
# Check if a scanner is connected
check_scanner
# Array to hold the names of generated PDF files
pdf_files=()
# Loop to scan multiple pages based on user input
while true; do
# Prompt user for output file name
read -p "Enter output file name for this page (without extension): " filename
# Use scanimage to scan at 300 dpi resolution and save as PNG (or PNM)
scanimage --resolution 300 --format=png > "${filename}.png"
# using imagemagick (requires specific permissions)
# convert "${filename}.png" "${filename}.pdf"
# Convert the scanned image to PDF using img2pdf
img2pdf "${filename}.png" -o "${filename}.pdf"
# Add the name of the newly created PDF to the array
pdf_files+=("${filename}.pdf")
# Ask user if they want to scan another page
read -p "Scan another page? (yes/no): " answer
if [[ "$answer" != "yes" ]]; then
break
fi
done
# If more than one PDF, merge them
if [ ${#pdf_files[@]} -gt 1 ]; then
# Generate a unique output file name for the merged PDF
merged_pdf="merged_$(date +%Y%m%d_%H%M%S).pdf"
# Use pdfunite to merge the PDFs
pdfunite "${pdf_files[@]}" "$merged_pdf"
echo "Merged PDF created: $merged_pdf"
else
echo "Single scanned page, no merge needed."
fi
# Clean up - Uncomment the following line if you want to delete individual PDFs after merging
# rm "${pdf_files[@]}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment