stesa/phpjasper
最新稳定版本:v1.1.0
Composer 安装命令:
composer require stesa/phpjasper
包简介
A Laravel package for generating reports with JasperReports using the latest version of JasperStarter
README 文档
README
A Laravel package for generating reports with JasperReports using the latest version of JasperStarter. Generate beautiful PDF, Excel, CSV, HTML, and other format reports from your Laravel application with ease.
Features
- Latest JasperReports: Uses JasperReports 7.0.3 via custom JasperStarter build
- Multiple Output Formats: PDF, Excel (XLS/XLSX), CSV, HTML, XML, and more
- Database Support: MySQL and PostgreSQL out of the box
- Fluent API: Intuitive, Laravel-style chainable methods
- Barcode Support: Full support for barcodes including Code128, Code39, QR codes, etc.
- JSON Output: Structured error handling and detailed logging
- Easy Integration: Automatic service provider discovery, facade support
- Comprehensive: Report compilation, execution, and parameter listing
Requirements
- PHP 8.0 or higher
- Laravel 9.0, 10.0, 11.0, or 12.0
- Java Runtime Environment (JRE) 24 or higher
Installation
1. Install via Composer
composer require stesa/phpjasper
2. Publish Configuration (Optional)
php artisan vendor:publish --provider="Stesa\PHPJasper\PHPJasperServiceProvider" --tag="config"
This will create config/phpjasper.php for customization.
3. Publish Example Templates (Optional)
php artisan vendor:publish --provider="Stesa\PHPJasper\PHPJasperServiceProvider" --tag="examples"
4. Verify Java Installation
Make sure Java is installed and accessible:
java -version
You should see Java 24 or higher.
Quick Start
Basic Usage
use Stesa\PHPJasper\Facades\PHPJasper; // Compile a JRXML template PHPJasper::compile(storage_path('app/reports/templates/invoice.jrxml')) ->execute(); // Generate a PDF report PHPJasper::process( storage_path('app/reports/templates/invoice.jrxml'), storage_path('app/reports/output/invoice'), [ 'format' => 'pdf', 'db_connection' => [ 'driver' => 'mysql', 'host' => 'localhost', 'database' => 'mydb', 'username' => 'root', 'password' => 'secret' ] ] )->execute(); // Download the report return response()->download(storage_path('app/reports/output/invoice.pdf'));
Using in Controller
<?php namespace App\Http\Controllers; use Stesa\PHPJasper\Facades\PHPJasper; use Illuminate\Http\Request; class ReportController extends Controller { public function generateInvoice($invoiceId) { $input = storage_path('app/reports/templates/invoice.jrxml'); $output = storage_path('app/reports/output/invoice_' . $invoiceId); PHPJasper::process($input, $output, [ 'format' => ['pdf'], 'params' => [ 'invoice_id' => $invoiceId ], 'db_connection' => [ 'driver' => config('database.default'), 'host' => config('database.connections.mysql.host'), 'database' => config('database.connections.mysql.database'), 'username' => config('database.connections.mysql.username'), 'password' => config('database.connections.mysql.password'), ] ])->execute(); return response()->download($output . '.pdf') ->deleteFileAfterSend(true); } }
API Reference
Compile
Compile a JRXML template to JASPER format:
PHPJasper::compile($inputFile, $outputFile = null)->execute();
Parameters:
$inputFile(string): Path to .jrxml file$outputFile(string, optional): Output path for .jasper file
Example:
PHPJasper::compile(storage_path('app/reports/templates/report.jrxml')) ->execute();
Process
Generate a report from a JASPER or JRXML file:
PHPJasper::process($inputFile, $outputFile, $options = [])->execute();
Parameters:
$inputFile(string): Path to .jasper or .jrxml file$outputFile(string): Output file path (without extension)$options(array): Report options
Options:
[
'format' => ['pdf', 'xlsx'], // Single format or array of formats
'params' => [ // Report parameters
'my_param' => 'value'
],
'db_connection' => [ // Database connection
'driver' => 'mysql', // mysql or postgresql
'host' => 'localhost',
'database' => 'mydb',
'username' => 'user',
'password' => 'pass'
],
'resources' => '/path/to/resources', // Resource directory for images, etc.
'locale' => 'en_US' // Locale for number/date formatting
]
Example:
PHPJasper::process( storage_path('app/reports/templates/sales.jrxml'), storage_path('app/reports/output/sales_report'), [ 'format' => ['pdf', 'xlsx'], 'params' => [ 'start_date' => '2024-01-01', 'end_date' => '2024-12-31' ] ] )->execute();
List Parameters
List all parameters in a JASPER report:
$result = PHPJasper::listParameters($inputFile)->execute();
Example:
$params = PHPJasper::listParameters( storage_path('app/reports/templates/report.jasper') )->execute(); print_r($params);
Multiple Output Formats
Generate reports in multiple formats simultaneously:
PHPJasper::process($input, $output, [ 'format' => ['pdf', 'xlsx', 'csv', 'html'] ])->execute(); // Results in: // - output.pdf // - output.xlsx // - output.csv // - output.html
Database Connections
Using Default Laravel Database
PHPJasper::process($input, $output, [ 'format' => 'pdf', 'db_connection' => [ 'driver' => config('database.default'), 'host' => config('database.connections.mysql.host'), 'database' => config('database.connections.mysql.database'), 'username' => config('database.connections.mysql.username'), 'password' => config('database.connections.mysql.password'), ] ])->execute();
Using PostgreSQL
PHPJasper::process($input, $output, [ 'format' => 'pdf', 'db_connection' => [ 'driver' => 'postgresql', 'host' => 'localhost:5432', 'database' => 'mydb', 'username' => 'postgres', 'password' => 'secret', ] ])->execute();
Report Parameters
Pass parameters to your reports:
PHPJasper::process($input, $output, [ 'format' => 'pdf', 'params' => [ 'company_name' => 'Acme Corp', 'report_date' => date('Y-m-d'), 'user_id' => auth()->id(), 'show_details' => true ] ])->execute();
In your JRXML, reference parameters like:
<parameter name="company_name" class="java.lang.String"/> <parameter name="report_date" class="java.lang.String"/> <parameter name="user_id" class="java.lang.Integer"/> <parameter name="show_details" class="java.lang.Boolean"/>
Configuration
The package can be configured via config/phpjasper.php:
return [ // Path to Java executable (defaults to 'java' command) 'java_path' => env('PHPJASPER_JAVA_PATH', null), // Path to JasperStarter JAR (auto-detected if null) 'jar_path' => env('PHPJASPER_JAR_PATH', null), // Default database connection 'db_connection' => [ 'driver' => env('PHPJASPER_DB_DRIVER', 'mysql'), 'host' => env('PHPJASPER_DB_HOST', 'localhost'), 'database' => env('PHPJASPER_DB_DATABASE', 'forge'), 'username' => env('PHPJASPER_DB_USERNAME', 'forge'), 'password' => env('PHPJASPER_DB_PASSWORD', ''), ], // Directory paths 'template_dir' => storage_path('app/reports/templates'), 'output_dir' => storage_path('app/reports/output'), 'resource_dir' => storage_path('app/reports/resources'), // Default locale 'locale' => 'en_US', ];
Environment Variables
Add to your .env file:
PHPJASPER_JAVA_PATH=/usr/lib/jvm/java-17-openjdk/bin/java PHPJASPER_JAR_PATH=/custom/path/to/jasperstarter.jar PHPJASPER_DB_DRIVER=mysql PHPJASPER_DB_HOST=localhost PHPJASPER_DB_DATABASE=mydb PHPJASPER_DB_USERNAME=root PHPJASPER_DB_PASSWORD=secret PHPJASPER_LOCALE=en_US
Using Multiple Java Versions
If you have multiple Java versions installed, you can specify which one to use:
Via Configuration:
// config/phpjasper.php 'java_path' => '/usr/lib/jvm/java-11-openjdk/bin/java',
Via Environment Variable:
# Linux/macOS PHPJASPER_JAVA_PATH=/usr/lib/jvm/java-17-openjdk/bin/java # Windows PHPJASPER_JAVA_PATH="C:\Program Files\Java\jdk-17\bin\java.exe"
Programmatically:
use Stesa\PHPJasper\PHPJasper; // Option 1: Set via constructor $jasper = new PHPJasper(null, '/usr/lib/jvm/java-11-openjdk/bin/java'); $jasper->compile($input)->execute(); // Option 2: Set via method PHPJasper::setJavaPath('/usr/lib/jvm/java-17-openjdk/bin/java') ->process($input, $output, ['format' => 'pdf']) ->execute(); // Get current Java path $javaPath = PHPJasper::getJavaPath();
Supported Formats
- PDF - Portable Document Format
- XLSX - Microsoft Excel 2007+
- XLS - Microsoft Excel (Legacy)
- CSV - Comma-separated values
- HTML - HTML format
- XML - XML format
- JRPRINT - JasperReports print format
Check supported formats:
$formats = PHPJasper::getSupportedFormats(); // ['pdf', 'csv', 'xls', 'xlsx', 'xml', 'html', 'jrprint'] $isSupported = PHPJasper::isFormatSupported('pdf'); // true
Barcode Support
This package includes full barcode support through Barcode4J integration:
Supported Barcode Types:
- Code128
- Code39
- EAN-13, EAN-8
- UPC-A, UPC-E
- Codabar
- PDF417
- DataMatrix
- QR Code
Example JRXML Barcode Component:
<componentElement> <reportElement x="100" y="50" width="200" height="50"/> <jr:barbecue xmlns:jr="http://jasperreports.sourceforge.net/jasperreports/components" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports/components http://jasperreports.sourceforge.net/xsd/components.xsd" type="Code128" drawText="true" checksumRequired="false"> <jr:codeExpression><![CDATA[$F{barcode_value}]]></jr:codeExpression> </jr:barbecue> </componentElement>
Directory Structure
Recommended directory structure for reports:
storage/app/reports/
├── templates/ # Store .jrxml files here
│ ├── invoice.jrxml
│ ├── sales_report.jrxml
│ └── ...
├── output/ # Generated reports (temporary)
│ ├── invoice.pdf
│ └── ...
└── resources/ # Images, fonts, subreports
├── logo.png
├── header.jasper
└── ...
Create directories:
mkdir -p storage/app/reports/{templates,output,resources}
Error Handling
The package throws exceptions with detailed error messages:
try { PHPJasper::process($input, $output, $options)->execute(); } catch (\Exception $e) { // Handle error Log::error('Report generation failed: ' . $e->getMessage()); return back()->with('error', 'Failed to generate report'); }
Advanced Usage
Get Command Without Executing
$command = PHPJasper::process($input, $output, $options) ->execute(true); // Returns command string echo $command;
Custom JAR Path
use Stesa\PHPJasper\PHPJasper; $jasper = new PHPJasper('/custom/path/to/jasperstarter.jar'); $jasper->compile($input)->execute();
Using Dependency Injection
use Stesa\PHPJasper\PHPJasper; class ReportService { protected $jasper; public function __construct(PHPJasper $jasper) { $this->jasper = $jasper; } public function generate($template, $output) { $this->jasper->process($template, $output, [ 'format' => 'pdf' ])->execute(); } }
Troubleshooting
Java Not Found
Error: java: command not found
Solution: Install Java JRE 24 or higher and ensure it's in your system PATH.
# Ubuntu/Debian sudo apt-get install openjdk-24-jre # macOS brew install openjdk@24 # Windows # Download from https://www.oracle.com/java/technologies/downloads/ # Or use https://adoptium.net/ for OpenJDK builds
JAR File Not Found
Error: JasperStarter JAR not found
Solution: The JAR file should be automatically included in the vendor directory. If missing, check your composer installation or manually specify the path in config.
Database Connection Failed
Error: Database connection error
Solution:
- Verify database credentials
- Ensure database server is running
- Check firewall settings
- Verify database driver (mysql/postgresql)
Compilation Errors
Error: Unable to load report
Solution:
- Validate XML syntax in JRXML file
- Ensure JRXML uses UTF-8 encoding
- Check JasperReports version compatibility (should be 7.0.3 or lower)
- Use JasperSoft Studio 6.20.x or earlier to create templates
Creating Reports
Using JasperSoft Studio
- Download JasperSoft Studio 6.20.x or earlier
- Create a new report or open existing .jrxml template
- Design your report with fields, parameters, and formatting
- Save the .jrxml file to your templates directory
- Use PHPJasper to compile and generate reports
Report Design Tips
- Use parameters for dynamic values:
$P{parameter_name} - Use fields for database columns:
$F{column_name} - Use variables for calculations:
$V{variable_name} - Store images in the resources directory
- Test reports in JasperSoft Studio before using in Laravel
Performance Tips
- Pre-compile templates: Compile .jrxml to .jasper during deployment
- Use queued jobs: For large reports, use Laravel queues to avoid timeouts
- Clean up old reports: Regularly delete old files from output directory
- Cache compiled reports: Store compiled .jasper files for reuse
- Optimize queries: Ensure database queries in reports are optimized
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
Credits
- Steven Samoy - Package creator
- JasperStarter - Based on custom build: ssamoy/jasperstarter
- JasperReports - Powered by JasperReports 7.0.3
- PHPJasper - Inspired by PHPJasper/phpjasper
License
This package is open-sourced software licensed under the MIT license.
Support
If you encounter any issues or have questions:
- Create an issue on GitHub
- Check existing issues for solutions
- Review the JasperStarter documentation
Changelog
See CHANGELOG.md for version history and changes.
统计信息
- 总下载量: 10
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 0
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2025-10-14