source: main/trunk/greenstone2/perllib/plugins/PDFv2Plugin.pm@ 32287

Last change on this file since 32287 was 32287, checked in by ak19, 3 years ago

Cleaning up unused strings, some debug statements and recently commented out code.

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