PHP code example of rctnet / jasperphp

1. Go to this page and download the library: Download rctnet/jasperphp library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

rctnet / jasperphp example snippets




asperPHP\core\TJasper;

// Path to your .jrxml file
$reportFile = __DIR__ . '/path/to/your/report.jrxml';

// Report parameters (if any)
$params = ['title' => 'My Report'];

// Data source configuration
$dataSource = [
    'type' => 'array',
    'data' => [
        ['id' => 1, 'name' => 'Product A', 'price' => 10.50],
        ['id' => 2, 'name' => 'Product B', 'price' => 22.00],
    ]
];

try {
    // Instantiate the report
    $jasper = new TJasper($reportFile, $params, $dataSource);

    // Generate and output the report to the browser
    // The output() method handles the entire process
    $jasper->output(); // Default output is PDF inline

} catch (\Exception $e) {
    echo 'Error generating report: ' . $e->getMessage();
}

$dataSource = [
    'type' => 'array',
    'data' => [
        (object)['id' => 1, 'name' => 'Item A'],
        (object)['id' => 2, 'name' => 'Item B']
    ]
];

$dataSource = [
    'type' => 'db',
    'sql' => 'SELECT * FROM customers',
    'db_driver' => 'mysql',
    'db_host' => 'localhost',
    'db_port' => '3306',
    'db_name' => 'mydatabase',
    'db_user' => 'user',
    'db_pass' => 'password',
];

// From a JSON file
$dataSource = [
    'type' => 'json_file',
    'path' => '/path/to/your/data.json'
];

// From a CSV file
$dataSource = [
    'type' => 'csv_file',
    'path' => '/path/to/your/data.csv'
];

$dbConfig = [
    'type' => 'db',
    // No 'sql' key is needed here
    'db_driver' => 'mysql',
    'db_host' => 'localhost',
    'db_name' => 'mydatabase',
    'db_user' => 'user',
    'db_pass' => 'password',
];

// Parameters needed by the query in the JRXML
$reportParams = [
    'CUSTOMER_ID' => 123
];

$jasper = new TJasper('report_with_query.jrxml', $reportParams, $dbConfig);
$jasper->output();

public function output(string $mode = 'I', string $filename = 'report.pdf', ?string $filePath = null): ?string

// Stream to browser
$jasper->output('I', 'my_report.pdf');

// Force download
$jasper->output('D', 'invoice.pdf');

// Save to a file
$jasper->output('F', 'report.pdf', '/path/to/save/report.pdf');

// Get as a string
$reportContent = $jasper->output('S');