Finding Embedded QR Codes on Mac Using Terminal

Abstract: Extract hidden QR codes from PDF files on macOS using Terminal and Python scripts.

Created: 2026-08-02 by
You can locate and extract embedded QR codes from PDF files on macOS by using the Terminal to run Python scripts with libraries like pyzbar or opencv. This method scans the binary data of documents for QR patterns that are invisible to the naked eye, allowing you to recover hidden information directly from your Mac without third-party GUI applications.

Understanding Embedded QR Codes in Documents

QR codes are not limited to visible stickers or printed paper; they are frequently embedded within digital documents such as PDFs, Word files, or images. These codes often contain metadata, authentication tokens, or links that are not immediately apparent. When a user asks how to find these codes, they are usually looking for data hidden inside the file structure rather than scanning a physical object. The Terminal provides a powerful environment for automating this search across multiple files efficiently.

Setting Up the Required Environment

Before running any extraction scripts, you must ensure your Mac has the necessary dependencies installed. macOS does not include advanced image processing libraries by default. You will need to use Homebrew to install system-level libraries and then configure Python to access them. First, open your Terminal application. If you do not have Homebrew installed, you should install it first by running the standard installation command provided on the Homebrew website. Once Homebrew is ready, update your package list to ensure you have the latest versions. Next, install the ZBar library, which is essential for barcode recognition. Run the following command in your Terminal:
brew install zbar
This library provides the low-level functionality needed to detect barcodes in images. After installing ZBar, you need to set up a Python environment. It is recommended to use a virtual environment to avoid conflicts with system Python packages. Create a new directory for your project and initialize a virtual environment:
mkdir qr-scanner
cd qr-scanner
python3 -m venv venv
source venv/bin/activate
Once the virtual environment is active, install the required Python packages. You will need pyzbar for decoding and Pillow for image handling. Install them using pip:
pip install pyzbar Pillow
If you encounter issues with pyzbar not finding the ZBar library, you may need to specify the path during installation or ensure that the Homebrew prefix is correctly linked. For more troubleshooting on terminal commands, see our guide on MacOS Terminal: Not Recognized Commands, Getting Back to Work with zsh.

Writing the Extraction Script

With the environment configured, you can write a simple Python script to scan a file. Create a new file named scan_qr.py using your preferred text editor. The script will load the PDF, convert each page to an image, and then scan for QR codes. Here is a basic implementation:
from pyzbar.pyzbar import decode
from PIL import Image
import fitz  # PyMuPDF for PDF handling

def scan_pdf_for_qr(pdf_path):
    doc = fitz.open(pdf_path)
    found_codes = []
    
    for page_num in range(len(doc)):
        page = doc[page_num]
        pix = page.get_pixmap()
        img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
        
        decoded_objects = decode(img)
        for obj in decoded_objects:
            if obj.type == 'QRCODE':
                found_codes.append({
                    'page': page_num + 1,
                    'data': obj.data.decode('utf-8')
                })
    
    return found_codes

if __name__ == "__main__":
    import sys
    if len(sys.argv) > 1:
        pdf_file = sys.argv[1]
        results = scan_pdf_for_qr(pdf_file)
        if results:
            print(f"Found {len(results)} QR codes:")
            for code in results:
                print(f"Page {code['page']}: {code['data']}")
        else:
            print("No QR codes found.")
    else:
        print("Please provide a PDF file path.")
This script uses PyMuPDF (install via pip install PyMuPDF) to render pages as images. It then passes these images to pyzbar, which detects any QR codes present. If no codes are found, it returns an empty list. This approach handles both visible and semi-hidden QR codes that might be overlaid on text or graphics.

Running the Scan

To use the script, navigate to your project directory in the Terminal and execute the script with the path to your target PDF file. Ensure your virtual environment is still active.
python scan_qr.py /path/to/your/document.pdf
The script will output the content of any detected QR codes along with the page number where they were found. This is particularly useful for auditing documents or extracting data from bulk files. For large batches of files, you can wrap this logic in a loop to process all PDFs in a directory. If you are working with other types of data retrieval, you might also find our article on Retrieving SQL Data using Terminal on Mac helpful for managing structured information alongside unstructured document data.

Troubleshooting Common Issues

Users often face challenges when the script fails to detect codes. The most common issue is incorrect image resolution. If the QR code is very small in the PDF, the rendered image might be too low-resolution for detection. You can adjust the rendering scale in the get_pixmap call by passing a matrix argument to increase density. Another issue is permission errors. Ensure you have read access to the PDF file. If you are scanning network drives, verify that your Mac has proper mounting permissions. Additionally, some PDFs use encryption or compression that might prevent direct pixel extraction. In such cases, converting the PDF to images externally before scanning may be necessary. For users experiencing command recognition errors while setting up their environment, refer to our detailed steps on fixing zsh: command not found: ssh -Y on Mac Terminal issues, although this specific error is unrelated to QR scanning, it highlights general Terminal configuration pitfalls.

Frequently Asked Questions

Can I scan QR codes from Word documents?

Yes, but you must first convert the Word document to PDF or images. pyzbar works on image formats like PNG and JPEG. You can use tools like soffice to convert DOCX files to PDF before running the scanner script.

Why is my script returning no results for visible QR codes?

This often happens due to low contrast or small size. Try increasing the resolution of the rendered page images by adjusting the zoom factor in the PDF rendering step. Also, ensure the QR code is not heavily distorted or rotated beyond the decoder's tolerance.

Is it safe to run these scripts on sensitive documents?

The scripts only read the file contents locally on your machine. They do not upload data to external servers. However, always review the code you download from the internet before executing it in your terminal to ensure no malicious operations are performed.

How do I scan multiple files at once?

You can modify the script to accept a directory path instead of a single file. Use Python's os or glob modules to iterate through all PDF files in a folder and apply the scan_pdf_for_qr function to each one, logging results to a CSV file.

What if the QR code is encrypted?

The scanner extracts the raw data payload of the QR code. If the payload itself is encrypted, the script will return the ciphertext. You would need a separate decryption key or algorithm to interpret the final message contained within the QR code.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More