rewrite basic generator in perl
authorDobrica Pavlinusic <dpavlin@rot13.org>
Wed, 6 Apr 2011 16:34:06 +0000 (18:34 +0200)
committerDobrica Pavlinusic <dpavlin@rot13.org>
Wed, 6 Apr 2011 16:34:06 +0000 (18:34 +0200)
I just couldn't fix bash CSV parser fast enough to have it working
for conference.

I also implemented using single inkscpape over shell pipe which improved
speed dramatically.

It doesn't intergrate in Inkscape at all (yet) but has following simple
syntax:

  usage: ./generator.pl template.svg data.csv

generator.pl [new file with mode: 0755]

diff --git a/generator.pl b/generator.pl
new file mode 100755 (executable)
index 0000000..2db22c7
--- /dev/null
@@ -0,0 +1,64 @@
+#!/usr/bin/perl
+use warnings;
+use strict;
+
+use Text::CSV;
+use Data::Dump qw(dump);
+use autodie;
+
+my ( $svg_template, $csv_file ) = @ARGV;
+
+die "usage: $0 template.svg data.csv\n" unless -r $svg_template && -r $csv_file;
+
+my $svg;
+{
+       local $/ = undef;
+       open(my $fh, '<', $svg_template);
+       $svg = <$fh>;
+       close $fh;
+}
+
+my $vars;
+
+my $csv = Text::CSV->new ( { binary => 1 } )  # should set binary attribute.
+       or die "Cannot use CSV: ".Text::CSV->error_diag ();
+
+my $nr = 1;
+
+open(my $inkscape, '|-', 'inkscape --shell --without-gui');
+
+open my $fh, "<:encoding(utf8)", $csv_file or die "$csv_file: $!";
+while ( my $row = $csv->getline( $fh ) ) {
+       if ( ! $vars ) { # header row
+               my $col = 0;
+               $vars->{ '%VAR_' . $_ . '%' } = $col++ foreach @$row;
+               warn "variables ",dump $vars;
+               next;
+       } else {
+               my $new_svg = $svg;
+               foreach my $pattern ( keys %$vars ) {
+                       $new_svg =~ s/\Q$pattern\E/$row->[$vars->{$pattern}]/sgx ||
+                               warn "didn't find $pattern in $svg_template";
+               }
+               my $tmp_path = sprintf "/tmp/%s-%04d", $svg_template, $nr++;
+               open(my $fh, '>', "$tmp_path.svg");
+               print $fh $new_svg;
+               close $fh;
+
+               print $inkscape "$tmp_path.svg --export-area-page --export-pdf $tmp_path.pdf\n";
+
+               warn "# $_ ", -s $_, " bytes\n" foreach glob "$tmp_path.*";
+       }
+}
+$csv->eof or $csv->error_diag();
+close $fh;
+
+close $inkscape;
+
+warn "generated $nr files in /tmp/$svg_template-*.pdf\n";
+
+my $print_pdf = 'nup.pdf';
+
+system "pdfnup --suffix nup --nup '2x5' --paper a4paper --no-landscape --scale 1.0 --frame true --noautoscale true --outfile $print_pdf -- /tmp/$svg_template-*.pdf";
+
+warn "PRINT file: $print_pdf ", -s $print_pdf, " bytes\n";