source: main/trunk/greenstone2/bin/script/gsConvert.pl@ 28166

Last change on this file since 28166 was 28166, checked in by ak19, 11 years ago

Minor improvements to debug msg display

  • Property svn:executable set to *
  • Property svn:keywords set to Author Date Id Revision
File size: 36.4 KB
Line 
1#!/usr/bin/perl -w
2
3###########################################################################
4#
5# gsConvert.pl -- convert documents to HTML or TEXT format
6#
7# A component of the Greenstone digital library software
8# from the New Zealand Digital Library Project at the
9# University of Waikato, New Zealand.
10#
11# Copyright (C) 1999-2002 New Zealand Digital Library Project
12#
13# This program is free software; you can redistribute it and/or modify
14# it under the terms of the GNU General Public License as published by
15# the Free Software Foundation; either version 2 of the License, or
16# (at your option) any later version.
17#
18# This program is distributed in the hope that it will be useful,
19# but WITHOUT ANY WARRANTY; without even the implied warranty of
20# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21# GNU General Public License for more details.
22#
23# You should have received a copy of the GNU General Public License
24# along with this program; if not, write to the Free Software
25# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
26#
27###########################################################################
28
29# gsConvert.pl converts documents in a range of formats to HTML or TEXT
30# by exploiting third-party programs. The sources of these are usually found
31# in the $GSDLHOME/packages directory, and the executables should live in
32# $GSDLHOME/bin/$GSDLOS (which is on the search path).
33#
34# Currently, we can convert the following formats by using external
35# conversion utilities:
36# Microsoft Word (versions 2,6,7 [==95?], 8[==97?], 9[==2000?]), RTF,
37# Adobe PDF, PostScript, MS PowerPoint (95 and 97), and MS Excel (95 and 97).
38#
39# We can try to convert any file to text with a perl implementation of the
40# UNIX strings command.
41#
42# We try to convert Postscript files to text using "gs" which is often on
43# *nix machines. We fall back to performing weak text extraction by using
44# regular expressions.
45
46BEGIN {
47 die "GSDLHOME not set\n" unless defined $ENV{'GSDLHOME'};
48 unshift (@INC, "$ENV{'GSDLHOME'}/perllib");
49}
50
51use strict;
52
53use parsargv;
54use util;
55use FileUtils;
56use Cwd;
57
58# Are we running on WinNT or Win2000 (or later)?
59my $is_winnt_2000=eval {require Win32; return (Win32::IsWinNT()); return 0;};
60if (!defined($is_winnt_2000)) {$is_winnt_2000=0;}
61
62my $use_strings;
63my $pdf_complex;
64my $pdf_nohidden;
65my $pdf_zoom;
66my $pdf_ignore_images;
67my $pdf_allow_images_only;
68my $windows_scripting;
69
70sub print_usage
71{
72 print STDERR "\n";
73 print STDERR "gsConvert.pl: Converts documents in a range of formats to html\n";
74 print STDERR " or text using third-party programs.\n\n";
75 print STDERR " usage: $0 [options] filename\n";
76 print STDERR " options:\n\t-type\tdoc|dot|pdf|ps|ppt|rtf|xls\t(input file type)\n";
77 print STDERR "\t-errlog\t<filename>\t(append err messages)\n";
78 print STDERR "\t-output\tauto|html|text|pagedimg_jpg|pagedimg_gif|pagedimg_png\t(output file type)\n";
79 print STDERR "\t-timeout\t<max cpu seconds>\t(ulimit on unix systems)\n";
80 print STDERR "\t-use_strings\tuse strings to extract text if conversion fails\n";
81 print STDERR "\t-windows_scripting\tuse windows VB script (if available) to convert Microsoft Word and PPT documents\n";
82 print STDERR "\t-pdf_complex\tuse complex output when converting PDF to HTML\n";
83 print STDERR "\t-pdf_nohidden\tDon't attempt to extract hidden text from PDF files\n";
84 print STDERR "\t-pdf_ignore_images\tdon't attempt to extract images when\n";
85 print STDERR "\t\tconverting PDF to HTML\n";
86 print STDERR "\t-pdf_allow_images_only\tallow images only (continue even if no text is present when converting to HTML)\n";
87 print STDERR "\t-pdf_zoom\tfactor by which to zoom PDF (only useful if\n";
88 print STDERR "\t\t-pdf_complex is set\n";
89 exit(1);
90}
91
92my $faillogfile="";
93my $timeout=0;
94my $verbosity=0;
95
96sub main
97{
98 my (@ARGV) = @_;
99 my ($input_type,$output_type,$verbose);
100
101 # Dynamically figure out what the --type option can support, based on whether -windows_scripting
102 # is in use or not
103 my $default_type_re = "(doc|dot|pdf|ps|ppt|rtf|xls)";
104 #my $enhanced_type_re = "(docx?|dot|pdf|ps|pptx?|rtf|xlsx?)";
105 #my $enhanced_type_re = "(docx?|dot|pdf|ps|pptx?|rtf|xlsx?)";
106 # Currently only have VBA for Word and PPT(but no XLS)
107 my $enhanced_type_re = "(docx?|dot|pdf|ps|pptx?|rtf|xls)";
108
109 my $type_re = $default_type_re;
110
111 foreach my $a (@ARGV) {
112 if ($a =~ m/^windows_scripting$/i) {
113 $type_re = $enhanced_type_re;
114 }
115 }
116
117 # read command-line arguments
118 if (!parsargv::parse(\@ARGV,
119 "type/$type_re/", \$input_type,
120 '/errlog/.*/', \$faillogfile,
121 'output/(auto|html|text|pagedimg).*/', \$output_type,
122 'timeout/\d+/0',\$timeout,
123 'verbose/\d+/0', \$verbose,
124 'windows_scripting',\$windows_scripting,
125 'use_strings', \$use_strings,
126 'pdf_complex', \$pdf_complex,
127 'pdf_ignore_images', \$pdf_ignore_images,
128 'pdf_allow_images_only', \$pdf_allow_images_only,
129 'pdf_nohidden', \$pdf_nohidden,
130 'pdf_zoom/\d+/2', \$pdf_zoom
131 ))
132 {
133 print_usage();
134 }
135
136 $verbosity=$verbose if defined $verbose;
137
138 # Make sure the input file exists and can be opened for reading
139 if (scalar(@ARGV!=1)) {
140 print_usage();
141 }
142
143 my $input_filename = $ARGV[0];
144 if (!-r $input_filename) {
145 print STDERR "Error: unable to open $input_filename for reading\n";
146 exit(1);
147 }
148
149 # Deduce filenames
150 my ($tailname,$dirname,$suffix)
151 = File::Basename::fileparse($input_filename, "\\.[^\\.]+\$");
152 my $output_filestem = &FileUtils::filenameConcatenate($dirname, "$tailname");
153
154 if ($input_type eq "")
155 {
156 $input_type = lc (substr($suffix,1,length($suffix)-1));
157 }
158
159 # Change to temporary working directory
160 my $stored_dir = cwd();
161 chdir ($dirname) || die "Unable to change to directory $dirname";
162
163 # Select convert utility
164 if (!defined $input_type) {
165 print STDERR "Error: No filename extension or input type defined\n";
166 exit(1);
167 }
168 elsif ($input_type =~ m/^docx?$/ || $input_type eq "dot") {
169 print &convertDOC($input_filename, $output_filestem, $output_type);
170 print "\n";
171 }
172 elsif ($input_type eq "rtf") {
173 print &convertRTF($input_filename, $output_filestem, $output_type);
174 print "\n";
175 }
176 elsif ($input_type eq "pdf") {
177 print &convertPDF($dirname, $input_filename, $output_filestem, $output_type);
178 print "\n";
179 }
180 elsif ($input_type eq "ps") {
181 print &convertPS($dirname, $input_filename, $output_filestem, $output_type);
182 print "\n";
183 }
184 elsif ($input_type =~ m/pptx?$/) {
185 print &convertPPT($input_filename, $output_filestem, $output_type);
186 print "\n";
187 }
188 elsif ($input_type =~ m/xlsx?$/) {
189 print &convertXLS($input_filename, $output_filestem, $output_type);
190 print "\n";
191 }
192 else {
193 print STDERR "Error: Unable to convert type '$input_type'\n";
194 exit(1);
195 }
196
197 # restore to original working directory
198 chdir ($stored_dir) || die "Unable to return to directory $stored_dir";
199
200}
201
202&main(@ARGV);
203
204
205
206# Document-type conversion functions
207#
208# The following functions attempt to convert documents from their
209# input type to the specified output type. If no output type was
210# given, then they first attempt HTML, and then TEXT.
211#
212# Each returns the output type ("html" or "text") or "fail" if no
213# conversion is possible.
214
215# Convert a Microsoft word document
216
217sub convertDOC {
218 my ($input_filename, $output_filestem, $output_type) = @_;
219
220 # Many .doc files are not in fact word documents!
221 my $realtype = &find_docfile_type($input_filename);
222
223 if ($realtype eq "word6" || $realtype eq "word7"
224 || $realtype eq "word8" || $realtype eq "docx") {
225 return &convertWord678($input_filename, $output_filestem, $output_type);
226 } elsif ($realtype eq "rtf") {
227 return &convertRTF($input_filename, $output_filestem, $output_type);
228 } else {
229 return &convertAnything($input_filename, $output_filestem, $output_type);
230 }
231}
232
233# Convert a Microsoft word 6/7/8 document
234
235sub convertWord678 {
236 my ($input_filename, $output_filestem, $output_type) = @_;
237
238 my $success = 0;
239 if (!$output_type || ($output_type =~ m/html/i)){
240 if ($windows_scripting) {
241 $success = &native_doc_to_html($input_filename, $output_filestem);
242 }
243 else {
244 $success = &doc_to_html($input_filename, $output_filestem);
245 }
246 if ($success) {
247 return "html";
248 }
249 }
250 return &convertAnything($input_filename, $output_filestem, $output_type);
251}
252
253
254# Convert a Rich Text Format (RTF) file
255
256sub convertRTF {
257 my ($input_filename, $output_filestem, $output_type) = @_;
258
259 my $success = 0;
260
261 # Attempt specialised conversion to HTML
262 if (!$output_type || ($output_type =~ m/html/i)) {
263
264 if ($windows_scripting) {
265 $success = &native_doc_to_html($input_filename, $output_filestem);
266 }
267 else {
268 $success = &rtf_to_html($input_filename, $output_filestem);
269 }
270 if ($success) {
271 return "html";
272 }
273 }
274
275# rtf is so ugly that's it's not worth running strings over.
276# One day I'll write some quick'n'dirty regexps to try to extract text - jrm21
277# return &convertAnything($input_filename, $output_filestem, $output_type);
278 return "fail";
279}
280
281
282# Convert an unidentified file
283
284sub convertAnything {
285 my ($input_filename, $output_filestem, $output_type) = @_;
286
287 my $success = 0;
288
289 # Attempt simple conversion to HTML
290 if (!$output_type || ($output_type =~ m/html/i)) {
291 $success = &any_to_html($input_filename, $output_filestem);
292 if ($success) {
293 return "html";
294 }
295 }
296
297 # Convert to text
298 if (!$output_type || ($output_type =~ m/text/i)) {
299 $success = &any_to_text($input_filename, $output_filestem);
300 if ($success) {
301 return "text";
302 }
303 }
304 return "fail";
305}
306
307
308
309# Convert an Adobe PDF document
310
311sub convertPDF {
312 my ($dirname, $input_filename, $output_filestem, $output_type) = @_;
313
314 my $success = 0;
315 $output_type =~ s/.*\-(.*)/$1/i;
316 # Attempt coversion to Image
317 if ($output_type =~ m/jp?g|gif|png/i) {
318 $success = &pdfps_to_img($dirname, $input_filename, $output_filestem, $output_type);
319 if ($success){
320 return "item";
321 }
322 }
323
324 # Attempt conversion to HTML
325 if (!$output_type || ($output_type =~ m/html/i)) {
326 $success = &pdf_to_html($dirname, $input_filename, $output_filestem);
327 if ($success) {
328 return "html";
329 }
330 }
331
332 # Attempt conversion to TEXT
333 if (!$output_type || ($output_type =~ m/text/i)) {
334 $success = &pdf_to_text($dirname, $input_filename, $output_filestem);
335 if ($success) {
336 return "text";
337 }
338 }
339
340 return "fail";
341
342}
343
344
345# Convert an Adobe PostScript document
346
347sub convertPS {
348 my ($dirname,$input_filename, $output_filestem, $output_type) = @_;
349
350 my $success = 0;
351 $output_type =~ s/.*\-(.*)/$1/i;
352 # Attempt coversion to Image
353 if ($output_type =~ m/jp?g|gif|png/i) {
354 $success = &pdfps_to_img($dirname, $input_filename, $output_filestem, $output_type);
355 if ($success){
356 return "item";
357 }
358 }
359
360 # Attempt conversion to TEXT
361 if (!$output_type || ($output_type =~ m/text/i)) {
362 $success = &ps_to_text($input_filename, $output_filestem);
363 if ($success) {
364 return "text";
365 }
366 }
367 return "fail";
368}
369
370
371sub convertPPT {
372 my ($input_filename, $output_filestem, $output_type) = @_;
373 my $success = 0;
374
375 my $ppt_convert_type = "";
376
377 #if (!$output_type || $windows_scripting || ($output_type !~ m/html/i) || ($output_type !~ m/text/i)){
378 if ($windows_scripting && ($output_type !~ m/html/i) && ($output_type !~ m/text/i)){
379 if ($output_type =~ m/gif/i) {
380 $ppt_convert_type = "-g";
381 } elsif ($output_type =~ m/jp?g/i){
382 $ppt_convert_type = "-j";
383 } elsif ($output_type =~ m/png/i){
384 $ppt_convert_type = "-p";
385 }
386 my $vbScript = &FileUtils::filenameConcatenate($ENV{'GSDLHOME'}, "bin",
387 $ENV{'GSDLOS'}, "pptextract");
388 $vbScript = "pptextract" if ($ENV{'GSDLOS'} =~ m/^windows$/i);
389
390 my $cmd = "";
391 if ($timeout) {$cmd = "ulimit -t $timeout;";}
392 # if the converting directory already exists
393 if (-d $output_filestem) {
394 print STDERR "**The conversion directory already exists\n";
395 return "item";
396 } else {
397 $cmd .= "$vbScript $ppt_convert_type \"$input_filename\" \"$output_filestem\"";
398 $cmd .= " 2>\"$output_filestem.err\""
399 if ($ENV{'GSDLOS'} !~ m/^windows$/i || $is_winnt_2000);
400 if (system($cmd) !=0) {
401 print STDERR "Powerpoint VB Scripting convert failed\n";
402 } else {
403 return "item";
404 }
405 }
406 } elsif (!$output_type || ($output_type =~ m/html/i)) {
407 # Attempt conversion to HTML
408 #if (!$output_type || ($output_type =~ m/html/i)) {
409 # formulate the command
410 my $cmd = "";
411 my $full_perl_path = &util::get_perl_exec();
412 $cmd .= "\"$full_perl_path\" -S ppttohtml.pl ";
413 $cmd .= " \"$input_filename\" \"$output_filestem.html\"";
414 $cmd .= " 2>\"$output_filestem.err\""
415 if ($ENV{'GSDLOS'} !~ m/^windows$/i || $is_winnt_2000);
416
417 # execute the command
418 $!=0;
419 if (system($cmd)!=0)
420 {
421 print STDERR "Powerpoint 95/97 converter failed $!\n";
422 } else {
423 return "html";
424 }
425 }
426
427 $success = &any_to_text($input_filename, $output_filestem);
428 if ($success) {
429 return "text";
430 }
431
432 return "fail";
433}
434
435
436sub convertXLS {
437 my ($input_filename, $output_filestem, $output_type) = @_;
438
439 my $success = 0;
440
441 # Attempt conversion to HTML
442 if (!$output_type || ($output_type =~ m/html/i)) {
443 # formulate the command
444 my $cmd = "";
445 my $full_perl_path = &util::get_perl_exec();
446 $cmd .= "\"$full_perl_path\" -S xlstohtml.pl ";
447 $cmd .= " \"$input_filename\" \"$output_filestem.html\"";
448 $cmd .= " 2>\"$output_filestem.err\""
449 if ($ENV{'GSDLOS'} !~ m/^windows$/i || $is_winnt_2000);
450
451
452 # execute the command
453 $!=0;
454 if (system($cmd)!=0)
455 {
456 print STDERR "Excel 95/97 converter failed $!\n";
457 } else {
458 return "html";
459 }
460 }
461
462 $success = &any_to_text($input_filename, $output_filestem);
463 if ($success) {
464 return "text";
465 }
466
467 return "fail";
468}
469
470
471
472# Find the real type of a .doc file
473#
474# We seem to have a lot of files with a .doc extension that are .rtf
475# files or Word 5 files. This function attempts to tell the difference.
476sub find_docfile_type {
477 my ($input_filename) = @_;
478
479 if (($windows_scripting) && ($input_filename =~ m/\.docx$/)) {
480 return "docx";
481 }
482
483 open(CHK, "<$input_filename");
484 binmode(CHK);
485 my $line = "";
486 my $first = 1;
487
488 while (<CHK>) {
489
490 $line = $_;
491
492 if ($first) {
493 # check to see if this is an rtf file
494 if ($line =~ m/^\{\\rtf/) {
495 close(CHK);
496 return "rtf";
497 }
498 $first = 0;
499 }
500
501 # is this is a word 6/7/8 document?
502 if ($line =~ m/Word\.Document\.([678])/) {
503 close(CHK);
504
505 return "word$1";
506 }
507
508 }
509
510 return "unknown";
511}
512
513
514# Specific type-to-type conversions
515#
516# Each of the following functions attempts to convert a document from
517# a specific format to another. If they succeed they return 1 and leave
518# the output document(s) in the appropriate place; if they fail they
519# return 0 and delete any working files.
520
521
522# Attempt to convert a word document to html with the wv program
523sub doc_to_html {
524 my ($input_filename, $output_filestem) = @_;
525
526 my $wvware_status = 0;
527
528 # need to ensure that the path to perl is quoted (in case there's spaces in it)
529 my $launch_cmd = "\"".&util::get_perl_exec()."\" -S wvware.pl \"$input_filename\" \"$output_filestem\" \"$faillogfile\" $verbosity $timeout";
530
531# print STDERR "***** wvware launch cmd = $launch_cmd\n";
532
533 $wvware_status = system($launch_cmd)/256;
534 return $wvware_status;
535}
536
537# Attempt to convert a word document to html with the word2html scripting program
538sub native_doc_to_html {
539 my ($input_filename, $output_filestem) = @_;
540
541 # build up the path to the doc-to-html conversion tool we're going to use
542 my $vbScript = &FileUtils::filenameConcatenate($ENV{'GSDLHOME'}, "bin", $ENV{'GSDLOS'});
543
544 if ($ENV{'GSDLOS'} =~ m/^windows$/i) {
545 # if windows scripting with docx input, use new VBscript to get the local Word install (if
546 # any) to do the conversion, since docX can't be processed by word2html's windows_scripting
547
548 if($input_filename =~ m/docx$/i) { # need to use full path to docx2html script,
549 # else script launch fails when there are error msgs
550 $vbScript = &FileUtils::filenameConcatenate($vbScript, "docx2html.vbs");
551 $vbScript = "CScript //Nologo \"$vbScript\""; # launche with CScript for error output in STDERR
552 # //Nologo flag avoids Microsoft's opening/logo msgs
553 print STDERR "About to use windows scripting to process docx file $input_filename.\n";
554 print STDERR " This may take some time. Please wait...\n";
555 }
556 else { # old doc versions. use the usual VB executable word2html for the
557 # conversion. Doesn't need full path, since bin\windows is on PATH
558 $vbScript = "word2html"; #$vbScript = "\"".&FileUtils::filenameConcatenate($vbScript, "word2html")."\"";
559 }
560 }
561 else { # not windows
562 $vbScript = "\"".&FileUtils::filenameConcatenate($vbScript, "word2html")."\"";
563 }
564
565 if (-e "$output_filestem.html") {
566 print STDERR " The conversion file:\n";
567 print STDERR " $output_filestem.html\n";
568 print STDERR " ... already exists. Skipping\n";
569 return 1;
570 }
571
572 my $cmd = "";
573 if ($timeout) {$cmd = "ulimit -t $timeout;";}
574 #$cmd .= "$vbScript \"$input_filename\" \"$output_filestem.html\"";
575 #$cmd .= "$vbScript $input_filename $output_filestem.html";
576 $cmd .= "$vbScript \"$input_filename\" \"$output_filestem.html\"";
577
578 # redirecting STDERR
579
580 $cmd .= " 2> \"$output_filestem.err\""
581 if ($ENV {'GSDLOS'} !~ m/^windows$/i || $is_winnt_2000);
582 #print STDERR "@@@@@@@@@ cmd=$cmd\n";
583
584 # execute the command
585 $!=0;
586 if (system($cmd)!=0)
587 {
588 print STDERR "Error executing $vbScript converter:$!\n";
589 if (-s "$output_filestem.err") {
590 open (ERRFILE, "<$output_filestem.err");
591
592 my $write_to_fail_log=0;
593 if ($faillogfile ne "" && defined(open(FAILLOG,">>$faillogfile")))
594 {$write_to_fail_log=1;}
595
596 my $line;
597 while ($line=<ERRFILE>) {
598 if ($line =~ m/\w/) {
599 print STDERR "$line";
600 print FAILLOG "$line" if ($write_to_fail_log);
601 }
602 if ($line !~ m/startup error/) {next;}
603 print STDERR " (given an invalid .DOC file?)\n";
604 print FAILLOG " (given an invalid .DOC file?)\n"
605 if ($write_to_fail_log);
606
607 } # while ERRFILE
608 close FAILLOG if ($write_to_fail_log);
609 }
610 return 0; # we can try any_to_text
611 }
612
613 # Was the conversion successful?
614 if (-s "$output_filestem.html") {
615 open(TMP, "$output_filestem.html");
616 my $line = <TMP>;
617 close(TMP);
618 if ($line && $line =~ m/html/i) {
619 &FileUtils::removeFiles("$output_filestem.err") if -e "$output_filestem.err";
620 return 1;
621 }
622 }
623
624 # If here, an error of some sort occurred
625 &FileUtils::removeFiles("$output_filestem.html") if -e "$output_filestem.html";
626 if (-e "$output_filestem.err") {
627 if ($faillogfile ne "" && defined(open(FAILLOG,">>$faillogfile"))) {
628 open (ERRLOG,"$output_filestem.err");
629 while (<ERRLOG>) {print FAILLOG $_;}
630 close FAILLOG;
631 close ERRLOG;
632 }
633 &FileUtils::removeFiles("$output_filestem.err");
634 }
635 return 0;
636}
637
638# Attempt to convert an RTF document to html with rtftohtml
639sub rtf_to_html {
640 my ($input_filename, $output_filestem) = @_;
641
642 # formulate the command
643 my $cmd = "";
644 if ($timeout) {$cmd = "ulimit -t $timeout;";}
645 $cmd .= "rtftohtml";
646 #$cmd .= "rtf-converter";
647
648 $cmd .= " -o \"$output_filestem.html\" \"$input_filename\"";
649
650 $cmd .= " 2>\"$output_filestem.err\""
651 if ($ENV{'GSDLOS'} !~ m/^windows$/i || $is_winnt_2000);
652
653
654 # execute the command
655 $!=0;
656 if (system($cmd)!=0)
657 {
658 print STDERR "Error executing rtf converter $!\n";
659 # don't currently bother printing out error log...
660 # keep going, in case it still created an HTML file...
661 }
662
663 # Was the conversion successful?
664 my $was_successful=0;
665 if (-s "$output_filestem.html") {
666 # make sure we have some content other than header
667 open (HTML, "$output_filestem.html"); # what to do if fail?
668 my $line;
669 my $past_header=0;
670 while ($line=<HTML>) {
671
672 if ($past_header == 0) {
673 if ($line =~ m/<body>/) {$past_header=1;}
674 next;
675 }
676
677 $line =~ s/<[^>]+>//g;
678 if ($line =~ m/\w/ && $past_header) { # we found some content...
679 $was_successful=1;
680 last;
681 }
682 }
683 close HTML;
684 }
685
686 if ($was_successful) {
687 &FileUtils::removeFiles("$output_filestem.err")
688 if (-e "$output_filestem.err");
689 # insert the (modified) table of contents, if it exists.
690 if (-e "${output_filestem}_ToC.html") {
691 &FileUtils::moveFiles("$output_filestem.html","$output_filestem.src");
692 my $open_failed=0;
693 open HTMLSRC, "$output_filestem.src" || ++$open_failed;
694 open TOC, "${output_filestem}_ToC.html" || ++$open_failed;
695 open HTML, ">$output_filestem.html" || ++$open_failed;
696
697 if ($open_failed) {
698 close HTMLSRC;
699 close TOC;
700 close HTML;
701 &FileUtils::moveFiles("$output_filestem.src","$output_filestem.html");
702 return 1;
703 }
704
705 # print out header info from src html.
706 while (defined($_ = <HTMLSRC>) && $_ =~ m/\w/) {
707 print HTML "$_";
708 }
709
710 # print out table of contents, making links relative
711 <TOC>; <TOC>; # ignore first 2 lines
712 print HTML scalar(<TOC>); # line 3 = "<ol>\n"
713 my $line;
714 while ($line=<TOC>) {
715 $line =~ s@</body></html>$@@i ; # only last line has this
716 # make link relative
717 $line =~ s@href=\"[^\#]+@href=\"@i;
718 print HTML $line;
719 }
720 close TOC;
721
722 # rest of html src
723 while (<HTMLSRC>) {
724 print HTML $_;
725 }
726 close HTMLSRC;
727 close HTML;
728
729 &FileUtils::removeFiles("${output_filestem}_ToC.html");
730 &FileUtils::removeFiles("${output_filestem}.src");
731 }
732 # we don't yet do anything with footnotes ($output_filestem_fn.html) :(
733 return 1; # success
734 }
735
736 if (-e "$output_filestem.err") {
737 if ($faillogfile ne "" && defined(open(FAILLOG,">>$faillogfile")))
738 {
739 print FAILLOG "Error - rtftohtml - couldn't extract text\n";
740 #print FAILLOG "Error - rtf-converter - couldn't extract text\n";
741 print FAILLOG " (rtf file might be too recent):\n";
742 open (ERRLOG, "$output_filestem.err");
743 while (<ERRLOG>) {print FAILLOG $_;}
744 close ERRLOG;
745 close FAILLOG;
746 }
747 &FileUtils::removeFiles("$output_filestem.err");
748 }
749
750 &FileUtils::removeFiles("$output_filestem.html") if (-e "$output_filestem.html");
751
752 return 0;
753}
754
755
756# Convert a pdf file to html with the pdftohtml command
757
758sub pdf_to_html {
759 my ($dirname, $input_filename, $output_filestem) = @_;
760
761 my $cmd = "";
762 if ($timeout) {$cmd = "ulimit -t $timeout;";}
763 my $full_perl_path = &util::get_perl_exec();
764 $cmd .= "\"$full_perl_path\" -S pdftohtml.pl -zoom $pdf_zoom";
765 $cmd .= " -c" if ($pdf_complex);
766 $cmd .= " -i" if ($pdf_ignore_images);
767 $cmd .= " -a" if ($pdf_allow_images_only);
768 $cmd .= " -hidden" unless ($pdf_nohidden);
769 $cmd .= " \"$input_filename\" \"$output_filestem\"";
770
771 if ($ENV{'GSDLOS'} !~ m/^windows$/i || $is_winnt_2000) {
772 $cmd .= " > \"$output_filestem.out\" 2> \"$output_filestem.err\"";
773 } else {
774 $cmd .= " > \"$output_filestem.err\"";
775 }
776
777 $!=0;
778
779 my $retval=system($cmd);
780 if ($retval!=0)
781 {
782 print STDERR "Error executing pdftohtml.pl";
783 if ($!) {print STDERR ": $!";}
784 print STDERR "\n";
785 }
786
787 # make sure the converter made something
788 if ($retval!=0 || ! -s "$output_filestem.html")
789 {
790 &FileUtils::removeFiles("$output_filestem.out") if (-e "$output_filestem.out");
791 # print out the converter's std err, if any
792 if (-s "$output_filestem.err") {
793 open (ERRLOG, "$output_filestem.err") || die "$!";
794 print STDERR "pdftohtml error log:\n";
795 while (<ERRLOG>) {
796 print STDERR "$_";
797 }
798 close ERRLOG;
799 }
800 #print STDERR "***********output filestem $output_filestem.html\n";
801 &FileUtils::removeFiles("$output_filestem.html") if (-e "$output_filestem.html");
802 if (-e "$output_filestem.err") {
803 if ($faillogfile ne "" && defined(open(FAILLOG,">>$faillogfile")))
804 {
805 open (ERRLOG, "$output_filestem.err");
806 while (<ERRLOG>) {print FAILLOG $_;}
807 close ERRLOG;
808 close FAILLOG;
809 }
810 &FileUtils::removeFiles("$output_filestem.err");
811 }
812 return 0;
813 }
814
815 &FileUtils::removeFiles("$output_filestem.err") if (-e "$output_filestem.err");
816 &FileUtils::removeFiles("$output_filestem.out") if (-e "$output_filestem.out");
817 return 1;
818}
819
820# Convert a pdf file to various types of image with the convert command
821
822sub pdfps_to_img {
823 my ($dirname, $input_filename, $output_filestem, $output_type) = @_;
824
825 # Check that ImageMagick is installed and available on the path (except for Windows 95/98)
826 if (!($ENV{'GSDLOS'} eq "windows" && !Win32::IsWinNT())) {
827 my $imagick_cmd = "\"".&util::get_perl_exec()."\" -S gs-magick.pl";
828 $imagick_cmd = $imagick_cmd." --verbosity=$verbosity" if defined $verbosity;
829 my $result = `$imagick_cmd identify 2>&1`;
830
831 # Linux and Windows return different values for "program not found".
832 # Linux returns -1 and Windows 256 for "program not found". But once they're
833 # converted to signed values, it will be -1 for Linux and 1 for Windows.
834 # Whenever we test for return values other than 0, shift by 8 and perform
835 # unsigned to signed status conversion on $? to get expected range of return vals
836 # Although gs-magick.pl already shifts its $? by 8, converts it to a signed value
837 # and then exits on that, by the time we get here, we need to do it again
838 my $status = $?;
839 $status >>= 8;
840 $status = (($status & 0x80) ? -(0x100 - ($status & 0xFF)) : $status);
841 if (($ENV{'GSDLOS'} ne "windows" && $status == -1) || ($ENV{'GSDLOS'} eq "windows" && $status == 1)) {
842 # if ($status == -1 || $status == 1) #if ($status == -1 || $status == 256) {
843 #ImageMagick is not installed, thus the convert utility is not available.
844 print STDERR "*** ImageMagick is not installed, the convert utility is not available. Unable to convert PDF/PS to images. Status: $status\n";
845 return 0;
846 }
847 }
848
849 my $cmd = "";
850 if ($timeout) {$cmd = "ulimit -t $timeout;";}
851 $output_type =~ s/.*\_(.*)/$1/i;
852 my $full_perl_path = &util::get_perl_exec();
853 $cmd .= "\"$full_perl_path\" -S pdfpstoimg.pl -convert_to $output_type \"$input_filename\" \"$output_filestem\"";
854 if ($ENV{'GSDLOS'} !~ m/^windows$/i || $is_winnt_2000) {
855 $cmd .= " > \"$output_filestem.out\" 2> \"$output_filestem.err\"";
856 } else {
857 $cmd .= " > \"$output_filestem.err\"";
858 }
859
860 # don't include path on windows (to avoid having to play about
861 # with quoting when GSDLHOME might contain spaces) but assume
862 # that the PATH is set up correctly
863 $!=0;
864 my $retval=system($cmd);
865 if ($retval!=0)
866 {
867 print STDERR "Error executing pdfpstoimg.pl";
868 if ($!) {print STDERR ": $!";}
869 print STDERR "\n";
870 }
871
872 #make sure the converter made something
873 #if ($retval !=0) || ! -s "$output_filestem")
874 if ($retval !=0)
875 {
876 &FileUtils::removeFiles("$output_filestem.out") if (-e "$output_filestem.out");
877 #print out the converter's std err, if any
878 if (-s "$output_filestem.err") {
879 open (ERRLOG, "$output_filestem.err") || die "$!";
880 print STDERR "pdfpstoimg error log:\n";
881 while (<ERRLOG>) {
882 print STDERR "$_";
883 }
884 close ERRLOG;
885 }
886 #&FileUtils::removeFiles("$output_filestem.html") if (-e "$output_filestem.html");
887 if (-e "$output_filestem.err") {
888 if ($faillogfile ne "" && defined(open(FAILLOG,">>$faillogfile")))
889 {
890 open (ERRLOG, "$output_filestem.err");
891 while (<ERRLOG>) {print FAILLOG $_;}
892 close ERRLOG;
893 close FAILLOG;
894 }
895 &FileUtils::removeFiles("$output_filestem.err");
896 }
897 return 0;
898 }
899 &FileUtils::removeFiles("$output_filestem.err") if (-e "$output_filestem.err");
900 &FileUtils::removeFiles("$output_filestem.out") if (-e "$output_filestem.out");
901 return 1;
902}
903
904# Convert a PDF file to text with the pdftotext command
905
906sub pdf_to_text {
907 my ($dirname, $input_filename, $output_filestem) = @_;
908
909 my $cmd = "pdftotext \"$input_filename\" \"$output_filestem.text\"";
910
911 if ($ENV{'GSDLOS'} !~ m/^windows$/i) {
912 $cmd .= " > \"$output_filestem.out\" 2> \"$output_filestem.err\"";
913 } else {
914 $cmd .= " > \"$output_filestem.err\"";
915 }
916
917 if (system($cmd)!=0)
918 {
919 print STDERR "Error executing $cmd: $!\n";
920 &FileUtils::removeFiles("$output_filestem.text") if (-e "$output_filestem.text");
921 }
922
923 # make sure there is some extracted text.
924 if (-e "$output_filestem.text") {
925 open (EXTR_TEXT, "$output_filestem.text") || warn "open: $!";
926 binmode(EXTR_TEXT); # just in case...
927 my $line="";
928 my $seen_text=0;
929 while (($seen_text==0) && ($line=<EXTR_TEXT>)) {
930 if ($line=~ m/\w/) {$seen_text=1;}
931 }
932 close EXTR_TEXT;
933 if ($seen_text==0) { # no text was extracted
934 print STDERR "Error: pdftotext found no text\n";
935 &FileUtils::removeFiles("$output_filestem.text");
936 }
937 }
938
939 # make sure the converter made something
940 if (! -s "$output_filestem.text")
941 {
942 # print out the converters std err, if any
943 if (-s "$output_filestem.err") {
944 open (ERRLOG, "$output_filestem.err") || die "$!";
945 print STDERR "pdftotext error log:\n";
946 while (<ERRLOG>) {
947 print STDERR "$_";
948 }
949 close ERRLOG;
950 }
951 # does this converter create a .out file?
952 &FileUtils::removeFiles("$output_filestem.out") if (-e "$output_filestem.out");
953 &FileUtils::removeFiles("$output_filestem.text") if (-e "$output_filestem.text");
954 if (-e "$output_filestem.err") {
955 if ($faillogfile ne "" && defined(open(FAILLOG,">>$faillogfile")))
956 {
957 open (ERRLOG,"$output_filestem.err");
958 while (<ERRLOG>) {print FAILLOG $_;}
959 close ERRLOG;
960 close FAILLOG;
961 }
962 &FileUtils::removeFiles("$output_filestem.err");
963 }
964 return 0;
965 }
966 &FileUtils::removeFiles("$output_filestem.err") if (-e "$output_filestem.err");
967 return 1;
968}
969
970# Convert a PostScript document to text
971# note - just using "ps2ascii" isn't good enough, as it
972# returns 0 for a postscript interpreter error. ps2ascii is just
973# a wrapper to "gs" anyway, so we use that cmd here.
974
975sub ps_to_text {
976 my ($input_filename, $output_filestem) = @_;
977
978 my $error = "";
979
980 # if we're on windows we'll fall straight through without attempting
981 # to use gs
982 if ($ENV{'GSDLOS'} =~ m/^windows$/i) {
983 $error = "Windows does not support gs";
984
985 } else {
986 my $cmd = "";
987 if ($timeout) {$cmd = "ulimit -t $timeout; ";}
988 $cmd .= "gs -q -dNODISPLAY -dNOBIND -dWRITESYSTEMDICT -dSIMPLE -c save ";
989 $cmd .= "-f ps2ascii.ps \"$input_filename\" -c quit > \"$output_filestem.text\"";
990 #$cmd .= "pstotext -output \"$output_filestem.text\" $input_filename\"";
991 $cmd .= " 2> $output_filestem.err";
992 $!=0;
993
994 my $retcode=system($cmd);
995 $retcode = $? >> 8; # see man perlfunc - system for this...
996 # if system returns -1 | 127 (couldn't start program), look at $! for message
997
998 if ($retcode!=0) {if ($!) {$error=$!;} else {$error="couldn't run.\n";}}
999 elsif (! -e "$output_filestem.text") {
1000 $error="did not create output file.\n";
1001 }
1002 else
1003 { # make sure the interpreter didn't get an error. It is technically
1004 # possible for the actual text to start with this, but....
1005 open PSOUT, "$output_filestem.text";
1006 if (<PSOUT> =~ m/^Error: (.*)/) {
1007 $error="interpreter error - \"$1\"";
1008 }
1009 close PSOUT;
1010 }
1011 }
1012
1013 if ($error ne "")
1014 {
1015 print STDERR "Warning: Error executing gs: $error\n";
1016 &FileUtils::removeFiles("$output_filestem.text") if (-e "$output_filestem.text");
1017
1018 if ("$faillogfile" ne "" && defined(open (FAILLOG, ">>$faillogfile")))
1019 {
1020 print FAILLOG "gs - $error\n";
1021 if (-e "$output_filestem.err") {
1022 open(ERRLOG, "$output_filestem.err");
1023 while (<ERRLOG>) {print FAILLOG $_;}
1024 close ERRLOG;
1025 }
1026 close FAILLOG;
1027 }
1028 &FileUtils::removeFiles("$output_filestem.err") if (-e "$output_filestem.err");
1029
1030
1031 # Fine then. We'll just do a lousy job by ourselves...
1032 # Based on 5-line regexp sed script found at:
1033 # http://snark.ptc.spbu.ru/mail-archives/lout/brown/msg00003.html
1034 #
1035 print STDERR "Stripping text from postscript\n";
1036 my $errorcode=0;
1037 open (IN, "$input_filename")
1038 || ($errorcode=1, warn "Couldn't read file: $!");
1039 open (OUT, ">$output_filestem.text")
1040 || ($errorcode=1, warn "Couldn't write file: $!");
1041 if ($errorcode) {print STDERR "errors\n";return 0;}
1042
1043 my $text=""; # this is for whole .ps file...
1044 $text = join('', <IN>); # see man perlport, under "System Resources"
1045 close IN;
1046
1047 # Make sure this is a ps file...
1048 if ($text !~ m/^%!/) {
1049 print STDERR "Bad postscript header: not '%!'\n";
1050 if ($faillogfile ne "" && defined(open(FAILLOG, ">>$faillogfile")))
1051 {
1052 print FAILLOG "Bad postscript header: not '%!'\n";
1053 close FAILLOG;
1054 }
1055 return 0;
1056 }
1057
1058 # if ps has Page data, then use it to delete all stuff before it.
1059 $text =~ s/^.*?%%Page:.*?\n//s; # treat string as single line
1060
1061 # remove all leading non-data stuff
1062 $text =~ s/^.*?\(//s;
1063
1064 # remove all newline chars for easier processing
1065 $text =~ s/\n//g;
1066
1067 # Big assumption here - assume that if any co-ordinates are
1068 # given, then we are at the end of a sentence.
1069 $text =~ s/\)-?\d+\ -?\d+/\) \(\n\)/g;
1070
1071 # special characters--
1072 $text =~ s/\(\|\)/\(\ - \)/g; # j -> em-dash?
1073
1074 # ? ps text formatting (eg italics?) ?
1075 $text =~ s/Fn\(f\)/\(\{\)/g; # f -> {
1076 $text =~ s/Fn\(g\)/\(\}\)/g; # g -> }
1077 $text =~ s/Fn\(j\)/\(\|\)/g; # j -> |
1078 # default - remove the rest
1079 $text =~ s/\ ?F.\((.+?)\)/\($1\)/g;
1080
1081 # attempt to add whitespace between words...
1082 # this is based purely on observation, and may be completely wrong...
1083 $text =~ s/([^F])[defghijkuy]\(/$1 \( /g;
1084 # eg I notice "b(" is sometimes NOT a space if preceded by a
1085 # negative number.
1086 $text =~ s/\)\d+ ?b\(/\) \( /g;
1087
1088 # change quoted braces to brackets
1089 $text =~ s/([^\\])\\\(/$1\{/g;
1090 $text =~ s/([^\\])\\\)/$1\}/g ;
1091
1092 # remove everything that is not between braces
1093 $text =~ s/\)([^\(\)])+?\(//sg ;
1094
1095 # remove any Trailer eof stuff.
1096 $text =~ s/\)[^\)]*$//sg;
1097
1098 ### ligatures have special characters...
1099 $text =~ s/\\013/ff/g;
1100 $text =~ s/\\014/fi/g;
1101 $text =~ s/\\015/fl/g;
1102 $text =~ s/\\016/ffi/g;
1103 $text =~ s/\\214/fi/g;
1104 $text =~ s/\\215/fl/g;
1105 $text =~ s/\\017/\n\* /g; # asterisk?
1106 $text =~ s/\\023/\023/g; # e acute ('e)
1107 $text =~ s/\\177/\252/g; # u"
1108# $text =~ s/ ?? /\344/g; # a"
1109
1110 print OUT "$text";
1111 close OUT;
1112 }
1113 # wrap the text - use a minimum length. ie, first space after this length.
1114 my $wrap_length=72;
1115 &FileUtils::moveFiles("$output_filestem.text", "$output_filestem.text.tmp");
1116 open INFILE, "$output_filestem.text.tmp" ||
1117 die "Couldn't open file: $!";
1118 open OUTFILE, ">$output_filestem.text" ||
1119 die "Couldn't open file for writing: $!";
1120 my $line="";
1121 while ($line=<INFILE>) {
1122 while (length($line)>0) {
1123 if (length($line)>$wrap_length) {
1124 $line =~ s/^(.{$wrap_length}[^\s]*)\s*//;
1125 print OUTFILE "$1\n";
1126 } else {
1127 print OUTFILE "$line";
1128 $line="";
1129 }
1130 }
1131 }
1132 close INFILE;
1133 close OUTFILE;
1134 &FileUtils::removeFiles("$output_filestem.text.tmp");
1135
1136 &FileUtils::removeFiles("$output_filestem.err") if (-e "$output_filestem.err");
1137 return 1;
1138}
1139
1140
1141# Convert any file to HTML with a crude perl implementation of the
1142# UNIX strings command.
1143
1144sub any_to_html {
1145 my ($input_filename, $output_filestem) = @_;
1146
1147 # First generate a text file
1148 return 0 unless (&any_to_text($input_filename, $output_filestem));
1149
1150 # create an HTML file from the text file
1151 open(TEXT, "<$output_filestem.text");
1152 open(HTML, ">$output_filestem.html");
1153
1154 print HTML "<html><head>\n";
1155 print HTML "<META HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html\">\n";
1156 print HTML "<META NAME=\"GENERATOR\" CONTENT=\"Greenstone any_to_html\">\n";
1157 print HTML "</head><body>\n\n";
1158
1159 my $line;
1160 while ($line=<TEXT>) {
1161 $line =~ s/</&lt;/g;
1162 $line =~ s/>/&gt;/g;
1163 if ($line =~ m/^\s*$/) {
1164 print HTML "<p>";
1165 } else {
1166 print HTML "<br> ", $line;
1167 }
1168 }
1169 print HTML "\n</body></html>\n";
1170
1171 close HTML;
1172 close TEXT;
1173
1174 &FileUtils::removeFiles("$output_filestem.text") if (-e "$output_filestem.text");
1175 return 1;
1176}
1177
1178# Convert any file to TEXT with a crude perl implementation of the
1179# UNIX strings command.
1180# Note - this assumes ascii charsets :( (jrm21)
1181
1182sub any_to_text {
1183 my ($input_filename, $output_filestem) = @_;
1184
1185 if (!$use_strings) {
1186 return 0;
1187 }
1188
1189 print STDERR "\n**** In any to text****\n\n";
1190 open(IN, "<$input_filename") || return 0;
1191 binmode(IN);
1192 open(OUT, ">$output_filestem.text") || return 0;
1193
1194 my ($line);
1195 my $output_line_count = 0;
1196 while (<IN>) {
1197 $line = $_;
1198
1199 # delete anything that isn't a printable character
1200 $line =~ s/[^\040-\176]+/\n/sg;
1201
1202 # delete any string less than 10 characters long
1203 $line =~ s/^.{0,9}$/\n/mg;
1204 while ($line =~ m/^.{1,9}$/m) {
1205 $line =~ s/^.{0,9}$/\n/mg;
1206 $line =~ s/\n+/\n/sg;
1207 }
1208
1209 # remove extraneous whitespace
1210 $line =~ s/\n+/\n/gs;
1211 $line =~ s/^\n//gs;
1212
1213 # output whatever is left
1214 if ($line =~ m/[^\n ]/) {
1215 print OUT $line;
1216 ++$output_line_count;
1217 }
1218 }
1219
1220 close OUT;
1221 close IN;
1222
1223 if ($output_line_count) { # try to protect against binary only formats
1224 return 1;
1225 }
1226
1227 &FileUtils::removeFiles("$output_filestem.text");
1228 return 0;
1229
1230}
Note: See TracBrowser for help on using the repository browser.