Bug 21560: create Koha::Util::OpenDocument with subroutine for ODS generation
[koha.git] / Koha / Util / OpenDocument.pm
1 package Koha::Util::OpenDocument;
2
3 # Copyright 2019 Biblibre
4 #
5 # This file is part of Koha.
6 #
7 # Koha is free software; you can redistribute it and/or modify it under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 3 of the License, or (at your option) any later
10 # version.
11 #
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License along
17 # with Koha; if not, write to the Free Software Foundation, Inc.,
18 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19
20 use Modern::Perl;
21
22 use Encode qw( decode );
23 use File::Temp;
24 use File::Basename qw( dirname );
25 use OpenOffice::OODoc;
26
27 use parent qw( Exporter );
28
29 our @EXPORT = qw(
30   generate_ods
31 );
32
33 =head1 NAME
34
35 Koha::Util::OpenDocument - utility class to manage filed in Open Document Format aka OpenDocument
36
37 =head1 METHODS
38
39 =head2 generate_ods
40
41 Generate an Open Document Sheet
42
43 Arguments are file path and content as an arrayref of lines containing arrayrefs of cells.
44
45 =cut
46
47
48 sub generate_ods {
49     my ( $filepath, $content ) = @_;
50
51     unless ( $filepath && $content ) {
52         return;
53     }
54     my @input_rows = @$content;
55     my $nb_rows    = scalar @input_rows;
56     my $nb_cols;
57     if ($nb_rows) {
58         $nb_cols= scalar @{ $input_rows[0] };
59     }
60
61     # Create document
62     my $wdir = dirname($filepath);
63     odfWorkingDirectory($wdir);
64     my $odf_doc = odfDocument( file => $filepath, create => 'spreadsheet' );
65
66     if ($nb_rows) {
67         # Prepare sheet
68         my $odf_sheet = $odf_doc->expandTable( 0, $nb_rows + 1, $nb_cols );
69         my @odf_rows = $odf_doc->getTableRows($odf_sheet);
70
71         # Writing
72         for ( my $i = 0 ; $i < $nb_rows ; $i++ ) {
73             for ( my $j = 0 ; $j < $nb_cols ; $j++ ) {
74                 my $cellval = $input_rows[$i][$j];
75                 $odf_doc->cellValue( $odf_rows[$i], $j, $cellval );
76             }
77         }
78     }
79
80     # Done
81     $odf_doc->save();
82
83     return $odf_doc;
84 }
85
86 1;
87 __END__
88
89 =head1 AUTHOR
90
91 Koha Development Team <http://koha-community.org/>
92
93 Fridolin Somers <fridolin.somers@biblibre.com>
94
95 =cut