root/main/trunk/greenstone2/perllib/plugins/PDFPlugin.pm @ 32290

Revision 32290, 17.2 KB (checked in by ak19, 13 months ago)

1. Making paged_pretty_html the default rather than pretty_html, since it's likely more users will want their converted PDF sectionalised. 2. Hopefully improved the display strings to make sense for users rather than for me.

  • Property svn:keywords set to Author Date Id Revision
Line 
1###########################################################################
2#
3# PDFPlugin.pm -- reasonably with-it pdf plugin
4# A component of the Greenstone digital library software
5# from the New Zealand Digital Library Project at the
6# University of Waikato, New Zealand.
7#
8# Copyright (C) 1999-2001 New Zealand Digital Library Project
9#
10# This program is free software; you can redistribute it and/or modify
11# it under the terms of the GNU General Public License as published by
12# the Free Software Foundation; either version 2 of the License, or
13# (at your option) any later version.
14#
15# This program is distributed in the hope that it will be useful,
16# but WITHOUT ANY WARRANTY; without even the implied warranty of
17# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18# GNU General Public License for more details.
19#
20# You should have received a copy of the GNU General Public License
21# along with this program; if not, write to the Free Software
22# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23#
24###########################################################################
25package PDFPlugin;
26
27use strict;
28no strict 'refs'; # so we can use a var for filehandles (e.g. STDERR)
29no strict 'subs'; # allow filehandles to be variables and viceversa
30
31use ReadTextFile;
32use unicode;
33
34use AutoLoadConverters;
35use ConvertBinaryFile;
36
37@PDFPlugin::ISA = ('ConvertBinaryFile', 'AutoLoadConverters', 'ReadTextFile');
38
39
40my $convert_to_list =
41    [ { 'name' => "auto",
42    'desc' => "{ConvertBinaryFile.convert_to.auto}" },
43      { 'name' => "html",
44    'desc' => "{ConvertBinaryFile.convert_to.html}" },
45      { 'name' => "text",
46    'desc' => "{ConvertBinaryFile.convert_to.text}" },
47      { 'name' => "pagedimg_jpg",
48    'desc' => "{ConvertBinaryFile.convert_to.pagedimg_jpg}"},
49      { 'name' => "pagedimg_gif",
50    'desc' => "{ConvertBinaryFile.convert_to.pagedimg_gif}"},
51      { 'name' => "pagedimg_png",
52    'desc' => "{ConvertBinaryFile.convert_to.pagedimg_png}"},
53      ];
54
55
56my $arguments =
57    [
58     { 'name' => "convert_to",
59       'desc' => "{ConvertBinaryFile.convert_to}",
60       'type' => "enum",
61       'reqd' => "yes",
62       'list' => $convert_to_list,
63       'deft' => "html" },   
64     { 'name' => "process_exp",
65       'desc' => "{BaseImporter.process_exp}",
66       'type' => "regexp",
67       'deft' => &get_default_process_exp(),
68       'reqd' => "no" },
69     { 'name' => "block_exp",
70       'desc' => "{CommonUtil.block_exp}",
71       'type' => "regexp",
72       'deft' => &get_default_block_exp() },
73     { 'name' => "metadata_fields",
74       'desc' => "{HTMLPlugin.metadata_fields}",
75       'type' => "string",
76       'deft' => "Title,Author,Subject,Keywords" },
77      { 'name' => "metadata_field_separator",
78    'desc' => "{HTMLPlugin.metadata_field_separator}",
79    'type' => "string",
80    'deft' => "" },
81     { 'name' => "noimages",
82       'desc' => "{PDFPlugin.noimages}",
83       'type' => "flag" },
84     { 'name' => "allowimagesonly",
85       'desc' => "{PDFPlugin.allowimagesonly}",
86       'type' => "flag" },
87     { 'name' => "complex",
88       'desc' => "{PDFPlugin.complex}",
89       'type' => "flag" },
90     { 'name' => "nohidden",
91       'desc' => "{PDFPlugin.nohidden}",
92       'type' => "flag" },
93     { 'name' => "zoom",
94       'desc' => "{PDFPlugin.zoom}",
95       'deft' => "2",
96       'range' => "1,3", # actually the range is 0.5-3
97       'type' => "int" },
98     { 'name' => "use_sections",
99       'desc' => "{PDFPlugin.use_sections}",
100       'type' => "flag" },
101     { 'name' => "description_tags",
102       'desc' => "{HTMLPlugin.description_tags}",
103       'type' => "flag" },
104      { 'name' => "use_realistic_book",
105        'desc' => "{PDFPlugin.use_realistic_book}",
106    'type' => "flag"}
107     ];
108
109my $options = { 'name'     => "PDFPlugin",
110        'desc'     => "{PDFPlugin.desc}",
111        'abstract' => "no",
112        'inherits' => "yes",
113        'srcreplaceable' => "yes", # Source docs in PDF can be replaced with GS-generated html     
114        'args'     => $arguments };
115
116sub new {
117    my ($class) = shift (@_);
118    my ($pluginlist,$inputargs,$hashArgOptLists) = @_;
119    push(@$pluginlist, $class);
120
121    push(@$inputargs,"-title_sub");
122    push(@$inputargs,'^(Page\s+\d+)?(\s*1\s+)?');
123
124    push(@{$hashArgOptLists->{"ArgList"}},@{$arguments});
125    push(@{$hashArgOptLists->{"OptList"}},$options);
126
127    my $auto_converter_self = new AutoLoadConverters($pluginlist,$inputargs,$hashArgOptLists,["PDFBoxConverter"],1);
128    my $cbf_self = new ConvertBinaryFile($pluginlist, $inputargs, $hashArgOptLists);
129    my $self = BaseImporter::merge_inheritance($auto_converter_self, $cbf_self);
130   
131    if ($self->{'info_only'}) {
132    # don't worry about any options etc
133    return bless $self, $class;
134    }
135   
136    $self = bless $self, $class;
137    $self->{'file_type'} = "PDF";
138
139    # PDFPlugin is deprecated and migrating users should hereafter choose between
140    # PDFv1Plugin, if they want to use the old pdftohtml tool's capabilities,
141    # and PDFv2Plugin, if they want to use pdfbox or the new xpdftools capabilities.
142    &gsprintf::gsprintf(STDERR, "{PDFPlugin.deprecated_plugin}\n");
143   
144    # these are passed through to gsConvert.pl by ConvertBinaryFile.pm
145    my $zoom = $self->{"zoom"};
146    # By default, PDFPlugin assumes gsConvert.pl will run the old pdftohtml conversion tool,
147    # But if pdfbox conversion is turned on, the tool used is pdfbox (which is presently an
148    # AutoLoadConverter and therefore bypasses gsConvert.pl)
149    $self->{'convert_options'} = "-pdf_tool pdftohtml";
150    $self->{'convert_options'} .= " -pdf_zoom $zoom";
151    $self->{'convert_options'} .= " -pdf_complex" if $self->{"complex"};
152    $self->{'convert_options'} .= " -pdf_nohidden" if $self->{"nohidden"};
153    $self->{'convert_options'} .= " -pdf_ignore_images" if $self->{"noimages"};
154    $self->{'convert_options'} .= " -pdf_allow_images_only" if $self->{"allowimagesonly"};
155
156    # check convert_to
157    if ($self->{'convert_to'} eq "text" && $ENV{'GSDLOS'} =~ /^windows$/i) {
158    &gsprintf::gsprintf(STDERR, "{PDFPlugin.win_old_pdftotext_unsupported}\n");
159    $self->{'convert_to'} = "html";
160    }
161    elsif ($self->{'convert_to'} eq "auto") {
162    # choose html ?? is this the best option
163    $self->{'convert_to'} = "html";
164    }
165    if ($self->{'use_realistic_book'}) {
166    if ($self->{'convert_to'} ne "html") {
167        &gsprintf::gsprintf(STDERR, "PDFv2Plugin: {PDFPlugin.html_for_realistic_book}\n");
168        $self->{'convert_to'} = "html";
169    }
170    }
171    # set convert_to_plugin and convert_to_ext
172    $self->set_standard_convert_settings();
173
174    my $secondary_plugin_name = $self->{'convert_to_plugin'};
175    my $secondary_plugin_options = $self->{'secondary_plugin_options'};
176
177    if (!defined $secondary_plugin_options->{$secondary_plugin_name}) {
178    $secondary_plugin_options->{$secondary_plugin_name} = [];
179    }
180    my $specific_options = $secondary_plugin_options->{$secondary_plugin_name};
181
182    # following title_sub removes "Page 1" added by pdftohtml, and a leading
183    # "1", which is often the page number at the top of the page. Bad Luck
184    # if your document title actually starts with "1 " - is there a better way?
185    push(@$specific_options , "-title_sub", '^(Page\s+\d+)?(\s*1\s+)?');
186    my $associate_tail_re = $self->{'associate_tail_re'};
187    if ((defined $associate_tail_re) && ($associate_tail_re ne "")) {
188    push(@$specific_options, "-associate_tail_re", $associate_tail_re);
189    }
190    push(@$specific_options, "-file_rename_method", "none");
191   
192    if ($secondary_plugin_name eq "HTMLPlugin") {
193    # pdftohtml always produces utf8 - What about pdfbox???
194    # push(@$specific_options, "-input_encoding", "utf8");
195    push(@$specific_options, "-extract_language") if $self->{'extract_language'};
196    push(@$specific_options, "-processing_tmp_files");
197    # Instruct HTMLPlug (when eventually accessed through read_into_doc_obj)
198    # to extract these metadata fields from the HEAD META fields
199    if (defined $self->{'metadata_fields'} && $self->{'metadata_fields'} =~ /\S/) {
200        push(@$specific_options,"-metadata_fields",$self->{'metadata_fields'});
201    } else {
202        push(@$specific_options,"-metadata_fields","Title,GENERATOR,date,author<Creator>");
203    }
204    if (defined $self->{'metadata_field_separator'} && $self->{'metadata_field_separator'} =~ /\S/) {
205        push(@$specific_options,"-metadata_field_separator",$self->{'metadata_field_separator'});
206    }
207    if ($self->{'use_sections'} || $self->{'description_tags'}) {
208        $self->{'description_tags'} = 1;
209        push(@$specific_options, "-description_tags");
210    }
211    if ($self->{'use_realistic_book'}) {
212        push(@$specific_options, "-use_realistic_book");
213    }
214    }
215    elsif ($secondary_plugin_name eq "PagedImagePlugin") {
216    push(@$specific_options, "-screenviewsize", "1000");
217    push(@$specific_options, "-enable_cache");
218    push(@$specific_options, "-processing_tmp_files");
219    }
220
221    $self = bless $self, $class;
222    $self->load_secondary_plugins($class,$secondary_plugin_options,$hashArgOptLists);
223    return $self;
224}
225
226sub get_default_process_exp {
227    my $self = shift (@_);
228
229    return q^(?i)\.pdf$^;
230}
231
232# so we don't inherit HTMLPlug's block exp...
233sub get_default_block_exp {
234    return "";
235}
236
237sub init {
238    my $self = shift (@_);
239
240    # ConvertBinaryFile init
241    $self->SUPER::init(@_);
242    $self->AutoLoadConverters::init(@_);
243
244}
245
246sub begin {
247    my $self = shift (@_);
248
249    $self->AutoLoadConverters::begin(@_);
250    $self->SUPER::begin(@_);
251
252}
253
254sub deinit {
255    my $self = shift (@_);
256   
257    $self->AutoLoadConverters::deinit(@_);
258    $self->SUPER::deinit(@_);
259
260}
261 
262# By setting hashing to be on ga xml this ensures that two
263# PDF files that are identical except for the metadata
264# to hash to different values. Without this, when each PDF
265# file is converted to HTML there is a chance that they
266# will both be *identical* if the conversion utility does
267# not embed the metadata in the generated HTML. This is
268# certainly the case when PDFBOX is being used.
269
270# This change makes this convert to based plugin more
271# consistent with the original vision that the same document
272# with different metadata should
273# be seen as different.
274
275sub get_oid_hash_type {
276    my $self = shift (@_);
277    return "hash_on_ga_xml";
278}
279 
280 
281sub tmp_area_convert_file {
282
283    my $self = shift (@_);
284    return $self->AutoLoadConverters::tmp_area_convert_file(@_);
285
286}
287
288sub convert_post_process
289{
290    my $self = shift (@_);
291    my ($conv_filename) = @_;
292
293    my $outhandle=$self->{'outhandle'};
294
295    #$self->{'input_encoding'} = "utf8"; # The output is always in utf8 (is it?? it is for html, but what about other types?)
296    #my ($language, $encoding) = $self->textcat_get_language_encoding ($conv_filename);
297
298    # read in file ($text will be in utf8)
299    my $text = "";
300    # encoding will be utf8 for html files - what about other types? will we do this step for them anyway?
301    $self->read_file ($conv_filename, "utf8", "", \$text);
302
303    # To support the use_sections option with PDFBox: Greenstone splits PDFs into pages for
304    # sections. The PDFPlugin code wants each new page to be prefixed with <a name=pagenum></a>,
305    # which it then splits on to generate page-based sections. However, that's not what PDFBox
306    # generates in its HTML output. Fortunately, PDFBox does have its own page-separator: it
307    # embeds each page in an extra div. The div opener is:
308    # <div style=\"page-break-before:always; page-break-after:always\">
309    # The PDFPlugin now looks for this and prefixes <a name=0></a> to each such div. (The
310    # pagenumber is fixed at 0 since I'm unable to work out how to increment the pagenum during
311    # a regex substitution even with regex extensions on.) Later, when we process each section
312    # to get the pagenum, PDFBox's output for this is pre-processed by having a loopcounter
313    # that increments the pagenum for each subsequent section.
314
315    #$pdfbox_pageheader="\<div style=\"page-break-before:always; page-break-after:always\">";
316    my $loopcounter = 0; # used later on!
317    $text =~ s@\<div style=\"page-break-before:always; page-break-after:always\">@<a name=$loopcounter></a><div style=\"page-break-before:always; page-break-after:always\">@g;
318
319
320    # Calculate number of pages based on <a ...> tags (we have a <a name=1> etc
321    # for each page).  Metadata based on this calculation not set until process()
322    #
323    # Note: this is done even if we are not breaking the document into pages as it might
324    # be useful to give an indication of document length in browser through setting
325    # num_pages as metadata.
326    # Clean html from low and hight surrogates D800–DFFF
327    $text =~ s@[\N{U+D800}-\N{U+DFFF}]@\ @g;
328    my @pages = ($text =~ m/\<[Aa] name=\"?\w+\"?>/ig); #<div style=\"?page-break-before:always; page-break-after:always\"?>
329    my $num_pages = scalar(@pages);
330    $self->{'num_pages'} = $num_pages;
331
332    if ($self->{'use_sections'}
333    && $self->{'converted_to'} eq "HTML") {
334
335    print $outhandle "PDFPlugin: Calculating sections...\n";
336
337    # we have "<a name=1></a>" etc for each page
338    # it may be <A name=
339    my @sections = split('<[Aa] name=', $text);
340
341    my $top_section = "";
342
343    if (scalar (@sections) == 1) { #only one section - no split!
344        print $outhandle "PDFPlugin: warning - no sections found\n";
345    } else {
346        $top_section .= shift @sections; # keep HTML header etc as top_section
347    }
348
349    # handle first section specially for title? Or all use first 100...
350   
351    my $title = $sections[0];
352    $title =~ s/^\"?\w+\"?>//; # specific for pdftohtml...
353    $title =~ s/<\/([^>]+)><\1>//g; # (eg) </b><b> - no space
354    $title =~ s/<[^>]*>/ /g;
355    $title =~ s/(?:&nbsp;|\xc2\xa0)/ /g; # utf-8 for nbsp...
356    $title =~ s/^\s+//s;
357    $title =~ s/\s+$//;
358    $title =~ s/\s+/ /gs;
359    $title =~ s/^$self->{'title_sub'}// if ($self->{'title_sub'});
360    $title =~ s/^\s+//s; # in case title_sub introduced any...
361    $title = substr ($title, 0, 100);
362    $title =~ s/\s\S*$/.../;
363
364
365    if (scalar (@sections) == 1) { # no sections found
366        $top_section .= $sections[0];
367        @sections=();
368    } else {
369        $top_section .= "<!--<Section>\n<Metadata name=\"Title\">$title</Metadata>\n-->\n <!--</Section>-->\n";
370    }
371
372    # add metadata per section...
373    foreach my $section (@sections) {
374        # section names are not always just digits, may be like "outline"
375        $section =~ s@^\"?(\w+)\"?></a>@@; # leftover from split expression...
376
377        $title = $1; # Greenstone does magic if sections are titled digits
378
379        # A title of pagenum=0 means use_sections is being applied on output from PDFBox,
380        # which didn't originally have a <a name=incremented pagenumber></a> to split each page.
381        # Our Perl code then prefixed <a name=0></a> to it. Now need to increment the pagenum here:
382        if($loopcounter > 0 || ($title eq 0 && $loopcounter == 0)) { # implies use_sections with PDFBox
383        $title = ++$loopcounter;
384        }
385
386        if (! defined($title) ) {
387        print STDERR "no title: $section\n";
388        $title = " "; # get rid of the undefined warning in next line
389        }
390        my $newsection = "<!-- from PDFPlugin -->\n<!-- <Section>\n";
391        $newsection .= "<Metadata name=\"Title\">" . $title
392        . "</Metadata>\n--><br />\n";
393        $newsection .= $section;
394        $newsection .= "<!--</Section>-->\n";
395        $section = $newsection;
396    }
397
398    $text=join('', ($top_section, @sections));
399    }
400
401    if ($self->{'use_sections'}
402    && $self->{'converted_to'} eq "text") {
403    print STDERR "**** When converting PDF to text, cannot apply use_sections\n";
404    }
405
406
407    # The following should no longer be needed, now that strings
408    # read in are Unicode aware (in the Perl sense) rather than
409    # raw binary strings that just happen to be UTF-8 compliant
410
411    # turn any high bytes that aren't valid utf-8 into utf-8.
412##    unicode::ensure_utf8(\$text);
413
414    # Write it out again!
415    $self->utf8_write_file (\$text, $conv_filename);
416}
417
418
419# do plugin specific processing of doc_obj for HTML type
420sub process {
421    my $self = shift (@_);
422    my ($pluginfo, $base_dir, $file, $metadata, $doc_obj, $gli) = @_;
423
424    my $result = $self->process_type($base_dir,$file,$doc_obj);
425
426    # fix up the extracted date metadata to be in Greenstone date format,
427    # and fix the capitalisation of 'date'
428    my $cursection = $doc_obj->get_top_section();
429    foreach my $datemeta (@{$doc_obj->get_metadata($cursection, "date")}) {
430    $doc_obj->delete_metadata($cursection, "date", $datemeta);
431
432    # We're just interested in the date bit, not the time
433    # some pdf creators (eg "Acrobat 5.0 Scan Plug-in for Windows")
434    # set a /CreationDate, and set /ModDate to 000000000. pdftohtml
435    # extracts the ModDate, so it is 0...
436    $datemeta =~ /(\d+)-(\d+)-(\d+)/;
437    my ($year, $month, $day) = ($1,$2,$3);
438    if (defined($year) && defined($month) && defined($day)) {
439        if ($year == 0) {next}
440        if ($year < 100) {$year += 1900} # just to be safe
441        if ($month =~ /^\d$/) {$month="0$month"} # single digit
442        if ($day =~ /^\d$/) {$day="0$day"} # single digit
443        my $date="$year$month$day";
444        $doc_obj->add_utf8_metadata($cursection, "Date", $date);
445    }
446    }
447
448    $doc_obj->add_utf8_metadata($cursection, "NumPages", $self->{'num_pages'}) if defined $self->{'num_pages'};
449   
450    if ($self->{'use_sections'} && $self->{'converted_to'} eq "HTML") {
451    # For gs2 we explicitly make it a paged document, cos greenstone won't get it
452    # right if any section has an empty title, or one with letters in it
453    if (&util::is_gs3()) {
454        # but for gs3, paged docs currently use image slider which is ugly if there are no images
455        $doc_obj->set_utf8_metadata_element ($cursection, "gsdlthistype", "Hierarchy");
456    } else {
457        $doc_obj->set_utf8_metadata_element ($cursection, "gsdlthistype", "Paged");
458    }
459    }
460
461    return $result;
462}
463
4641;
Note: See TracBrowser for help on using the browser.