
Security News
Static vs. Runtime Reachability: Insights from Latioβs On the Record Podcast
The Latio podcast explores how static and runtime reachability help teams prioritize exploitable vulnerabilities and streamline AppSec workflows.
π¨οΈ A powerful, dependency-free Python library for cross-platform document printing with enhanced PDF generation
Universal Printer is a comprehensive document printing and PDF generation library that works seamlessly across Windows, macOS, and Linux. Version 3.0 introduces powerful enhanced PDF generation with intelligent formatting for Markdown, CSV, JSON, and text files.
pip install universal-printer
from universal_printer import DocumentPrinter
# Create printer instance
printer = DocumentPrinter()
# Print text content
success, message, pdf_path = printer.print_text(
"Hello, World!\nThis is a test document.",
fallback_to_pdf=True
)
# Print any file type
success, message, pdf_path = printer.print_file(
"/path/to/document.pdf", # or .docx, .jpg, .html, etc.
fallback_to_pdf=True
)
# Generate PDF directly (NEW in v3.0)
success, message, pdf_path = printer.generate_pdf(
"document.md", # Supports .txt, .md, .csv, .json
pdf_filename="formatted_document"
)
# Markdown with intelligent formatting
markdown_content = """
# My Document
## Introduction
This **bold text** and *italic text* will be properly formatted.
- Bullet points become β’ symbols
- Code blocks get special formatting
- Tables are properly aligned
```python
print("Code blocks are highlighted")
"""
success, message, pdf_path = printer.generate_pdf( markdown_content, pdf_filename="formatted_markdown" )
csv_content = """Name,Age,City John,30,New York Jane,25,Los Angeles Bob,35,Chicago"""
success, message, pdf_path = printer.generate_pdf( csv_content, pdf_filename="formatted_table" )
### Batch Processing (NEW in v3.0)
```python
# Print multiple files
files = ["doc1.txt", "doc2.md", "doc3.csv"]
results = printer.print_batch(files, fallback_to_pdf=True)
print(f"Processed {results['total_files']} files")
print(f"Success rate: {results['successful_prints']}/{results['total_files']}")
# Generate PDFs for multiple files
results = printer.generate_batch_pdfs(files)
print(f"Generated {results['successful_pdfs']} PDFs")
from universal_printer import DocumentPrinter, PrinterConfig
# Create custom configuration
config = PrinterConfig()
config.pdf.font_size = 12
config.pdf.margin_left = 60
config.logging.level = "DEBUG"
# Use custom configuration
printer = DocumentPrinter(config=config)
# Or load from file
printer = DocumentPrinter(config_file="my_config.json")
Universal Printer now includes a powerful CLI for all operations:
# Print a file
universal-printer print document.txt
universal-printer print --printer "HP LaserJet" document.pdf
# Generate PDF
universal-printer pdf document.md --output formatted_doc
universal-printer pdf "Hello, World!" --output hello
# Batch operations
universal-printer batch-print *.txt --no-fallback
universal-printer batch-pdf *.md --report results.json
# Get information
universal-printer info --file document.txt
universal-printer info # Show general info
# Configuration
universal-printer config --create config.json
universal-printer config --show default
The library can handle any file type, with optimized support for:
.pdf
, .doc
, .docx
, .rtf
, .odt
.txt
, .csv
, .json
, .xml
, .html
, .htm
, .md
.jpg
, .jpeg
, .png
, .gif
, .bmp
, .tiff
__init__()
Creates a new DocumentPrinter instance with automatic file type detection.
print_document(content_or_path, printer_name=None, fallback_to_pdf=True, pdf_filename=None)
Universal method to print text content or any file type.
Parameters:
content_or_path
(str): Text content or path to any file typeprinter_name
(str, optional): Name of printer to use, or "PDF" for print-to-PDFfallback_to_pdf
(bool): Create PDF if printing fails (default: True)pdf_filename
(str, optional): Custom filename for PDF fallbackReturns:
tuple
: (success: bool, message: str, pdf_path: str or None)print_text(text, printer_name=None, fallback_to_pdf=True, pdf_filename=None)
Convenience method specifically for printing text content.
print_file(file_path, printer_name=None, fallback_to_pdf=True, pdf_filename=None)
Convenience method specifically for printing files.
get_supported_file_types()
Returns set of file extensions optimized for direct printing.
is_file_printable(file_path)
Check if a file type is directly supported for printing.
generate_pdf(content_or_path, pdf_filename=None)
Generate a PDF directly from text content or supported file types (.txt, .md, .csv, .json). This method bypasses printing and creates a PDF directly with enhanced formatting.
Parameters:
content_or_path
(str): Text content or path to supported file typepdf_filename
(str, optional): Custom filename for PDF outputReturns:
tuple
: (success: bool, message: str, pdf_path: str or None)from universal_printer import DocumentPrinter
printer = DocumentPrinter()
# Simple text printing
success, msg, pdf = printer.print_text("Hello, World!")
print(f"Result: {success}, Message: {msg}")
# Multi-line text with custom PDF name
text_content = """
Invoice #12345
Date: 2024-01-01
Amount: $100.00
Thank you for your business!
"""
success, msg, pdf = printer.print_text(
text_content,
pdf_filename="invoice_12345.pdf"
)
# Print a PDF document
success, msg, pdf = printer.print_file("/path/to/document.pdf")
# Print a Word document
success, msg, pdf = printer.print_file("/path/to/report.docx")
# Print an image
success, msg, pdf = printer.print_file("/path/to/photo.jpg")
# Print HTML file
success, msg, pdf = printer.print_file("/path/to/webpage.html")
# Print CSV data
success, msg, pdf = printer.print_file("/path/to/data.csv")
# Print Markdown file
success, msg, pdf = printer.print_file("/path/to/document.md")
# Check if file type is supported
if printer.is_file_printable("/path/to/document.pdf"):
print("PDF files are directly printable")
# Get all supported file types
supported_types = printer.get_supported_file_types()
print(f"Supported types: {supported_types}")
# Print to specific printer
success, msg, pdf = printer.print_document(
"Important memo",
printer_name="HP_LaserJet_Pro"
)
# Print to PDF (bypass physical printer)
success, msg, pdf = printer.print_document(
"Save as PDF",
printer_name="PDF",
pdf_filename="saved_document.pdf"
)
# The library automatically detects file types
success, msg, pdf = printer.print_file("unknown_file.xyz")
# Will attempt to print or create PDF representation
# Handle binary files gracefully
success, msg, pdf = printer.print_file("/path/to/program.exe")
# Creates PDF with file information for binary files
# Disable PDF fallback for testing
success, msg, pdf = printer.print_text(
"Print or fail",
fallback_to_pdf=False
)
if not success:
print("Printing failed and no PDF was created")
Generate PDFs directly from supported file types with enhanced formatting:
# Generate PDF from text content
success, msg, pdf_path = printer.generate_pdf(
"Hello, World!\nThis will be formatted nicely in the PDF.",
pdf_filename="my_text_document"
)
# Generate PDF from Markdown file with enhanced formatting
success, msg, pdf_path = printer.generate_pdf(
"/path/to/document.md",
pdf_filename="formatted_markdown"
)
# Generate PDF from CSV with table formatting
success, msg, pdf_path = printer.generate_pdf(
"/path/to/data.csv",
pdf_filename="formatted_table"
)
# Generate PDF from JSON with pretty formatting
success, msg, pdf_path = printer.generate_pdf(
"/path/to/config.json",
pdf_filename="formatted_json"
)
if success:
print(f"Enhanced PDF created: {pdf_path}")
else:
print(f"PDF generation failed: {msg}")
rundll32.exe
with shell print verb for all file typeslp
command (CUPS) for all file typesThe library includes intelligent file type detection:
mimetypes
Enhanced PDF fallback system:
MIT License - see LICENSE file for details.
Contributions are welcome! Please feel free to submit a Pull Request.
from universal_printer import DocumentPrinter, PrinterConfig
# Initialize with optional configuration
printer = DocumentPrinter()
printer = DocumentPrinter(config=my_config)
printer = DocumentPrinter(config_file="config.json")
print_file(file_path, printer_name=None, fallback_to_pdf=True, pdf_filename=None)
print_text(text, printer_name=None, fallback_to_pdf=True, pdf_filename=None)
generate_pdf(content_or_path, pdf_filename=None)
- Direct PDF generationprint_batch(files, printer_name=None, fallback_to_pdf=True)
- Batch printinggenerate_batch_pdfs(files, output_directory=None)
- Batch PDF generationget_statistics()
- Get performance statisticsget_file_info(file_path)
- Get comprehensive file informationvalidate_pdf(pdf_path)
- Validate PDF filesget_supported_formats()
- Get supported file formats by categoryget_config()
- Get current configurationupdate_config(**kwargs)
- Update configuration settingsfrom universal_printer import PrinterConfig
# Create and customize configuration
config = PrinterConfig()
config.pdf.font_size = 12
config.pdf.margin_left = 60
config.logging.level = "DEBUG"
config.print.enable_pdf_fallback = True
# Save/load configuration
config.save_to_file("my_config.json")
config = PrinterConfig("my_config.json")
MIT License - see LICENSE file for details.
Contributions are welcome! Please see our Contributing Guidelines.
See CHANGELOG.md for detailed version history.
FAQs
Cross-platform document printing with enhanced PDF generation
We found that universal-printer demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago.Β It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
The Latio podcast explores how static and runtime reachability help teams prioritize exploitable vulnerabilities and streamline AppSec workflows.
Security News
The latest Opengrep releases add Apex scanning, precision rule tuning, and performance gains for open source static code analysis.
Security News
npm now supports Trusted Publishing with OIDC, enabling secure package publishing directly from CI/CD workflows without relying on long-lived tokens.