Use new logger

This commit is contained in:
John Whitington 2023-04-25 13:45:56 +01:00
parent b17b08a3e1
commit c30c49e90e
13 changed files with 78 additions and 80 deletions

View File

@ -24,7 +24,7 @@ let charcodes_of_utf8 font s =
match extractor codepoint with
| Some cc -> Some cc
| None ->
Printf.eprintf "Warning: character not found in font for unicode codepoint 0x%X\n" codepoint;
Pdfe.log (Printf.sprintf "Warning: character not found in font for unicode codepoint 0x%X\n" codepoint);
None)
codepoints
in
@ -498,7 +498,7 @@ let
| Some (Pdftext.SimpleFont {fontdescriptor = Some {capheight}}) ->
voffset := !voffset +. capheight /. 2.
| _ ->
Printf.eprintf "Unable to find midline adjustment in this font\n"
Pdfe.log "Unable to find midline adjustment in this font\n"
end
else
if topline then
@ -511,7 +511,7 @@ let
| Some (Pdftext.SimpleFont {fontdescriptor = Some {capheight}}) ->
voffset := !voffset +. capheight
| _ ->
Printf.eprintf "Unable to find midline adjustment in this font\n"
Pdfe.log "Unable to find midline adjustment in this font\n"
end;
let encoding =
match font with

View File

@ -75,7 +75,7 @@ let annotations_json_page calculate_pagenumber pdf page pagenum =
`Int objnum;
Cpdfjson.json_of_object ~utf8:true ~clean_strings:true pdf (fun _ -> ())
~no_stream_data:false ~parse_content:false annot])
| _ -> Printf.eprintf "Warning: annotations must be indirect\n"; None
| _ -> Pdfe.log "Warning: annotations must be indirect\n"; None
end)
annots
| _ -> []
@ -93,7 +93,7 @@ let get_annotations_json pdf range =
let pages, pagenums = split pairs in
let json = flatten (map2 (annotations_json_page calculate_pagenumber pdf) pages pagenums) in
(*Printf.printf "%i extra roots to explore\n" (length extra);
iter (fun x -> Printf.eprintf "%s\n\n" (Pdfwrite.string_of_pdf x)) extra;*)
iter (fun x -> Pdfe.log "%s\n\n" (Pdfwrite.string_of_pdf x)) extra;*)
let extra =
map
(fun n ->

View File

@ -169,7 +169,7 @@ let list_attached_files pdf =
| Some (Pdf.String s) ->
begin match Pdf.lookup_direct pdf "/FS" annot with
| Some ((Pdf.Dictionary _) as d) ->
(*Printf.eprintf "%s\n%!" (Pdfwrite.string_of_pdf d);*)
(*Pdfe.log (Printf.sprintf "%s\n" (Pdfwrite.string_of_pdf d));*)
begin match Pdf.lookup_direct pdf "/EF" d with
| Some ((Pdf.Dictionary _) as d) ->
begin match Pdf.lookup_direct pdf "/F" d with
@ -264,7 +264,7 @@ let dump_attachment out pdf (_, embeddedfile) =
for x = 0 to bytes_size efdata - 1 do output_byte fh (bget efdata x) done;
close_out fh
with
e -> Printf.eprintf "Failed to write attachment to %s\n%!" filename;
e -> Pdfe.log (Printf.sprintf "Failed to write attachment to %s\n" filename);
end
| _ -> ()

View File

@ -69,12 +69,11 @@ exception StayOnError
(* Fatal error reporting. *)
let error s =
prerr_string (s ^ "\nUse -help for help.\n");
flush stderr;
Pdfe.log (s ^ "\nUse -help for help.\n");
if not !stay_on_error then exit 2 else raise StayOnError
let soft_error s =
Printf.eprintf "%s\n%!" s;
Pdfe.log (Printf.sprintf "%s\n" s);
if not !stay_on_error then exit 1 else raise StayOnError
let parse_pagespec pdf spec =
@ -757,14 +756,14 @@ let call_cpdflin cpdflin temp output best_password =
match Sys.os_type with
"Win32" ->
(* On windows, don't use LD_LIBRARY_PATH - it will happen automatically *)
if args.debug then prerr_endline command;
if args.debug then Pdfe.log (command ^ "\n");
Sys.command command
| _ ->
(* On other platforms, if -cpdflin was provided, or cpdflin was in the
current folder, set up LD_LIBRARY_PATH: *)
match cpdflin with
"cpdflin" ->
if args.debug then prerr_endline command;
if args.debug then Pdfe.log (command ^ "\n");
Sys.command command
| _ ->
let command =
@ -772,7 +771,7 @@ let call_cpdflin cpdflin temp output best_password =
"LD_LIBRARY_PATH=" ^ Filename.quote (Filename.dirname cpdflin) ^ " " ^
command
in
if args.debug then prerr_endline command;
if args.debug then Pdfe.log (command ^ "\n");
Sys.command command
let get_pagespec () =
@ -904,8 +903,8 @@ let detect_duplicate_op op =
match args.op with
None | Some Shift -> ()
| _ ->
Printf.eprintf "Operation %s already specified, so cannot specify operation %s.\nUse AND from Chapter 1 of the manual to chain commands together.\n%!"
(string_of_op (unopt args.op)) (string_of_op op);
Pdfe.log (Printf.sprintf "Operation %s already specified, so cannot specify operation %s.\nUse AND from Chapter 1 of the manual to chain commands together.\n"
(string_of_op (unopt args.op)) (string_of_op op));
exit 1
let setop op () =
@ -986,7 +985,7 @@ let anon_fun s =
Not_found ->
match args.inputs with
| [] ->
Printf.eprintf "Warning: range '%s' ignored\n%!" s
Pdfe.log (Printf.sprintf "Warning: range '%s' ignored\n" s)
| (a, _, d, e, f, g)::t ->
args.inputs <- (a, fixdashes s, d, e, f, g)::t
@ -1485,7 +1484,7 @@ let setrevision n =
(a, b, c, d, e, _)::more ->
args.inputs <- (a, b, c, d, e, Some n) :: more
| [] ->
Printf.eprintf "Warning. -revision ignored. Put it after the filename.\n%!"
Pdfe.log "Warning. -revision ignored. Put it after the filename.\n"
let setoutline () =
args.outline <- true
@ -1769,7 +1768,7 @@ let setfontttfencoding s =
| _ -> error "Unknown encoding"
let whingemalformed () =
prerr_string "Command line must be of exactly the form\ncpdf <infile> -gs <path> -gs-malformed-force -o <outfile>\n";
Pdfe.log "Command line must be of exactly the form\ncpdf <infile> -gs <path> -gs-malformed-force -o <outfile>\n";
exit 1
(* Drawing operations. FIXME: Clear this around ANDs? *)
@ -2045,6 +2044,9 @@ let set_input_png s =
let addimage s =
addop (Cpdfdraw.Image s)
let setstderrtostdout () =
Pdfe.logger := (fun s -> print_string s; flush stdout)
(* Parse a control file, make an argv, and then make Arg parse it. *)
let rec make_control_argv_and_parse filename =
control_args := !control_args @ parse_control_file filename
@ -2881,6 +2883,7 @@ and specs =
("-debug-crypt", Arg.Unit setdebugcrypt, "");
("-debug-force", Arg.Unit setdebugforce, "");
("-debug-malformed", Arg.Set Pdfread.debug_always_treat_malformed, "");
("-debug-stderr-to-stdout", Arg.Unit setstderrtostdout, "");
("-stay-on-error", Arg.Unit setstayonerror, "");
(* These items are unfinished *)
("-extract-fontfile", Arg.Unit (setop ExtractFontFile), "");
@ -2911,11 +2914,12 @@ let filesize name =
(* Mend PDF file with Ghostscript. We use this if a file is malformed and CPDF
* cannot mend it. It is copied to a temporary file, fixed, then we return None or Some (pdf). *)
let mend_pdf_file_with_ghostscript filename =
if args.path_to_ghostscript = "" then begin
Printf.eprintf "Please supply path to gs with -gs\n%!";
end;
Printf.eprintf "CPDF could not mend. Attempting to mend file with gs\n%!";
flush stderr;
match args.path_to_ghostscript with
| "" ->
Pdfe.log "Please supply path to gs with -gs\n";
exit 2
| _ ->
Pdfe.log "CPDF could not mend. Attempting to mend file with gs\n";
let tmpout = Filename.temp_file "cpdf" ".pdf" in
tempfiles := tmpout::!tempfiles;
let gscall =
@ -2924,8 +2928,8 @@ let mend_pdf_file_with_ghostscript filename =
["-dNOPAUSE"; "-sDEVICE=pdfwrite"; "-sOUTPUTFILE=" ^ tmpout; "-dBATCH"; filename])
in
match Sys.command gscall with
| 0 -> Printf.eprintf "Succeeded!\n%!"; flush stderr; tmpout
| _ -> Printf.eprintf "Could not fix malformed PDF file, even with gs\n%!"; flush stderr; exit 2
| 0 -> Pdfe.log "Succeeded!\n"; tmpout
| _ -> Pdfe.log "Could not fix malformed PDF file, even with gs\n"; exit 2
exception StdInBytes of bytes
@ -2951,7 +2955,7 @@ let rec get_single_pdf ?(decrypt=true) ?(fail=false) op read_lazy =
let failout () =
if fail then begin
(* Reconstructed with ghostscript, but then we couldn't read it even then. Do not loop. *)
Printf.eprintf "Failed to read gs-reconstructed PDF even though gs succeeded\n%!";
Pdfe.log "Failed to read gs-reconstructed PDF even though gs succeeded\n";
exit 2
end
in
@ -2959,12 +2963,12 @@ let rec get_single_pdf ?(decrypt=true) ?(fail=false) op read_lazy =
begin match args.inputs with
(InFile inname, _, _, _, _, _)::_ ->
begin try ignore (close_in (open_in_bin inname)) with _ ->
Printf.eprintf "File %s does not exist\n%!" inname;
Pdfe.log (Printf.sprintf "File %s does not exist\n" inname);
exit 2
end
| _ -> ()
end;
Printf.eprintf "get_single_pdf: failed to read malformed PDF file. Consider using -gs-malformed\n%!";
Pdfe.log "get_single_pdf: failed to read malformed PDF file. Consider using -gs-malformed\n";
exit 2
in
match args.inputs with
@ -3034,7 +3038,7 @@ let rec get_pdf_from_input_kind ?(read_lazy=false) ?(decrypt=true) ?(fail=false)
let failout () =
if fail then begin
(* Reconstructed with ghostscript, but then we couldn't read it even then. Do not loop. *)
Printf.eprintf "Failed to read gs-reconstructed PDF even though gs succeeded\n%!";
Pdfe.log "Failed to read gs-reconstructed PDF even though gs succeeded\n";
exit 2
end
in
@ -3042,12 +3046,12 @@ let rec get_pdf_from_input_kind ?(read_lazy=false) ?(decrypt=true) ?(fail=false)
begin match input with
(InFile inname, _, _, _, _, _) ->
begin try ignore (close_in (open_in_bin inname)) with _ ->
Printf.eprintf "File %s does not exist\n%!" inname;
Pdfe.log (Printf.sprintf "File %s does not exist\n" inname);
exit 2
end
| _ -> ()
end;
Printf.eprintf "get_pdf_from_input_kind: failed to read malformed PDF file. Consider using -gs-malformed\n%!";
Pdfe.log "get_pdf_from_input_kind: failed to read malformed PDF file. Consider using -gs-malformed\n";
exit 2
in
match ik with
@ -3138,7 +3142,7 @@ let really_write_pdf ?(encryption = None) ?(is_decompress=false) mk_id pdf outna
then
set_producer "cpdf non-commercial use only. To buy: http://coherentpdf.com/" pdf;
if args.creator <> None then set_creator (unopt args.creator) pdf;
if args.debugcrypt then Printf.printf "really_write_pdf\n%!";
if args.debugcrypt then Printf.printf "really_write_pdf\n";
let will_linearize =
args.linearize || args.keeplinearize && pdf.Pdf.was_linearized
in
@ -3262,7 +3266,7 @@ let write_pdf ?(encryption = None) ?(is_decompress=false) mk_id pdf =
with
End_of_file ->
begin try close_in temp_file; Sys.remove temp with
e -> Printf.eprintf "Failed to remove temp file %s (%s)\n%!" temp (Printexc.to_string e)
e -> Pdfe.log (Printf.sprintf "Failed to remove temp file %s (%s)\n" temp (Printexc.to_string e))
end;
flush stdout (*r For Windows *)
@ -3393,9 +3397,9 @@ let collate (names, pdfs, ranges) =
let warn_prerotate range pdf =
if not args.prerotate && not (Cpdfpage.allupright range pdf) then
Printf.eprintf "Some pages in the range have non-zero rotation or non (0,0)-based mediabox. \
Pdfe.log "Some pages in the range have non-zero rotation or non (0,0)-based mediabox. \
Consider adding -prerotate or pre-processing with -upright. \
To silence this warning use -no-warn-rotate\n%!"
To silence this warning use -no-warn-rotate\n"
let prerotate range pdf =
Cpdfpage.upright ~fast:args.fast range pdf
@ -3426,13 +3430,13 @@ let embed_font () =
let check_bookmarks_mistake () =
if args.merge_add_bookmarks_use_titles && not args.merge_add_bookmarks then
Printf.eprintf "Warning: -merge-add-bookmarks-use-titles is for use with -merge-add-bookmarks\n"
Pdfe.log "Warning: -merge-add-bookmarks-use-titles is for use with -merge-add-bookmarks\n"
let check_clashing_output_name () =
match args.out with
| File s ->
if (List.exists (function (InFile s', _, _, _, _, _) when s = s' -> true | _ -> false) args.inputs) then
Printf.eprintf "Warning: output file name clashes with input file name. Malformed file may result.\n"
Pdfe.log "Warning: output file name clashes with input file name. Malformed file may result.\n"
| _ -> ()
(* Main function *)
@ -3688,7 +3692,7 @@ let go () =
Pdf.iter_stream
(function stream ->
try Pdfcodec.decode_pdfstream_until_unknown pdf stream with
e -> Printf.eprintf "Decode failure: %s. Carrying on...\n%!" (Printexc.to_string e); ())
e -> Pdfe.log (Printf.sprintf "Decode failure: %s. Carrying on...\n" (Printexc.to_string e)); ())
pdf;
write_pdf ~is_decompress:true false pdf
| Some Compress ->
@ -4386,7 +4390,7 @@ let check_command_line () =
let parse_argv () s specs anon_fun usage_msg =
if args.debug then
Array.iter (Printf.eprintf "arg: %s\n%!") Sys.argv;
Array.iter (fun s -> Pdfe.log (Printf.sprintf "arg: %s\n" s)) Sys.argv;
Arg.parse_argv ~current:(ref 0) s specs anon_fun usage_msg;
check_command_line ()
@ -4408,7 +4412,7 @@ let expand_args argv =
let gs_malformed_force fi fo =
if args.path_to_ghostscript = "" then begin
Printf.eprintf "Please supply path to gs with -gs\n%!";
Pdfe.log "Please supply path to gs with -gs\n";
exit 2
end;
let gscall =
@ -4418,7 +4422,7 @@ let gs_malformed_force fi fo =
in
match Sys.command gscall with
| 0 -> exit 0
| _ -> Printf.eprintf "Failed to mend file.\n%!"; exit 2
| _ -> Pdfe.log "Failed to mend file.\n"; exit 2
let process_env_vars () =
match Sys.getenv_opt "CPDF_DEBUG" with
@ -4447,9 +4451,8 @@ let go_withargv argv =
flprint "This demo is for evaluation only. http://www.coherentpdf.com/\n";
if noncomp then
begin
prerr_string "For non-commercial use only\n";
prerr_string "To purchase a license visit http://www.coherentpdf.com/\n\n";
flush stderr
Pdfe.log "For non-commercial use only\n";
Pdfe.log "To purchase a license visit http://www.coherentpdf.com/\n\n";
end;
try
(* Pre-expand -args *)
@ -4480,23 +4483,20 @@ let go_withargv argv =
exit 0
with
| Arg.Bad s ->
prerr_string
Pdfe.log
(implode (takewhile (neq '\n') (explode s)) ^ " Use -help for help.\n\n");
flush stderr;
if not !stay_on_error then exit 2 else raise StayOnError
| Arg.Help _ ->
Arg.usage (align_specs specs) usage_msg;
flush stderr (*r for Windows *)
| Sys_error s as e ->
prerr_string (s ^ "\n\n");
flush stderr;
Pdfe.log (s ^ "\n\n");
if not !stay_on_error then
(if args.debug then raise e else exit 2)
else raise StayOnError
| Pdf.PDFError s as e ->
prerr_string
Pdfe.log
("cpdf encountered an error. Technical details follow:\n\n" ^ s ^ "\n\n");
flush stderr;
if not !stay_on_error then
if args.debug then raise e else exit 2
else
@ -4504,10 +4504,9 @@ let go_withargv argv =
| Cpdferror.SoftError s -> soft_error s
| Cpdferror.HardError s -> error s
| e ->
prerr_string
Pdfe.log
("cpdf encountered an unexpected error. Technical Details follow:\n" ^
Printexc.to_string e ^ "\n\n");
flush stderr;
if not !stay_on_error then
(if args.debug then raise e else exit 2) else raise StayOnError

View File

@ -3,8 +3,7 @@ open Pdfutil
let emptypage = Pdfpage.blankpage Pdfpaper.a4
let error s =
prerr_string (s ^ "\nUse -help for help.\n");
flush stderr;
Pdfe.log (s ^ "\nUse -help for help.\n");
exit 2
(* Unit conversions to points. *)

View File

@ -5,7 +5,7 @@ open Pdfio
(* Embed missing fonts with Ghostscript. *)
let embed_missing_fonts path_to_ghostscript gs_quiet fi fo =
if path_to_ghostscript = "" then begin
Printf.eprintf "Please supply path to gs with -gs\n%!";
Pdfe.log "Please supply path to gs with -gs\n";
exit 2
end;
let gscall =
@ -19,7 +19,7 @@ let embed_missing_fonts path_to_ghostscript gs_quiet fi fo =
in
match Sys.command gscall with
| 0 -> exit 0
| _ -> Printf.eprintf "Font embedding failed.\n%!"; exit 2
| _ -> Pdfe.log "Font embedding failed.\n"; exit 2
(* Copy a font from [frompdf] with name [fontname] on page [fontpage] to [pdf] on all pages in [range] *)
let copy_font frompdf fontname fontpage range pdf =

View File

@ -70,14 +70,14 @@ let write_image path_to_p2p path_to_im pdf resources name image =
begin match path_to_p2p with
| "" ->
begin match path_to_im with
"" -> Printf.eprintf "Neither pnm2png nor imagemagick found. Specify with -p2p or -im\n%!"
"" -> Pdfe.log "Neither pnm2png nor imagemagick found. Specify with -p2p or -im\n"
| _ ->
begin match
Sys.command (Filename.quote_command path_to_im [pnm; png])
with
0 -> Sys.remove pnm
| _ ->
Printf.eprintf "Call to imagemagick failed: did you specify -p2p or -im correctly?\n%!";
Pdfe.log "Call to imagemagick failed: did you specify -p2p or -im correctly?\n";
Sys.remove pnm
end
end
@ -87,17 +87,17 @@ let write_image path_to_p2p path_to_im pdf resources name image =
with
| 0 -> Sys.remove pnm
| _ ->
Printf.eprintf "Call to pnmtopng failed: did you specify -p2p correctly?\n%!";
Pdfe.log "Call to pnmtopng failed: did you specify -p2p correctly?\n";
Sys.remove pnm
end
end
| _ ->
Printf.eprintf "Unsupported image type when extracting image %s %!" name
Pdfe.log (Printf.sprintf "Unsupported image type when extracting image %s " name)
end
in
match write_image_png pdf resources name image with
| true -> ()
| exception x -> Printf.printf "Failed to write PNG directly (%s)\n" (Printexc.to_string x); main ()
| exception x -> Pdfe.log (Printf.sprintf "Failed to write PNG directly (%s)\n" (Printexc.to_string x)); main ()
| _ -> main ()
let written = ref []

View File

@ -204,11 +204,11 @@ let rec op_of_json = function
| `String "SCNName"::`String s::ns -> O.Op_SCNName (s, map opf (rev ns))
| `String "scnName"::`String s::ns -> O.Op_scnName (s, map opf (rev ns))
| j ->
Printf.eprintf "Unable to read reversed op from %s\n" (J.show (`List j));
Pdfe.log (Printf.sprintf "Unable to read reversed op from %s\n" (J.show (`List j)));
error "op reading failed"
end
| j ->
Printf.eprintf "Unable to read op from %s\n" (J.show j);
Pdfe.log (Printf.sprintf "Unable to read op from %s\n" (J.show j));
error "op reading failed"
and object_of_json = function
@ -219,7 +219,7 @@ and object_of_json = function
| `List objs -> P.Array (map object_of_json objs)
| `Assoc ["U", `String u] ->
begin try P.String (Pdftext.pdfdocstring_of_utf8 u) with
_ -> Printf.eprintf "Could not read UTF8 string %S\n" u; P.String u
_ -> Pdfe.log (Printf.sprintf "Could not read UTF8 string %S\n" u); P.String u
end
| `Assoc ["I", `Int i] -> P.Integer i
| `Assoc ["F", `Float f] -> P.Real f

View File

@ -487,11 +487,11 @@ let xmp_date date =
| _ -> raise Exit
end
| _ ->
Printf.eprintf "xmp_date: Malformed date string (no year): %s\n%!" date;
Pdfe.log (Printf.sprintf "xmp_date: Malformed date string (no year): %s\n" date);
make_xmp_date_from_components d
end
| _ ->
Printf.eprintf "xmp_date: Malformed date string (no prefix): %s\n%!" date;
Pdfe.log (Printf.sprintf "xmp_date: Malformed date string (no prefix): %s\n" date);
make_xmp_date_from_components d
with
Exit -> make_xmp_date_from_components d

View File

@ -525,7 +525,7 @@ let protect fast pdf resources content =
let qs = length (keep (eq Pdfops.Op_q) ops) in
let bigqs = length (keep (eq Pdfops.Op_Q) ops) in
let deficit = if qs > bigqs then qs - bigqs else 0 in
if deficit <> 0 then Printf.eprintf "Q Deficit was nonzero. Fixing. %i\n%!" deficit;
if deficit <> 0 then Pdfe.log (Printf.sprintf "Q Deficit was nonzero. Fixing. %i\n" deficit);
deficit
in
let addstream ops = Pdf.addobj pdf (Pdfops.stream_of_ops ops) in
@ -876,7 +876,7 @@ let trim_marks_page fast pdf n page =
in
Pdfpage.postpend_operators pdf ops ~fast page
| _, _ ->
(*Printf.eprintf "warning: no /TrimBox found on page %i\n%!" n;*)
(*Pdfe.log (Printf.sprintf "warning: no /TrimBox found on page %i\n" n);*)
page
let trim_marks ?(fast=false) pdf range =

View File

@ -199,7 +199,7 @@ let return_date () =
let current_time () =
try return_date () with
e ->
Printf.eprintf "Failed to retrieve time due to %s\n%!" (Printexc.to_string e);
Pdfe.log (Printf.sprintf "Failed to retrieve time due to %s\n" (Printexc.to_string e));
{_tm_sec = 0;
_tm_min = 0;
_tm_hour = 0;

View File

@ -51,7 +51,7 @@ let typeset_table_of_contents ~font ~fontsize ~title ~bookmark pdf =
| Cpdfembed.ExistingNamedFont -> raise (Pdf.PDFError "Cannot use existing font with -table-of-contents")
in
let marks = Pdfmarks.read_bookmarks pdf in
if marks = [] then (Printf.eprintf "No bookmarks, not making table of contents\n%!"; pdf) else
if marks = [] then (Pdfe.log "No bookmarks, not making table of contents\n"; pdf) else
let f, fs = (font, fontsize) in
let _, bfs as big = (font, fontsize *. 2.) in
let firstpage = hd (Pdfpage.pages_of_pagetree pdf) in

View File

@ -149,7 +149,7 @@ let read_encoding_table fmt length version b =
| 6 ->
if !dbg then Printf.printf "read_encoding_table: format 6\n";
read_format_6_encoding_table b;
| n -> raise (Pdf.PDFError "read_encoding_table: format %i not known\n%!")
| n -> raise (Pdf.PDFError "read_encoding_table: format %i not known\n")
let read_loca_table indexToLocFormat numGlyphs b =
match indexToLocFormat with