92400a593ab9e3eb93287a13da629bf3c8fbdf26
[ink-generator.git] / generator.pl
1 #!/usr/bin/perl
2 use warnings;
3 use strict;
4
5 use Text::CSV;
6 use Data::Dump qw(dump);
7 use autodie;
8
9 my ( $svg_template, $csv_file ) = @ARGV;
10
11 die "usage: $0 template.svg data.csv\n" unless -r $svg_template && -r $csv_file;
12
13 my $svg;
14 {
15         local $/ = undef;
16         open(my $fh, '<:encoding(utf8)', $svg_template);
17         $svg = <$fh>;
18         close $fh;
19 }
20
21 my $vars;
22
23 my $csv = Text::CSV->new ( { binary => 1 } )  # should set binary attribute.
24         or die "Cannot use CSV: ".Text::CSV->error_diag ();
25
26 my $nr = 1;
27
28 open(my $inkscape, '|-', 'inkscape --shell --without-gui');
29
30 open my $fh, "<:encoding(utf8)", $csv_file or die "$csv_file: $!";
31 while ( my $row = $csv->getline( $fh ) ) {
32         if ( ! $vars ) { # header row
33                 my $col = 0;
34                 $vars->{ '%VAR_' . $_ . '%' } = $col++ foreach @$row;
35                 warn "variables ",dump $vars;
36                 next;
37         } else {
38                 my $new_svg = $svg;
39                 foreach my $pattern ( keys %$vars ) {
40                         $new_svg =~ s/\Q$pattern\E/$row->[$vars->{$pattern}]/sgx ||
41                                 warn "didn't find $pattern in $svg_template";
42                 }
43                 my $tmp_path = sprintf "/tmp/%s-%04d", $svg_template, $nr++;
44                 open(my $fh, '>', "$tmp_path.svg");
45                 print $fh $new_svg;
46                 close $fh;
47
48                 print $inkscape "$tmp_path.svg --export-area-page --export-pdf $tmp_path.pdf\n";
49
50                 warn "# $_ ", -s $_, " bytes\n" foreach glob "$tmp_path.*";
51         }
52 }
53 $csv->eof or $csv->error_diag();
54 close $fh;
55
56 close $inkscape;
57
58 warn "generated $nr files in /tmp/$svg_template-*.pdf\n";
59
60 my $print_pdf = 'nup.pdf';
61
62 system "pdfnup --suffix nup --nup '2x5' --paper a4paper --no-landscape --scale 1.0 --frame true --noautoscale true --outfile $print_pdf -- /tmp/$svg_template-*.pdf";
63
64 warn "PRINT file: $print_pdf ", -s $print_pdf, " bytes\n";