root/main/trunk/greenstone2/perllib/plugins/PDFv2Plugin.pm @ 32285

Revision 32285, 33.0 KB (checked in by ak19, 16 months ago)

Fix to sectionalising xpdftools' produced paged_pretty_html: Dr Bainbridge explained that when the total num of pages < 10, we still wanted individual page headings, so GS' section-level search behaviour would work for all PDF docs processed with the sectionalised paged_pretty_html mode.

Line 
1###########################################################################
2#
3# PDFv2Plugin.pm -- pdf plugin that uses xpdftools or, if switched on,
4# pdfbox, to process PDFs.
5# A component of the Greenstone digital library software
6# from the New Zealand Digital Library Project at the
7# University of Waikato, New Zealand.
8#
9# Copyright (C) 1999-2001 New Zealand Digital Library Project
10#
11# This program is free software; you can redistribute it and/or modify
12# it under the terms of the GNU General Public License as published by
13# the Free Software Foundation; either version 2 of the License, or
14# (at your option) any later version.
15#
16# This program is distributed in the hope that it will be useful,
17# but WITHOUT ANY WARRANTY; without even the implied warranty of
18# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19# GNU General Public License for more details.
20#
21# You should have received a copy of the GNU General Public License
22# along with this program; if not, write to the Free Software
23# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
24#
25###########################################################################
26package PDFv2Plugin;
27
28use strict;
29no strict 'refs'; # so we can use a var for filehandles (e.g. STDERR)
30no strict 'subs'; # allow filehandles to be variables and viceversa
31
32use ReadTextFile;
33use unicode;
34use Mojo::DOM; # for HTML parsing
35
36use AutoLoadConverters;
37use ConvertBinaryFile;
38
39@PDFv2Plugin::ISA = ('ConvertBinaryFile', 'AutoLoadConverters', 'ReadTextFile');
40
41
42my $convert_to_list =
43    [ { 'name' => "auto",
44    'desc' => "{ConvertBinaryFile.convert_to.auto}" },
45      { 'name' => "text", # xpdftools
46    'desc' => "{ConvertBinaryFile.convert_to.text}" },
47      { 'name' => "paged_text", # xpdftools
48    'desc' => "{ConvertBinaryFile.convert_to.paged_text}" },
49     
50      { 'name' => "html", # pdfbox ## TODO: rename this to html_without_imgs
51    'desc' => "{PDFPlugin.convert_to.html}" },
52      { 'name' => "pretty_html", # xpdftools
53    'desc' => "{PDFPlugin.convert_to.pretty_html}" },
54      { 'name' => "paged_pretty_html", # xpdftools
55    'desc' => "{PDFPlugin.convert_to.paged_pretty_html}"},
56
57      #pdfbox
58      { 'name' => "pagedimg_jpg",
59    'desc' => "{ConvertBinaryFile.convert_to.pagedimg_jpg}"},
60      { 'name' => "pagedimg_png",
61    'desc' => "{ConvertBinaryFile.convert_to.pagedimg_png}"},
62     
63      { 'name' => "pagedimgtxt_jpg",
64    'desc' => "{ConvertBinaryFile.convert_to.pagedimgtxt_jpg}"},
65      { 'name' => "pagedimgtxt_png",
66    'desc' => "{ConvertBinaryFile.convert_to.pagedimgtxt_png}"},
67      ];
68
69
70my $arguments =
71    [
72     { 'name' => "convert_to",
73       'desc' => "{ConvertBinaryFile.convert_to}",
74       'type' => "enum",
75       'reqd' => "yes",
76       'list' => $convert_to_list,
77       'deft' => "pretty_html" },   
78     { 'name' => "process_exp",
79       'desc' => "{BaseImporter.process_exp}",
80       'type' => "regexp",
81       'deft' => &get_default_process_exp(),
82       'reqd' => "no" },
83     { 'name' => "block_exp",
84       'desc' => "{CommonUtil.block_exp}",
85       'type' => "regexp",
86       'deft' => &get_default_block_exp() },
87     { 'name' => "metadata_fields",
88       'desc' => "{HTMLPlugin.metadata_fields}",
89       'type' => "string",
90       'deft' => "Title,Author,Subject,Keywords" },
91     { 'name' => "metadata_field_separator",
92    'desc' => "{HTMLPlugin.metadata_field_separator}",
93    'type' => "string",
94    'deft' => "" },
95     { 'name' => "dpi",
96       'desc' => "{PDFv2Plugin.dpi}",
97       'deft' => "96",
98       'type' => "int" }, # 72DPI is xpdf's pdftohtml's default. pdfbox' default is 96DPI in headless mode else detected from the screen resolution, see https://pdfbox.apache.org/2.0/commandline.html#pdftoimage
99#     { 'name' => "use_sections",
100#       'desc' => "{PDFPlugin.use_sections}",
101#       'type' => "flag" },
102#     { 'name' => "description_tags",
103#       'desc' => "{HTMLPlugin.description_tags}",
104#       'type' => "flag" },
105      { 'name' => "use_realistic_book",
106        'desc' => "{PDFPlugin.use_realistic_book}",
107    'type' => "flag"}
108     ];
109
110my $options = { 'name'     => "PDFv2Plugin",
111        'desc'     => "{PDFPlugin.desc}",
112        'abstract' => "no",
113        'inherits' => "yes",
114        'srcreplaceable' => "yes", # Source docs in PDF can be replaced with GS-generated html     
115        'args'     => $arguments };
116
117sub new {
118    my ($class) = shift (@_);
119    my ($pluginlist,$inputargs,$hashArgOptLists) = @_;
120    push(@$pluginlist, $class);
121
122    push(@$inputargs,"-title_sub");
123    push(@$inputargs,'^(Page\s+\d+)?(\s*1\s+)?');
124
125    push(@{$hashArgOptLists->{"ArgList"}},@{$arguments});
126    push(@{$hashArgOptLists->{"OptList"}},$options);
127
128    my $auto_converter_self = new AutoLoadConverters($pluginlist,$inputargs,$hashArgOptLists,["PDFBoxConverter"],1);
129    my $cbf_self = new ConvertBinaryFile($pluginlist, $inputargs, $hashArgOptLists);
130    my $self = BaseImporter::merge_inheritance($auto_converter_self, $cbf_self);
131   
132    if ($self->{'info_only'}) {
133    # don't worry about any options etc
134    return bless $self, $class;
135    }
136   
137    $self = bless $self, $class;
138    $self->{'file_type'} = "PDF";
139
140    # convert_options are passed through to gsConvert.pl by ConvertBinaryFile.pm
141   
142    # the most important option is the tool that's used to do the conversion
143    $self->{'convert_options'} = "-pdf_tool xpdftools"; # default for PDFv2Plugin. If pdfbox_conversion is on, the pdfbpox GS extension sets pdf_tool to pdfbox
144
145    # Setting dpi has meaning for xpdftools pdftohtml (so paged_pretty_html and pretty_html)
146    # and for when pdfbox outputs an image for each page (pagedimg, pagedimgtxt).
147    # dpi has no effect on (paged_)text and html output modes.
148    my $dpi = $self->{"dpi"};
149    $self->{'convert_options'} .= " -pdf_dpi $dpi";
150
151    # PDFv2Plugin now supports PDF to txt conversion on Windows too:
152    # using XPDF Tools (incl pdftotext) on Windows/Linux/Mac
153    if ($self->{'convert_to'} eq "text" && $ENV{'GSDLOS'} =~ /^windows$/i) {
154    &gsprintf::gsprintf(STDERR, "{PDFv2Plugin.win_pdftotext_info}\n");
155    }
156    elsif ($self->{'convert_to'} eq "auto") {
157    # choose pretty_html is the best default option when using xpdftools
158    $self->{'convert_to'} = "pretty_html";
159    }
160    if ($self->{'use_realistic_book'}) {
161    if ($self->{'convert_to'} ne "html") {
162        print STDERR "PDFs will be converted to HTML for realistic book functionality\n";
163        $self->{'convert_to'} = "html";
164    }
165    }
166
167    # if pdfbox_conversion is not on, check convert_to to make sure that xpdftools can
168    # support the selected output format, or fallback on a sensible default
169    # Not all available conversion output options are possible with xpdftools, as some are
170    # only handled by pdfbox. If a format is unavailable with xpdftools, default to pretty_html
171    if (!$self->{"pdfbox_conversion"}) {
172    my $convert_to = $self->{'convert_to'};
173    my $fallback_convert_to = $convert_to;
174    if($convert_to =~ /^html$/) {
175        $fallback_convert_to = "pretty_html";
176    }
177    elsif ($self->{'convert_to'} =~ /^pagedimg/) {
178        $fallback_convert_to = "paged_pretty_html";
179    }
180    elsif ($self->{'convert_to'} =~ /^paged_text$/) {
181        #   print STDERR "@@@ Conversion to " . $self->{'convert_to'} , " with Xpdf Tools is not yet implemented.\n";
182        $fallback_convert_to = "text";
183    }
184
185    if($convert_to =~ /^(html|pagedimg|paged_text)/) {
186        &gsprintf::gsprintf(STDERR, "{PDFv2Plugin.conversion_needs_pdfbox}\n", ($self->{'convert_to'}, $fallback_convert_to));
187        $self->{'convert_to'} = $fallback_convert_to;
188    }
189    }
190   
191    # set convert_to_plugin and convert_to_ext
192    $self->set_standard_convert_settings();
193
194    my $secondary_plugin_name = $self->{'convert_to_plugin'};
195    my $secondary_plugin_options = $self->{'secondary_plugin_options'};
196
197    if (!defined $secondary_plugin_options->{$secondary_plugin_name}) {
198    $secondary_plugin_options->{$secondary_plugin_name} = [];
199    }
200    my $specific_options = $secondary_plugin_options->{$secondary_plugin_name};
201
202    # following title_sub removes "Page 1" added by pdftohtml, and a leading
203    # "1", which is often the page number at the top of the page. Bad Luck
204    # if your document title actually starts with "1 " - is there a better way?
205    push(@$specific_options , "-title_sub", '^(Page\s+\d+)?(\s*1\s+)?');
206    my $associate_tail_re = $self->{'associate_tail_re'};
207    if ((defined $associate_tail_re) && ($associate_tail_re ne "")) {
208    push(@$specific_options, "-associate_tail_re", $associate_tail_re);
209    }
210    push(@$specific_options, "-file_rename_method", "none");
211   
212    if ($secondary_plugin_name eq "HTMLPlugin") {
213    # pdftohtml always produces utf8 - What about pdfbox???
214    # push(@$specific_options, "-input_encoding", "utf8");
215    push(@$specific_options, "-extract_language") if $self->{'extract_language'};
216    push(@$specific_options, "-processing_tmp_files");
217    # Instruct HTMLPlug (when eventually accessed through read_into_doc_obj)
218    # to extract these metadata fields from the HEAD META fields
219    if (defined $self->{'metadata_fields'} && $self->{'metadata_fields'} =~ /\S/) {
220        push(@$specific_options,"-metadata_fields",$self->{'metadata_fields'});
221    } else {
222        push(@$specific_options,"-metadata_fields","Title,GENERATOR,date,author<Creator>");
223    }
224    if (defined $self->{'metadata_field_separator'} && $self->{'metadata_field_separator'} =~ /\S/) {
225        push(@$specific_options,"-metadata_field_separator",$self->{'metadata_field_separator'});
226    }
227    if ($self->{'use_sections'} || $self->{'description_tags'}) {
228        $self->{'description_tags'} = 1;
229        push(@$specific_options, "-description_tags");
230    }
231    if ($self->{'use_realistic_book'}) {
232        push(@$specific_options, "-use_realistic_book");
233    }
234    if($self->{'convert_to'} eq "paged_pretty_html") { # for paged pretty html, the default should be to sectionalise
235        # the single superpage, the one containing divs representing individual pages as sections, on headings
236        push(@$specific_options, "sectionalise_using_h_tags");
237    }
238    }
239    elsif ($secondary_plugin_name eq "PagedImagePlugin") {
240    push(@$specific_options, "-screenviewsize", "1000");
241    push(@$specific_options, "-enable_cache");
242    push(@$specific_options, "-processing_tmp_files");
243    }
244
245    $self = bless $self, $class;
246    $self->load_secondary_plugins($class,$secondary_plugin_options,$hashArgOptLists);
247    return $self;
248}
249
250sub get_default_process_exp {
251    my $self = shift (@_);
252
253    return q^(?i)\.pdf$^;
254}
255
256# so we don't inherit HTMLPlug's block exp...
257sub get_default_block_exp {
258    return "";
259}
260
261sub init {
262    my $self = shift (@_);
263
264    # ConvertBinaryFile init
265    $self->SUPER::init(@_);
266    $self->AutoLoadConverters::init(@_);
267
268}
269
270sub begin {
271    my $self = shift (@_);
272
273    $self->AutoLoadConverters::begin(@_);
274    $self->SUPER::begin(@_);
275
276}
277
278sub deinit {
279    my $self = shift (@_);
280   
281    $self->AutoLoadConverters::deinit(@_);
282    $self->SUPER::deinit(@_);
283
284}
285 
286# By setting hashing to be on ga xml this ensures that two
287# PDF files that are identical except for the metadata
288# to hash to different values. Without this, when each PDF
289# file is converted to HTML there is a chance that they
290# will both be *identical* if the conversion utility does
291# not embed the metadata in the generated HTML. This is
292# certainly the case when PDFBOX is being used.
293
294# This change makes this convert to based plugin more
295# consistent with the original vision that the same document
296# with different metadata should
297# be seen as different.
298
299sub get_oid_hash_type {
300    my $self = shift (@_);
301    return "hash_on_ga_xml";
302}
303 
304 
305sub tmp_area_convert_file {
306
307    my $self = shift (@_);
308   
309    if($self->{'convert_to'} =~ m/pretty_html$/) { # if outputting paged_pretty_html or pretty_html:
310    # only xpdftools can output pretty_html regardless of whether pdfbox_conversion is switched on
311    print STDERR "@@@@ PDFBox_conversion is switched on, but pretty_html variants are generated by xpdftools.\n";
312    return $self->ConvertBinaryFile::tmp_area_convert_file(@_);
313    }
314    # else, output format uses pdfbox:
315    return $self->AutoLoadConverters::tmp_area_convert_file(@_);
316
317}
318
319# Overriding to do some extra handling for pretty_html/paged_pretty_html output mode
320sub run_conversion_command {
321    my $self = shift (@_);
322    my ($tmp_dirname, $tmp_inputPDFname, $utf8_tailname, $lc_suffix, $tailname, $suffix) = @_;   
323
324    if($self->{'convert_to'} !~ m/pretty_html$/) {
325    return $self->ConvertBinaryFile::run_conversion_command(@_);
326    }
327
328    # else, paged_pretty_html or pretty_html
329
330    # if output mode is (paged_)pretty_html, we use Xpdf tools' pdftohtml and tell it
331    # to create a subdir called "pages" in the tmp area to puts its products
332    # in there. (Xpdf's pdftohtml needs to be passed a *non-existent* directory
333    # parameter, the "pages" subdir). If Xpdf's pdftohtml has successfully run,
334    # the intermediary output file tmp/<random-num>/pages/index.html should
335    # exist (besides other output products there)
336
337    # We let ConvertBinaryFile proceed normally, but the return value should reflect
338    # that on success it should expect the intermediary product tmpdir/pages/index.html
339    # (which is the product of xpdftohtml conversion).
340    my $output_filename = $self->ConvertBinaryFile::run_conversion_command(@_);
341    $output_filename = &FileUtils::filenameConcatenate($tmp_dirname, "pages", "index.html");
342
343    # However, when convert_post_process() is done, it should have output the final
344    # product of the (paged_)pretty_html conversion: an html file of the same name and in the
345    # same tmp location as the input PDF file.
346
347    my ($name_prefix, $output_dir, $ext)
348    = &File::Basename::fileparse($tmp_inputPDFname, "\\.[^\\.]+\$");
349    $self->{'conv_filename_after_post_process'} = &FileUtils::filenameConcatenate($output_dir, $name_prefix.".html");
350#    print STDERR "@@@@@ final paged html file will be: " . $self->{'conv_filename_after_post_process'} . "\n";
351
352    return $output_filename;
353}
354
355sub convert_post_process
356{
357    my $self = shift (@_);
358    my ($conv_filename) = @_;
359
360    my $outhandle=$self->{'outhandle'};
361
362    if($self->{'convert_to'} =~ /pretty_html/) { # (paged_)pretty_html
363    # special post-processing for (paged_)pretty_html mode, as HTML pages generated
364    # by xpdf's pdftohtml need to be massaged into the form we want
365    $self->xpdftohtml_convert_post_process($conv_filename);
366    }
367    else { # use PDFPlugin's usual post processing
368    $self->default_convert_post_process($conv_filename);
369    }
370}
371
372# Called after gsConvert.pl has been run to convert a PDF to (paged_)pretty_html
373# using Xpdftools' pdftohtml
374# This method will do some cleanup of the HTML files produced after XPDF has produced
375# an HTML doc for each PDF page: it first gets rid of the default index.html.
376# Instead, it constructs a single html page containing each original HTML page
377# <body> nested as divs instead, with simple section information inserted at the top
378# of each 'page' <div> and some further styling customisation. This HTML manipulation
379# is to be done with the Mojo::DOM perl package.
380# Note that since xpdf's pdftohtml would have failed if the output dir already
381# existed and for simpler naming, the output files are created in a new "pages"
382# subdirectory of the tmp location parent of $conv_filename instead
383sub xpdftohtml_convert_post_process
384{
385    my $self = shift (@_);
386    my ($pages_index_html) = @_; # = tmp/<rand>/pages/index.html for (paged_)pretty_html output mode
387    my $output_filename = $self->{'conv_filename_after_post_process'};
388
389    # Read in all the html files in tmp's "pages" subdir, except for index.html.
390    # and use it to create a new html file called $self->{'conv_filename_after_post_process'}
391    # which will consist of a slightly modified version of
392    # each of the other html files concatenated together.
393
394    my $outhandle=$self->{'outhandle'};
395
396    my ($tailname, $pages_subdir, $suffix)
397    = &File::Basename::fileparse($pages_index_html, "\\.[^\\.]+\$");
398
399    # Code from util::create_itemfile()
400    # Read in all the files
401    opendir(DIR, $pages_subdir) || die "can't opendir $pages_subdir: $!";
402    my @page_files = grep {-f "$pages_subdir/$_"} readdir(DIR);
403    closedir DIR;
404    # Sort files in the directory by page_num
405    # files are named index.html, page1.html, page2.html, ..., pagen.html
406    sub page_number {
407    my ($dir) = @_;
408    my ($pagenum) =($dir =~ m/^page(\d+)\.html?$/i);
409    $pagenum = 0 unless defined $pagenum; # index.html will be given pagenum=0
410    return $pagenum;
411    }
412    # sort the files in the directory in the order of page_num rather than lexically.
413    @page_files = sort { page_number($a) <=> page_number($b) } @page_files;
414
415    #my $num_html_pages = (scalar(@page_files) - 1)/2; # skip index file.
416              # For every html file there's an img file, so halve the total num.
417              # What about other file types that may potentially be there too???
418    my $num_html_pages = 0;
419    foreach my $pagefile (@page_files) {
420    $num_html_pages++ if $pagefile =~ m/\.html?$/ && $pagefile !~ /^index\.html?/i;
421    }
422
423    # Prepare to create our new html page that will contain all the individual
424    # htmls generated by xpdf's pdftohtml in sequence.
425    # First write the opening html tags out to the output file. These are the
426    # same tags and their contents, including <meta>, as is generated by
427    # Xpdf's pdftohtml for each of its individual html pages.
428    my $start_text = "<html>\n<head>\n";
429    my ($output_tailname, $tmp_subdir, $html_suffix)
430    = &File::Basename::fileparse($output_filename, "\\.[^\\.]+\$");
431    $start_text .= "<title>$output_tailname</title>\n";
432    $start_text .= "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n";
433    $start_text .= "</head>\n<body>\n\n";
434   
435    if($self->{'convert_to'} =~ /paged_pretty_html/) { # then add the <h>tags for sectionalising
436    $start_text .= "<h1>$output_tailname</h1>\n\n";
437    }
438
439    #handle content encodings the same way that default_convert_post_process does
440    # $self->utf8_write_file ($start_text, $conv_filename); # will close file after write   
441    # Don't want to build a giant string in memory of all the pages concatenated
442    # and then write it out in one go. Instead, build up the final single page
443    # by writing each modified (paged_)pretty_html file out to it as this is processed.
444    # Copying file open/close code from CommonUtil::utf8_write_file()
445    if (!open (OUTFILE, ">:utf8", $output_filename)) {
446    gsprintf(STDERR, "PDFv2Plugin::xpdftohtml_convert_post_process {CommonUtil.could_not_open_for_writing} ($!)\n", $output_filename);
447    die "\n";
448    }
449    print OUTFILE $start_text;
450
451    # Get the contents of each individual HTML page generated by Xpdf, after first
452    # modifying each, and write each out into our single all-encompassing html
453    foreach my $pagefile (@page_files) {
454    if ($pagefile =~ m/\.html?$/ && $pagefile !~ /^index\.html?/i) {
455        my $page_num = page_number($pagefile);   
456        # get full path to pagefile
457        $pagefile = &FileUtils::filenameConcatenate($pages_subdir, $pagefile);
458#       print STDERR "@@@ About to process html file $pagefile (num $page_num)\n";
459        my $modified_page_contents = $self->_process_pretty_html_page($pagefile, $page_num, $num_html_pages);
460        print OUTFILE "$modified_page_contents\n\n";
461    }
462    }
463
464    # we've now created a single HTML file by concatenating (a modified version)
465    # of each paged html file
466    print OUTFILE "</body>\n</html>\n"; # write out closing tags
467    close OUTFILE; # done
468
469    # Get rid of all the htm(l) files incl index.html in the associated "pages"
470    # subdir, since we've now processed them all into a single html file
471    # one folder level up and we don't want HTMLPlugin to process all of them next.
472    &FileUtils::removeFilesFiltered($pages_subdir, "\.html?\$"); #  no specific whitelist, but blacklist htm(l)
473
474    # now the tmp area should contain a single html file contain all the html pages'
475    # contents in sequence, and a "pages" subdir containing the screenshot images
476    # of each page.   
477    # HTMLPlugin will process these further in the plugin pipeline
478}
479
480# For whatever reason, most html <tags> don't get printed out in GLI
481# So when debugging, use this function to print them out as [tags] instead.
482sub _debug_print_html
483{
484    my $self = shift (@_);
485    my ($string_or_dom) = @_;
486
487    # can't seem to determine type of string with ref/reftype
488    # https://stackoverflow.com/questions/1731333/how-do-i-tell-what-type-of-value-is-in-a-perl-variable
489    # Not needed, as $dom objects seem to get correctly stringified in string contexts
490    # $dom.to_string/$dom.stringify seem to get called, no need to call them
491    # https://stackoverflow.com/questions/5214543/what-is-stringification-in-perl
492    my $escapedTxt = $string_or_dom;
493    $escapedTxt =~ s@\<@[@sg;
494    $escapedTxt =~ s@\>@]@sg;
495
496    print STDERR "#### $escapedTxt\n";
497}
498
499# Helper function for (paged_)pretty_html
500# to read in each page of pretty_html generated by Xpdf's pdftohtml
501# then modify the html suitably using the HTML parsing functions offered by
502# Mojo::DOM, then return the modified HTML content as a string.
503# For paged_pretty_html, some additional modification is done to sectionalise the final html
504# See https://mojolicious.org/perldoc/Mojo/DOM
505sub _process_pretty_html_page
506{
507    my $self = shift (@_);
508    my ($pagefile, $page_num, $num_html_pages) = @_;
509
510    my $text = "";
511
512    # handling content encoding the same way default_convert_post_process does
513    $self->read_file ($pagefile, "utf8", "", \$text);
514
515    my $dom = Mojo::DOM->new($text);
516
517#    $self->_debug_print_html($dom);
518
519    # there's a <style> element on the <html>, we need to shift it into the <div>
520    # tag that we'll be creating. We'll first slightly modify the <style> element
521    # store the first style element, which is the only one and in the <body>
522    # we'll later insert it as child of an all-encompassing div that we'll create
523    my $page_style_tag_str = $dom->at('html')->at('style')->to_string;
524    # In the style tag, convert id style references to class style references
525    my $css_class = ".p".$page_num."f";
526    $page_style_tag_str =~ s@\#f@$css_class@sg;
527    my $style_element = Mojo::DOM->new($page_style_tag_str)->at('style'); # modified   
528#$self->_debug_print_html($style_element);
529
530    # need to know the image's height to set the height of the surrounding
531    # div that's to replace this page's <body>:
532    my $img_height = $dom->find('img')->[0]{height};
533
534    # 2. Adjust the img#background src attribute to point to the pages subdir for imgs
535    # 3. Set that img tag's class=background, and change its id to background+$page_num
536    my $bg_img_tag=$dom->find('img#background')->[0];
537    my $img_src_str = $bg_img_tag->{src};
538    $img_src_str = "pages/$img_src_str";
539    $bg_img_tag->attr(src => $img_src_str); # reset
540#$self->_debug_print_html($bg_img_tag);
541    # set both class and modified id attributes in one step:
542    $bg_img_tag->attr({class => "background", id => "background".$page_num});
543#$self->_debug_print_html($bg_img_tag);
544
545    # get all the <span> nested inside <div class="txt"> elements and
546    # 1. set their class attr to be "p + page_num + id-of-the-span",
547    # 2. then delete the id, because the span ids have been reused when element
548    # ids ought to be unique. Which is why we set the modified ids to be the
549    # value of the class attribute instead
550    $dom->find('div.txt span')->each(sub {
551    $_->attr(class => "p". $page_num. $_->{id});
552    delete $_->{id};
553                     }); # both changes done in one find() operation
554#$self->_debug_print_html($dom->find('div.txt span')->last);
555
556    # Finally can create our new dom, starting with a div tag for the current page
557    # Must be: <div id="$page_num" style="position:relative; height:$img_height;"/>
558#    my $new_dom = Mojo::DOM->new_tag('div', id => "page".$page_num, style => "position: relative; height: ".$img_height."px;" )
559    my $new_dom = Mojo::DOM->new_tag('div', style => "position: relative; height: ".$img_height."px;" );
560#$self->_debug_print_html($new_dom);
561    $new_dom->at('div')->append_content($style_element)->root;
562
563
564#$self->_debug_print_html($new_dom);
565    # Copy across all the old html's body tag's child nodes into the new dom's new div tag
566    $dom->at('body')->child_nodes->each(sub { $new_dom->at('div')->append_content($_)}); #$_->to_string
567#$self->_debug_print_html($new_dom);
568
569    # build up the outer div
570    my $inner_div_str = $new_dom->to_string;
571    my $page_div = "<div id=\"page".$page_num."\">\n";
572
573    # If paged_pretty_html, then add <h>tags for sectionalising
574    if($self->{'convert_to'} =~ /paged_pretty_html/) {
575   
576    # Append a page range bucket heading if applicable: if we have more than 10 pages
577    # to display in the current bucket AND we're on the first page of each bucket of 10 pages.
578    # Dr Bainbridge thinks for now we need only consider PDFs where the
579    # total number of pages < 1000 and create buckets of size 10 (e.g. 1-10, ... 51-60, ...)
580    # If number of remaining pages >= 10, then create new bucket heading
581    # e.g. "Pages 30-40"
582    if(($page_num % 10) == 1 && ($num_html_pages - $page_num) > 10) {
583        # Double-digit page numbers that start with 2
584        # i.e. 21 to 29 (and 30) should be in 21 to 30 range
585        my $start_range = $page_num - ($page_num % 10) + 1;
586        my $end_range = $page_num + 10 - ($page_num % 10);
587        $page_div .= "<h2 style=\"font-size:1em;font-weight:normal;\">Pages ".$start_range . "-" . $end_range."</h2>\n";
588    }
589
590    # Every page is now a section too, not just buckets.
591    # Whether we're starting a new bucket or not, add a simpler heading: just the pagenumber, "Page #"
592    # However, this should be <H3> when there are buckets and <H2> when there aren't any.
593    if($num_html_pages > 10) {
594        $page_div .= "<h3 style=\"font-size:1em;font-weight:normal;\">Page ".$page_num."</h3>\n";       
595    } else { # PDF has less than 10 pages in total
596        $page_div .= "<h2 style=\"font-size:1em;font-weight:normal;\">Page ".$page_num."</h2>\n";       
597    }
598    }
599
600    $page_div .= $inner_div_str;
601    $page_div .= "\n</div>";
602
603    # Finished processing a single html page of the (paged_)pretty_html output generated by
604    # Xpdf's pdftohtml: finished massaging that single html page into the right form
605    return $page_div;
606}
607
608# This subroutine is called to do the PDFv2Plugin post-processing for all cases
609# except the "pretty_html" or "paged_pretty_html" conversion modes.
610# This is what PDFPlugin always used to do:
611sub default_convert_post_process
612{
613    my $self = shift (@_);
614    my ($conv_filename) = @_;
615    my $outhandle=$self->{'outhandle'};
616
617    #$self->{'input_encoding'} = "utf8"; # TODO: The output is always in utf8 (is it?? it is for html, but what about other types?)
618    #my ($language, $encoding) = $self->textcat_get_language_encoding ($conv_filename);
619
620    # read in file ($text will be in utf8)
621    my $text = "";
622    # encoding will be utf8 for html files - what about other types? will we do this step for them anyway?
623    $self->read_file ($conv_filename, "utf8", "", \$text);
624
625    # To support the use_sections option with PDFBox: Greenstone splits PDFs into pages for
626    # sections. The PDFPlugin code wants each new page to be prefixed with <a name=pagenum></a>,
627    # which it then splits on to generate page-based sections. However, that's not what PDFBox
628    # generates in its HTML output. Fortunately, PDFBox does have its own page-separator: it
629    # embeds each page in an extra div. The div opener is:
630    # <div style=\"page-break-before:always; page-break-after:always\">
631    # The PDFPlugin now looks for this and prefixes <a name=0></a> to each such div. (The
632    # pagenumber is fixed at 0 since I'm unable to work out how to increment the pagenum during
633    # a regex substitution even with regex extensions on.) Later, when we process each section
634    # to get the pagenum, PDFBox's output for this is pre-processed by having a loopcounter
635    # that increments the pagenum for each subsequent section.
636
637    #$pdfbox_pageheader="\<div style=\"page-break-before:always; page-break-after:always\">";
638    my $loopcounter = 0; # used later on!
639    $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;
640
641
642    # Calculate number of pages based on <a ...> tags (we have a <a name=1> etc
643    # for each page).  Metadata based on this calculation not set until process()
644    #
645    # Note: this is done even if we are not breaking the document into pages as it might
646    # be useful to give an indication of document length in browser through setting
647    # num_pages as metadata.
648    # Clean html from low and hight surrogates D800–DFFF
649    $text =~ s@[\N{U+D800}-\N{U+DFFF}]@\ @g;
650    my @pages = ($text =~ m/\<[Aa] name=\"?\w+\"?>/ig); #<div style=\"?page-break-before:always; page-break-after:always\"?>
651    my $num_pages = scalar(@pages);
652    $self->{'num_pages'} = $num_pages;
653
654    if ($self->{'use_sections'}
655    && $self->{'converted_to'} eq "HTML") {
656
657    print $outhandle "PDFv2Plugin: Calculating sections...\n";
658
659    # we have "<a name=1></a>" etc for each page
660    # it may be <A name=
661    my @sections = split('<[Aa] name=', $text);
662
663    my $top_section = "";
664
665    if (scalar (@sections) == 1) { #only one section - no split!
666        print $outhandle "PDFv2Plugin: warning - no sections found\n";
667    } else {
668        $top_section .= shift @sections; # keep HTML header etc as top_section
669    }
670
671    # handle first section specially for title? Or all use first 100...
672   
673    my $title = $sections[0];
674    $title =~ s/^\"?\w+\"?>//; # specific for pdftohtml...
675    $title =~ s/<\/([^>]+)><\1>//g; # (eg) </b><b> - no space
676    $title =~ s/<[^>]*>/ /g;
677    $title =~ s/(?:&nbsp;|\xc2\xa0)/ /g; # utf-8 for nbsp...
678    $title =~ s/^\s+//s;
679    $title =~ s/\s+$//;
680    $title =~ s/\s+/ /gs;
681    $title =~ s/^$self->{'title_sub'}// if ($self->{'title_sub'});
682    $title =~ s/^\s+//s; # in case title_sub introduced any...
683    $title = substr ($title, 0, 100);
684    $title =~ s/\s\S*$/.../;
685
686
687    if (scalar (@sections) == 1) { # no sections found
688        $top_section .= $sections[0];
689        @sections=();
690    } else {
691        $top_section .= "<!--<Section>\n<Metadata name=\"Title\">$title</Metadata>\n-->\n <!--</Section>-->\n";
692    }
693
694    # add metadata per section...
695    foreach my $section (@sections) {
696        # section names are not always just digits, may be like "outline"
697        $section =~ s@^\"?(\w+)\"?></a>@@; # leftover from split expression...
698
699        $title = $1; # Greenstone does magic if sections are titled digits
700
701        # A title of pagenum=0 means use_sections is being applied on output from PDFBox,
702        # which didn't originally have a <a name=incremented pagenumber></a> to split each page.
703        # Our Perl code then prefixed <a name=0></a> to it. Now need to increment the pagenum here:
704        if($loopcounter > 0 || ($title eq 0 && $loopcounter == 0)) { # implies use_sections with PDFBox
705        $title = ++$loopcounter;
706        }
707
708        if (! defined($title) ) {
709        print STDERR "no title: $section\n";
710        $title = " "; # get rid of the undefined warning in next line
711        }
712        my $newsection = "<!-- from PDFv2Plugin -->\n<!-- <Section>\n";
713        $newsection .= "<Metadata name=\"Title\">" . $title
714        . "</Metadata>\n--><br />\n";
715        $newsection .= $section;
716        $newsection .= "<!--</Section>-->\n";
717        $section = $newsection;
718    }
719
720    $text=join('', ($top_section, @sections));
721    }
722
723    if ($self->{'use_sections'}
724    && $self->{'converted_to'} eq "text") {
725    print STDERR "**** When converting PDF to text, cannot apply use_sections\n";
726    }
727
728
729    # The following should no longer be needed, now that strings
730    # read in are Unicode aware (in the Perl sense) rather than
731    # raw binary strings that just happen to be UTF-8 compliant
732
733    # turn any high bytes that aren't valid utf-8 into utf-8.
734##    unicode::ensure_utf8(\$text);
735
736    # Write it out again!
737    $self->utf8_write_file (\$text, $conv_filename);
738}
739
740
741# do plugin specific processing of doc_obj for HTML type
742sub process {
743    my $self = shift (@_);
744    my ($pluginfo, $base_dir, $file, $metadata, $doc_obj, $gli) = @_;
745
746    my $result = $self->process_type($base_dir,$file,$doc_obj);
747
748    # fix up the extracted date metadata to be in Greenstone date format,
749    # and fix the capitalisation of 'date'
750    my $cursection = $doc_obj->get_top_section();
751    foreach my $datemeta (@{$doc_obj->get_metadata($cursection, "date")}) {
752    $doc_obj->delete_metadata($cursection, "date", $datemeta);
753
754    # We're just interested in the date bit, not the time
755    # some pdf creators (eg "Acrobat 5.0 Scan Plug-in for Windows")
756    # set a /CreationDate, and set /ModDate to 000000000. pdftohtml
757    # extracts the ModDate, so it is 0...
758    $datemeta =~ /(\d+)-(\d+)-(\d+)/;
759    my ($year, $month, $day) = ($1,$2,$3);
760    if (defined($year) && defined($month) && defined($day)) {
761        if ($year == 0) {next}
762        if ($year < 100) {$year += 1900} # just to be safe
763        if ($month =~ /^\d$/) {$month="0$month"} # single digit
764        if ($day =~ /^\d$/) {$day="0$day"} # single digit
765        my $date="$year$month$day";
766        $doc_obj->add_utf8_metadata($cursection, "Date", $date);
767    }
768    }
769
770    $doc_obj->add_utf8_metadata($cursection, "NumPages", $self->{'num_pages'}) if defined $self->{'num_pages'};
771   
772    if ($self->{'use_sections'} && $self->{'converted_to'} eq "HTML") {
773    # For gs2 we explicitly make it a paged document, cos greenstone won't get it
774    # right if any section has an empty title, or one with letters in it
775    if (&util::is_gs3()) {
776        # but for gs3, paged docs currently use image slider which is ugly if there are no images
777        $doc_obj->set_utf8_metadata_element ($cursection, "gsdlthistype", "Hierarchy");
778    } else {
779        $doc_obj->set_utf8_metadata_element ($cursection, "gsdlthistype", "Paged");
780    }
781    }
782
783    return $result;
784}
785
7861;
Note: See TracBrowser for help on using the browser.