In pdftk, or another Linux app, is there a way to separate b&w and color pages in a pdf…
- User
In pdftk, or another Linux app, is there a way to separate b&w and color pages in a pdf that has both? Or at least quickly find the b&w pages?
Assistant
Of course! This is a common and practical task, often done to save on printing costs.
You've hit on the key challenge:
pdftkis excellent for manipulating PDFs (splitting, merging, rotating) once you know which pages you want, but it cannot analyze the content of a page to determine if it's color or black and white (B&W).Therefore, the solution is a two-step process:
- Analyze: Use a tool that can inspect each page to see if it contains color.
- Separate: Use the lists of page numbers from the analysis step with
pdftkto split the original file.
Here are a few ways to achieve this on Linux, from a quick command-line check to a fully automated script.
Method 1: The Quickest Way to Find Color Pages (Ghostscript)
This is the fastest method if you just need to identify the page numbers without creating new files. Ghostscript has a special "device" called
inkcovthat reports the ink coverage for each page.Command:
gs -o - -sDEVICE=inkcov your_document.pdfHow to Read the Output: Ghostscript will process each page and print a line with the CMYK (Cyan, Magenta, Yellow, Black) ink coverage percentages.
Page 1 0.00000 0.00000 0.00000 0.06891 CMYK OK Page 2 0.00000 0.00000 0.00000 0.05147 CMYK OK Page 3 0.15678 0.09871 0.00000 0.04512 CMYK OK <-- This page has color Page 4 0.00000 0.00000 0.00000 0.07111 CMYK OK- A page is B&W or Grayscale if the C, M, and Y values are all
0.00000. - A page is Color if any of the C, M, or Y values are greater than zero.
In the example above, Page 3 is a color page. All others are B&W/grayscale. You can then manually use this information with
pdftk.Method 2: Fully Automated Shell Script (pdftoppm + ImageMagick + pdftk)
This method automates the entire process. It converts each page to an image, checks the image's color space, builds two lists of page numbers (color and B&W), and then uses
pdftkto create the final PDFs.1. Install Dependencies: You'll need
poppler-utils(forpdftoppmandpdfinfo),imagemagick(foridentify), andpdftk.# On Debian/Ubuntu sudo apt-get update sudo apt-get install poppler-utils imagemagick-6.q16 pdftk-java # or pdftk # On Fedora/CentOS sudo dnf install poppler-utils ImageMagick pdftk-javaNote:
pdftkhas been replaced bypdftk-javain many modern distributions.2. The Script (
pdf_split_color.sh):Create a new file named
pdf_split_color.sh, paste the code below, and make it executable withchmod +x pdf_split_color.sh.#!/bin/bash # A script to separate color and B&W pages from a PDF. # Dependencies: pdftk, poppler-utils (pdfinfo, pdftoppm), imagemagick (identify) # --- Configuration --- INPUT_PDF="$1" OUTPUT_COLOR_PDF="${INPUT_PDF%.pdf}_color.pdf" OUTPUT_BW_PDF="${INPUT_PDF%.pdf}_bw.pdf" # Use a high-quality temporary format to avoid color loss TMP_FORMAT="png" # --- Validation --- if [[ -z "$INPUT_PDF" ]]; then echo "Usage: $0 <input_file.pdf>" exit 1 fi if ! command -v pdftk &> /dev/null || ! command -v pdfinfo &> /dev/null || ! command -v pdftoppm &> /dev/null || ! command -v identify &> /dev/null; then echo "Error: Missing one or more required commands: pdftk, pdfinfo, pdftoppm, identify." echo "Please install pdftk, poppler-utils, and imagemagick." exit 1 fi # --- Main Logic --- echo "Analyzing PDF: $INPUT_PDF" PAGE_COUNT=$(pdfinfo "$INPUT_PDF" | grep "Pages:" | awk '{print $2}') echo "Found $PAGE_COUNT pages." COLOR_PAGES="" BW_PAGES="" TMP_DIR=$(mktemp -d) echo "Using temporary directory: $TMP_DIR" for i in $(seq 1 $PAGE_COUNT); do echo -ne "Processing page $i/$PAGE_COUNT...\r" # Convert single page to a temporary image pdftoppm -f $i -l $i -"${TMP_FORMAT}" "$INPUT_PDF" "${TMP_DIR}/page" # Check the colorspace of the image COLORSPACE=$(identify -format '%[colorspace]' "${TMP_DIR}/page.${TMP_FORMAT}") if [[ "$COLORSPACE" == "sRGB" || "$COLORSPACE" == "CMYK" ]]; then # Double-check it's not just grayscale masquerading as sRGB UNIQUE_COLORS=$(identify -format '%k' "${TMP_DIR}/page.${TMP_FORMAT}") if (( UNIQUE_COLORS > 256 )); then COLOR_PAGES="$COLOR_PAGES $i" else BW_PAGES="$BW_PAGES $i" fi else # Grayscale, Gray BW_PAGES="$BW_PAGES $i" fi done echo -e "\nAnalysis complete." # --- Separation using pdftk --- if [[ -n "$COLOR_PAGES" ]]; then echo "Creating color PDF with pages:$COLOR_PAGES" pdftk "$INPUT_PDF" cat $COLOR_PAGES output "$OUTPUT_COLOR_PDF" else echo "No color pages found." fi if [[ -n "$BW_PAGES" ]]; then echo "Creating B&W PDF with pages:$BW_PAGES" pdftk "$INPUT_PDF" cat $BW_PAGES output "$OUTPUT_BW_PDF" else echo "No B&W pages found." fi # --- Cleanup --- rm -rf "$TMP_DIR" echo "Done."3. How to Run It:
./pdf_split_color.sh your_document.pdfThis will create two new files:
your_document_color.pdfandyour_document_bw.pdf.Method 3: The Python Way (PyMuPDF)
For those who prefer Python or need more flexibility, the
PyMuPDFlibrary is incredibly fast and efficient. It can analyze page content without having to write temporary image files to disk, making it faster than the shell script method for large documents.1. Install the Library:
pip install PyMuPDF2. The Python Script (
split_pdf_color.py):import fitz # PyMuPDF import sys import os def separate_pdf_by_color(input_path): """ Separates a PDF into two files: one with color pages, one with B&W. """ try: doc = fitz.open(input_path) except Exception as e: print(f"Error opening PDF: {e}") return color_pages = [] bw_pages = [] print(f"Analyzing {doc.page_count} pages in '{input_path}'...") for i, page in enumerate(doc): # get_colors() returns a list of tuples for each color used on the page. # The first element of the tuple is the colorspace (1=GRAY, 3=RGB, 4=CMYK) colors = page.get_colors(full=False) is_color = any(cs != 1 for cs, _ in colors) page_num = i + 1 if is_color: color_pages.append(page_num) else: bw_pages.append(page_num) # Simple progress indicator print(f" - Page {page_num}: {'Color' if is_color else 'B&W'}") print("\nAnalysis complete.") # Create output filenames base_name = os.path.splitext(input_path)[0] color_output_path = f"{base_name}_color.pdf" bw_output_path = f"{base_name}_bw.pdf" # Split the document if color_pages: print(f"Creating color PDF with {len(color_pages)} pages...") color_doc = fitz.open() # New empty PDF color_doc.insert_pdf(doc, from_page=0, to_page=doc.page_count - 1, select=[p - 1 for p in color_pages]) color_doc.save(color_output_path) color_doc.close() else: print("No color pages found.") if bw_pages: print(f"Creating B&W PDF with {len(bw_pages)} pages...") bw_doc = fitz.open() # New empty PDF bw_doc.insert_pdf(doc, from_page=0, to_page=doc.page_count - 1, select=[p - 1 for p in bw_pages]) bw_doc.save(bw_output_path) bw_doc.close() else: print("No B&W pages found.") doc.close() print("\nDone.") if __name__ == "__main__": if len(sys.argv) != 2: print("Usage: python split_pdf_color.py <input_file.pdf>") sys.exit(1) input_file = sys.argv[1] separate_pdf_by_color(input_file)3. How to Run It:
python split_pdf_color.py your_document.pdfSummary of Methods
Method Pros Cons Best For Ghostscript inkcovVery fast, single command, no new files created. Output requires manual interpretation, doesn't perform the split. Quickly finding which pages have color. Shell Script Fully automated, uses standard Linux tools. Slower due to creating temporary image files for each page. Automated workflows on a standard Linux server. Python (PyMuPDF) Very fast (in-memory processing), powerful, cross-platform. Requires Python and an external library. Fast, efficient, and flexible scripting, especially for large documents. - User
Sorry, I should have said grayscale instead of b&w. What I need is to separate the grayscale pages from the color ones. Does all of the above apply to grayscale equally well or would any tweaks be necessary? Or is there perhaps a different method that would apply to grayscale but not b&w?
Assistant
Excellent question! That is a crucial clarification. The distinction between true "Grayscale" and "B&W" (which is technically monochrome) is important, and my previous answer can be refined to address this perfectly.
Yes, all of the methods described previously work equally well—in fact, they are more accurate—for separating Grayscale from Color. The underlying logic was already checking for the presence of color ink/channels, which is the correct way to distinguish a grayscale page.
Let's revisit each method with this specific distinction in mind.
The Key Technical Distinction
- Grayscale: A page is truly grayscale if it only uses shades of black ink. In PDF terms, its content is defined in the
DeviceGraycolorspace. When printed, it only requires black toner/ink. - Color: A page is color if it uses Cyan, Magenta, or Yellow inks (in a CMYK model) or has distinct R, G, B values (in an RGB model).
- The Trap: "Rich Black" / Color-Defined Gray: Sometimes, a page looks gray to the human eye, but it's actually defined using a mix of C, M, Y, and K inks (e.g., 20% Cyan, 10% Magenta, 10% Yellow, 100% Black). This is often done to achieve a deeper black shade in professional printing. All the methods below will correctly classify this as a COLOR page, which is usually what you want, as it would consume color ink/toner.
Here are the refined methods, with explanations tailored to separating Grayscale from Color.
Method 1: Ghostscript
inkcov(Quickest Check)This method is perfect for your needs without any modification. It directly reports ink usage.
Command:
gs -o - -sDEVICE=inkcov your_document.pdfHow to Interpret for Grayscale vs. Color: The output shows coverage for Cyan, Magenta, Yellow, and Black (CMYK).
Page 1 0.00000 0.00000 0.00000 0.06891 CMYK OK <-- True Grayscale (only K has a value) Page 2 0.00000 0.00000 0.00000 0.05147 CMYK OK <-- True Grayscale Page 3 0.15678 0.09871 0.00000 0.04512 CMYK OK <-- Color (C and M have values) Page 4 0.02000 0.01500 0.01500 0.75000 CMYK OK <-- Color (looks gray, but uses CMY - "Rich Black")- A page is Grayscale if the first three values (C, M, and Y) are all zero.
- A page is Color if any of the first three values (C, M, or Y) are greater than zero.
This is the most direct and reliable way to check from the command line without creating new files.
Method 2: Fully Automated Shell Script (Updated)
This script works by rendering each page and having ImageMagick identify its colorspace. A true grayscale page will be rendered into a
Graycolorspace.I've updated the script for clarity, renaming variables from
BWtoGRAYSCALE. The core logic remains robust for this task.The Script (
pdf_split_grayscale.sh):#!/bin/bash # A script to separate color and grayscale pages from a PDF. # Dependencies: pdftk, poppler-utils (pdfinfo, pdftoppm), imagemagick (identify) INPUT_PDF="$1" OUTPUT_COLOR_PDF="${INPUT_PDF%.pdf}_color.pdf" OUTPUT_GRAY_PDF="${INPUT_PDF%.pdf}_grayscale.pdf" TMP_FORMAT="ppm" # PPM is a good, simple format for this # --- Validation --- if [[ -z "$INPUT_PDF" ]]; then echo "Usage: $0 <input_file.pdf>" exit 1 fi # ... (add other validation from previous script if desired) echo "Analyzing PDF: $INPUT_PDF" PAGE_COUNT=$(pdfinfo "$INPUT_PDF" | grep "Pages:" | awk '{print $2}') echo "Found $PAGE_COUNT pages." COLOR_PAGES="" GRAYSCALE_PAGES="" TMP_DIR=$(mktemp -d) for i in $(seq 1 $PAGE_COUNT); do echo -ne "Processing page $i/$PAGE_COUNT...\r" # Convert a single page to a temporary image pdftoppm -f $i -l $i -"${TMP_FORMAT}" "$INPUT_PDF" "${TMP_DIR}/page" # ImageMagick's identify tells us the colorspace of the rendered image. COLORSPACE=$(identify -format '%[colorspace]' "${TMP_DIR}/page.${TMP_FORMAT}") # True grayscale pages will be identified with the 'Gray' colorspace. # Anything else (sRGB, CMYK) is treated as color. if [[ "$COLORSPACE" == "Gray" ]]; then GRAYSCALE_PAGES="$GRAYSCALE_PAGES $i" else COLOR_PAGES="$COLOR_PAGES $i" fi done echo -e "\nAnalysis complete." # --- Separation using pdftk --- if [[ -n "$COLOR_PAGES" ]]; then echo "Creating color PDF with pages:$COLOR_PAGES" pdftk "$INPUT_PDF" cat $COLOR_PAGES output "$OUTPUT_COLOR_PDF" else echo "No color pages found." fi if [[ -n "$GRAYSCALE_PAGES" ]]; then echo "Creating grayscale PDF with pages:$GRAYSCALE_PAGES" pdftk "$INPUT_PDF" cat $GRAYSCALE_PAGES output "$OUTPUT_GRAY_PDF" else echo "No grayscale pages found." fi # --- Cleanup --- rm -rf "$TMP_DIR" echo "Done."To Run:
- Save the code as
pdf_split_grayscale.sh. - Make it executable:
chmod +x pdf_split_grayscale.sh. - Run it:
./pdf_split_grayscale.sh your_document.pdf.
Method 3: The Python Way (PyMuPDF - Most Accurate)
This method is the fastest and most precise because it inspects the PDF's internal objects directly without rendering images. The logic was already perfect for detecting grayscale vs. color.
The
page.get_colors()method checks the defined colorspaces on the page. In PyMuPDF,DeviceGrayhas a colorspace ID of1. Any other colorspace (sRGB,DeviceCMYK, etc.) means the page is color.Here is the updated script with clearer variable names.
The Python Script (
split_pdf_grayscale.py):import fitz # PyMuPDF import sys import os def separate_pdf_by_color(input_path): """ Separates a PDF into two files: one with color pages, one with grayscale pages. """ try: doc = fitz.open(input_path) except Exception as e: print(f"Error opening PDF: {e}") return color_pages = [] grayscale_pages = [] print(f"Analyzing {doc.page_count} pages in '{input_path}'...") for i, page in enumerate(doc): # get_colors() returns a list of tuples. The first element of the tuple # is the colorspace ID (1=GRAY, 3=RGB, 4=CMYK). # If any colorspace other than GRAY (1) is present, we treat it as color. colors = page.get_colors(full=False) is_color = any(cs_id != 1 for cs_id, _ in colors) page_num = i + 1 if is_color: color_pages.append(page_num) else: grayscale_pages.append(page_num) print(f" - Page {page_num}: {'Color' if is_color else 'Grayscale'}") print("\nAnalysis complete.") base_name = os.path.splitext(input_path)[0] color_output_path = f"{base_name}_color.pdf" gray_output_path = f"{base_name}_grayscale.pdf" if color_pages: print(f"Creating color PDF with {len(color_pages)} pages...") # PyMuPDF uses 0-based indexing for page selection color_doc = fitz.open() color_doc.insert_pdf(doc, select=[p - 1 for p in color_pages]) color_doc.save(color_output_path) color_doc.close() else: print("No color pages found.") if grayscale_pages: print(f"Creating grayscale PDF with {len(grayscale_pages)} pages...") gray_doc = fitz.open() gray_doc.insert_pdf(doc, select=[p - 1 for p in grayscale_pages]) gray_doc.save(gray_output_path) gray_doc.close() else: print("No grayscale pages found.") doc.close() print("\nDone.") if __name__ == "__main__": if len(sys.argv) != 2: print("Usage: python split_pdf_grayscale.py <input_file.pdf>") sys.exit(1) input_file = sys.argv[1] separate_pdf_by_color(input_file)To Run:
# First, ensure PyMuPDF is installed: pip install PyMuPDF python split_pdf_grayscale.py your_document.pdfRecommendation Summary
Your clarification doesn't require a different method, but it highlights the strength of the existing ones.
- For the quickest possible check: Use Ghostscript
inkcov. It's the fastest way to get a list of which pages use color ink. - For the fastest and most accurate automated solution: Use the Python (PyMuPDF) script. It inspects the PDF structure directly and is very efficient.
- For a pure-CLI automated solution without Python: Use the updated shell script. It's slightly slower but very reliable and uses standard Linux utilities.
- Grayscale: A page is truly grayscale if it only uses shades of black ink. In PDF terms, its content is defined in the
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.