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

Last change on this file was 36057, checked in by kjdon, 2 years ago

in the whakatohea project, converting the pdfs to paged_pretty_html resulted in unclosed divs in the sections. This is because the <div page=1> was outside the <h2> or <h3> headings. Put these <h> headings on the outside of divs to keep the resulting doc.xml nicer.

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