GithubHelp home page GithubHelp logo

quilhasoft / jasperphp Goto Github PK

View Code? Open in Web Editor NEW
58.0 14.0 21.0 11.97 MB

Pure PHP library to read JRXML files made in "JasperSoft Studio" and generate reports in PDF/XLS

Home Page: https://jasperphp.com

License: MIT License

PHP 100.00% HTML 0.01%
jrxml-file jrxml-pdf report-generator jaspersoft jaspersoft-studio jasperserver jasper-reports php-reports php-reporting-tools

jasperphp's Introduction

alt text

JasperPHP

Library to generate reports created with the JasperSoft Studio application
Pure PHP library, without a java server or Jasper Server

Please, consider donating funds to support us Donate

See more blog, documentation, and more on https://jasperphp.net

Export formats

PDF
XLS

Supported tags/components

TAG/component Status TAG/component Status
Basic elements
Text Field OK Static Text OK
Image OK Break OK
Rectangle OK Line OK
SubReport* OK Barcode OK
Composite elements
Page Number OK Total Pages OK
Current Date OK Page X of Y OK
Bands
Title OK Page Header OK
Group OK Detail OK
Column Header OK Column Footer OK
Page Footer OK Sumary OK
Background OK Style OK
Frame OK dynamic table OK
* Subreports are supported recursively and unlimited

Other features

  • sum, average,minimum, max of variables
  • read and calculate subreport variables
  • array of objects as input data
  • textfield with html render with data replacement
  • active record
  • Conditional styles ready too
  • support for Laravel DB Facade adding tag `property name="net.sf.jasperreports.data.adapter" value="laravel.sqlsrv"` on jrxml files or edit Default data adapter on report properties on JasperSoft Studio

  • Generic sample

    <?php
    
    use JasperPHP\Report;
    use JasperPHP\ado\TTransaction;
    use JasperPHP\ado\TLogger;
    use JasperPHP\ado\TLoggerHTML;
    
    //use \NumberFormatter;
    //use PHPexcel as PHPexcel; // experimental
    /**
     * classe TJasper
     *
     * @author   Rogerio Muniz de Castro <[email protected]>
     * @version  2018.10.15
     * @access   restrict
     * 
     * 2015.03.11 -- create
     * 2018.10.15 -- revision and internationalize, add TLogger classes
     * */
    class TJasper {
    
        private $report;
        private $type;
        private $param;
    
        /**
         * method __construct()
         * 
         * @param $jrxml = a jrxml file name
         * @param $param = a array with params to use into jrxml report
         */
        public function __construct($jrxml, array $param) {
            $GLOBALS['reports'] = array();
            $xmlFile = $jrxml;
            $this->type = (array_key_exists('type', $param)) ? $param['type'] : 'pdf';
            //error_reporting(0);
            $this->param = $param;
            $this->report = new JasperPHP\Report($xmlFile, $param); // $GLOBALS['reports'][$xmlFile];
            switch ($this->type) {
                case 'pdf':
                    JasperPHP\Instructions::prepare($this->report);
                    break;
                case 'xls':
                    JasperPHP\Instructions::setProcessor('\JasperPHP\XlsProcessor');
                    JasperPHP\Instructions::prepare($this->report);
                    break;
            }
        }
    
        public function outpage($type = 'pdf') {
            $this->report->generate();
            $this->report->out();
            switch ($this->type) {
                case 'pdf':
                    $pdf = JasperPHP\Instructions::get();
                    $pdf->Output('report.pdf', "I");
                    break;
                case 'xls':
                    header('Content-Type: application/vnd.ms-excel');
                    header('Content-Disposition: attachment;filename="01simple.xls"');
                    header('Cache-Control: max-age=0');
                    // If you're serving to IE 9, then the following may be needed
                    header('Cache-Control: max-age=1');
                    // If you're serving to IE over SSL, then the following may be needed
                    header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
                    header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
                    header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
                    header('Pragma: public'); // HTTP/1.0
                    $objWriter = PHPExcel_IOFactory::createWriter(JasperPHP\Instructions::$objOutPut, 'Excel5');
                    $objWriter->save('php://output');
                    break;
            }
        }
    
        public function setVariable($name, $value) {
            $this->report->arrayVariable[$name]['initialValue'] = $value;
        }
    
    }
    
    require('autoloader.php');
    require('../../tecnickcom/tcpdf/tcpdf.php'); // point to tcpdf class previosly instaled , (probaly in composer instalations)
    require('../../phpoffice/phpexcel/Classes/PHPExcel.php'); // point to tcpdf class previosly instaled , (probaly in composer instalations)
    //require('../TCPDF/tcpdf.php'); // point to tcpdf class previosly instaled , (probaly in stand alone instalations)
    // on production using composer instalation is not necessaty 
    
    $report_name = isset($_GET['report']) ? $_GET['report'] : 'testReport.jrxml';  // sql into testReport.txt report do not select any table.
    TTransaction::open('dev');
    TTransaction::setLogger(new TLoggerHTML('log.html'));
    $jasper = new TJasper($report_name, $_GET);
    $jasper->outpage();
    ?>

    Requirements

    • PHP 5.2+
    • "tecnickcom/tcpdf":"6.2.*"
    • "PHPOffice/PHPExcel" only of XLS export

    How to use this sample

    Define database conections params into file config\dev.ini
    View file src\ado\TConection.php to define database type
    Sample URL:
    http://localhost/vendor/quilhasoft/JasperPHP/TJasper.class.php?param1=foo&param2=bar
    URL params passed into URL are the params defined into xmlr file.

    Using composer

    Add "quilhasoft/jasperphp":"dev-master" into your composer config file and update/install

    Live samples

    • A basic test: Here
    • A burn test, 201 pages, hosted in a default hostgator server: Here
    • Brasilian payment method "boleto" in "carne":Here
    • Brasilian payment method "boleto" in A4 :Here
      ** Brasilian boleto project disponible in QuilhaSoft/JasperPHP-OpenBoleto.

    License

    • MIT License

    jasperphp's People

    Contributors

    allgood avatar dadeke avatar gamadoleo avatar juliosborchia avatar rctnet avatar

    Stargazers

     avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

    Watchers

     avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

    jasperphp's Issues

    Grouping not working

    When using groups on jasper file it doesn't group the records accordingly.

    I have a "cidades" listing grouped by "mesoregioes" and "estados"

    Following image shows the output of jaspersoft studio and jasperphp repesctively:

    image

    image

    I've tested without the nested groups, same problem.

    Number and date format

    What is the best way (is supported any) to format monetary numbers and dates on the report?

    $P!{name} Parameters

    how to work with this type of parameter, used for example to pass sql statements, I know it may be a failure for sql injector but it will not be used for parameter edited by the user and in jasperReporta it works normally. I wanted to know how to adopt in your api.

    select * from pessoa where ($P!{p_where})

    ??

    JasperPHP + iReport 5.6 Error

    Grettings,

    I have a iReport file with 3 pages wich contains some fields and controls but when i test the report in pdf generation this shows the fields with another position, i make a video for a better explain, this is the link https://youtu.be/yKdgeFYh7dI.

    I hope, you can help me because i'm workin in this project some weeks and i need finish this work.

    Thakns,

    Omar

    Fatal error with php 8.0

    I am using PHP 8.0 and getting following errors, is there a known issue to run under php 8.0?

    Fatal error: Uncaught Error: Non-static method JasperPHP\StaticText::formatPen() cannot be called statically in /var/www/html/reports/MyCode/jasperPHP_20211007/quilhasoft/jasperphp/src/StaticText.php:204 Stack trace: #0 /var/www/html/reports/MyCode/jasperPHP_20211007/quilhasoft/jasperphp/src/StaticText.php(62): JasperPHP\StaticText::formatBox() #1 /var/www/html/reports/MyCode/jasperPHP_20211007/quilhasoft/jasperphp/src/Band.php(26): JasperPHP\StaticText->generate() #2 /var/www/html/reports/MyCode/jasperPHP_20211007/quilhasoft/jasperphp/src/Element.php(174): JasperPHP\Band->generate() #3 /var/www/html/reports/MyCode/jasperPHP_20211007/quilhasoft/jasperphp/src/ColumnHeader.php(37): JasperPHP\Element->generate() #4 /var/www/html/reports/MyCode/jasperPHP_20211007/quilhasoft/jasperphp/src/Element.php(174): JasperPHP\ColumnHeader->generate() #5 /var/www/html/reports/MyCode/jasperPHP_20211007/quilhasoft/jasperphp/src/Report.php(668): JasperPHP\Element->generate() #6 /var/www/html/reports/MyCode/Report001/report.php(26): JasperPHP\Report->generate() #7 /var/www/html/reports/MyCode/Report001/report.php(59): TJasper->outpage() #8 {main} thrown in /var/www/html/reports/MyCode/jasperPHP_20211007/quilhasoft/jasperphp/src/StaticText.php on line 204

    Filter by Collection or Array

    Olá, Rogério. Gostaria de saber se o JasperPHP oferece suporte a filtros sql que utilizam parâmetros Java Collection no JasperReports. Consultas como a seguinte:

    SELECT * FROM bd_banco.contratos WHERE $X{IN, idCampanha, FILTRO_ID} AND $X{IN, idStatus, FILTRO_STATUS}

    Desde já, agradeço a atenção.

    Band title with subreport, empty space

    Building a title with elements in the same report I have no problem, but as I work with a standard header I decide to work with subreport, in the subreport I just left the band title and left the subreport page extremely small, I also reduce the size of the subreport in the main report. title band, however it generates an empty space in the title region, see the image, there is something that can be done for this, because the idea of using a subreport in the title makes it much easier.
    subreport

    Suport add element frame?

    There is the possibility of adding support to the frame element, as I use it to group elements within the report and allowing, for example, to apply a specific placement in the frame and it auto-adjusts to the content that contains them

    Conditional print how to use?

    conditional print how to use?
    I have reports that I basically use two functions for.
    New Boolean and the AND() and OR() functions all native to jasper report, I realize that JasperPHP doesn't work I would like to know what is the recommendation to work with conditional print and how I can adapt my example:
    printWhenExpression:

    AND(new Boolean($F{invoice_bar_code} != null), new Boolean($F{invoice_payment_form_id} != 4) )

    Conditional colors?

    Is conditional color supported? tried to add directly via html <font color"red">
    however without success, I would like to know what is the recommended way to work with conditional colors, for example I wanted to display a zebra listing with conditioned color.

    Subreports

    Estimados todos, tengo un problema al querer exportar un reporte que contiene Sub-reportes, en el Jasper Report 6.0 no me presenta ningún problema, se muestra correctamente, pero al momento de ejecutarlo en la aplicación, me aparece el error que indica que no se encuentra el archivo, he intentado poniendo solo el nombre del reporte (que esta en el mismo directorio que el principal) y poniendo la ruta completa del archivo, pero de ninguna de las dos maneras muestra el reporte.

    Adjunto el mensaje de error:

    Fatal error: Uncaught JasperPHP\Exception: File http://localhost:8089/hrmedic/jasperphp/report/rpthisrec.jasper not found!! in C:\xampp\htdocs\hrmedic\JasperPHP\src\Report.php:47 Stack trace: #0 C:\xampp\htdocs\hrmedic\JasperPHP\src\Subreport.php(40): JasperPHP\Report->__construct('http://localhos...', Array) #1 C:\xampp\htdocs\hrmedic\JasperPHP\src\Band.php(26): JasperPHP\Subreport->generate(Object(JasperPHP\Report)) #2 C:\xampp\htdocs\hrmedic\JasperPHP\src\Element.php(174): JasperPHP\Band->generate(Object(JasperPHP\Report)) #3 C:\xampp\htdocs\hrmedic\JasperPHP\src\GroupHeader.php(40): JasperPHP\Element->generate(Array) #4 C:\xampp\htdocs\hrmedic\JasperPHP\src\Element.php(174): JasperPHP\GroupHeader->generate(Object(JasperPHP\Report)) #5 C:\xampp\htdocs\hrmedic\JasperPHP\src\GroupHeader.php(40): JasperPHP\Element->generate(Array) #6 C:\xampp\htdocs\hrmedic\JasperPHP\src\Detail.php(44): JasperPHP\GroupHeader->generate(Object(JasperPHP\Report)) #7 C:\xampp\htdocs\hrmedic\JasperPHP\src\Element.php(174): JasperPHP\Detail->ge in C:\xampp\htdocs\hrmedic\JasperPHP\src\Report.php on line 47

    image

    En Jasper Report 6.0 Preview
    image

    Barcode doesn't respect position

    Barcode element doesn't respect the position defined on XML

    The sample attached have two elements, a rectangle and a barcode, both with same position and dimensions, but barcode ends outside the defined on the report.

    image

    Stretch overflowed fields not stretching it's band

    On a report with two detail bands, the first one have a field that stretchs with its contents, the expected behavior is to move the following band down but it gets overwritten.

    Looks like the stretched field isn't stretching its parent band

    Image of sample is attached.

    image

    Feature suggestion: accept different types of dbData

    Currently only supported dbData is an array of objects.

    It should be possible to accept an array of arrays and an object that is Traversable/Countable/ArrayAccess ... this is very common on Laravel's Eloquent ORM.

    Will be submitting soon a PR that adjusts this.

    Node no longer exists

    Mestre,

    Estou tentando usar o JasperPHP no Laravel, coloquei um report de teste dentro da pasta public, e a pasta config com a configuração do BD pra teste e ao tentar imprimir recebo o seguinte erro:

    [2020-05-04 14:29:52] local.ERROR: JasperPHP\Element::__construct(): Node no longer exists {"exception":"[object] (ErrorException(code: 0): JasperPHP\Element::__construct(): Node no longer exists at E:\Web_Projetos\teste-boleto\vendor\quilhasoft\jasperphp\src\Element.php:28)

    laravel-2020-05-04.log

    Minha classe pra carregar os reports:

    LoadReport.php.txt

    e o método que chama o report:
    public function teste4() {
    TTransaction::open("dev");
    TTransaction::setLogger(new TLoggerHTML("log.html"));
    $jasper = new LoadReport("reports/testeCS.jrxml", array());
    $jasper->outpage();

    }
    

    desde já agradeço a atenção recebida.

    Need full document

    i want to integrate this library in my project.but i can't,can u please help me

    PHP 8.2 support

    When using php 8.2 tcpdf have some failures with the bad use of strpos inverting the parameters.

    Solution appears to be update to recent tcpdf

    Se visualizan formulas en Campos con Expresiones Lógicas

    Estimados amigos,

    Quisiera su ayuda, no se de que manera podría resolver el problema de que al momento de utilizar una expresión lógica en un campo de mi reporte JasperReport, al presentar se en PDF se visualiza la formula, cuando debería presentarse el contenido.

    He utilizado variables para poder realizar la evaluación lógica antes de usar el campo directamente, pero aun así se da el problema.

    Cabe indicar que he actualizado la librería con la ultima versión de Julio-2021.

    Visualización del PDF

    image

    Visualización del Preliminar en JasperStudio 6

    image

    Agradezco de antemano por su ayuda.

    Saludos,

    Omar Noboa

    Does not respect the positioning

    Look guys, I'm facing a problem of misconfiguring the positioning of the text fields when generating in jasperphp I would like to know if there is any detail to be done to avoid this, the report generated in jasper studio and jasperphp is attached.

    jasper report
    jasperphp

    Hostgator

    @Rctnet boa tarde!
    Este projeto roda na hospedagem compartilhada do hostgator?
    Obrigado!

    HEADER COLUMN REPEAT?

    Hello, this project has gotten better and better, and it will really make reporting a lot easier, especially for those who don't want to rely on java generators.

    And I hope it gets better and better!
    See only COLUMN HEADER is supported in JASPERPHP generator, but there is a behavior that we could improve, the COLUMN HEADER in its default behavior is repeated on all pages (in JASPER STUDIO), but in JASPERPHP this does not happen, how could we implement this behavior? wouldn't it be possible to make HEADER COLUMN REPEAT?

    How to install?

    I have tried with "composer require quilhasoft/jasperphp" but it doesn't work.

    No shows images in pdf

    Grettings,

    I've implemented your class in my project, when i process the pdf no shows images.
    Please tell me how can i do for shows the images.

    Thanks,

    Omar Noboa

    JasperPHP_01
    JasperPHP_02

    TODO list

    internationalization

    automate support to decimal and thousand points
    use php internationalization classes to get names off month, week days and number names

    Rectangle does not put the border?

    I have been using the rectangle component, but it does not respect the application of the border, how can we check to solve this? or am i doing something wrong?

    Error on band Title

    When using the band Title there is an unknown variable being referenced: $rowIndex.

    I do not know what is expected, I changed my local code to point to the first record if datasource is an array:

    diff --git a/src/Title.php b/src/Title.php
    index 121b256..c94f406 100644
    --- a/src/Title.php
    +++ b/src/Title.php
    @@ -20,8 +20,7 @@ class Title extends Element {
             $recordObject = array_key_exists('recordObj', $arrayVariable) ? $arrayVariable['recordObj']['initialValue'] : "stdClass";
             // echo  $recordObject;
             //var_dump($obj);
    -        $row = ( is_array($dbData) ) ? (array_key_exists($rowIndex, $dbData)) ? $dbData[$rowIndex] : null : $obj->rowData;
    -        //$obj->rowData = $row;
    +        $row = ( is_array($dbData) ) ? (array_key_exists(0, $dbData)) ? $dbData[0] : null : $obj->rowData;
             if ($row) {
                 switch ($row) {
                     case (is_object($row)):

    localhost relatório não carrega

    Boa Tarde,

    Acho que não entendi a documentação.

    Mais eu baixei a pasta descompactei, edite o dev.ini criei um arquivo.php com o contéudo da documentação, criei um template.jrxml somente com texto(sem acesso no banco de dados) apenas pra teste mesmo; coloquei o e chamei no browser o arquivo.php, mais acusa:

    localhost não consegue atender a esta solicitação no momento.

    Desde já agradeço

    Recommend Projects

    • React photo React

      A declarative, efficient, and flexible JavaScript library for building user interfaces.

    • Vue.js photo Vue.js

      🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

    • Typescript photo Typescript

      TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

    • TensorFlow photo TensorFlow

      An Open Source Machine Learning Framework for Everyone

    • Django photo Django

      The Web framework for perfectionists with deadlines.

    • D3 photo D3

      Bring data to life with SVG, Canvas and HTML. 📊📈🎉

    Recommend Topics

    • javascript

      JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

    • web

      Some thing interesting about web. New door for the world.

    • server

      A server is a program made to process requests and deliver data to clients.

    • Machine learning

      Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

    • Game

      Some thing interesting about game, make everyone happy.

    Recommend Org

    • Facebook photo Facebook

      We are working to build community through open source technology. NB: members must have two-factor auth.

    • Microsoft photo Microsoft

      Open source projects and samples from Microsoft.

    • Google photo Google

      Google ❤️ Open Source for everyone.

    • D3 photo D3

      Data-Driven Documents codes.