html2pdf_chromium.pl 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #!/usr/bin/perl
  2. # Author: Trizen
  3. # Date: 16 April 2023
  4. # https://github.com/trizen
  5. # HTML|URL to PDF converter, with JavaScript support.
  6. # Using the following tool:
  7. # chromium -- for converting HTML to PDF
  8. use 5.010;
  9. use strict;
  10. use warnings;
  11. use open IO => ':utf8', ':std';
  12. use Getopt::Long qw(GetOptions);
  13. my $js_delay = 10000;
  14. sub usage {
  15. my ($exit_code) = @_;
  16. $exit_code //= 0;
  17. print <<"EOT";
  18. usage: $0 [options] [input.html | URL] [output.pdf]
  19. options:
  20. --js-delay=i : wait some milliseconds for JavaScript to finish (default: $js_delay)
  21. EOT
  22. exit($exit_code);
  23. }
  24. GetOptions('js-delay=i' => \$js_delay,
  25. "h|help" => sub { usage(0) },)
  26. or die("Error in command line arguments\n");
  27. my $input_html_file = $ARGV[0] // usage(2);
  28. my $output_pdf_file = $ARGV[1] // "output.pdf";
  29. say ":: Converting HTML to PDF...";
  30. # Reference:
  31. # https://peter.sh/experiments/chromium-command-line-switches/
  32. system(
  33. qw(
  34. chromium
  35. --headless
  36. --disable-gpu
  37. --no-pdf-header-footer
  38. --disable-pdf-tagging
  39. --enable-local-file-accesses
  40. --run-all-compositor-stages-before-draw
  41. ),
  42. "--virtual-time-budget=$js_delay",
  43. "--print-to-pdf=$output_pdf_file",
  44. $input_html_file,
  45. );
  46. if ($? != 0) {
  47. die "`chromium` failed with code: $?";
  48. }
  49. say ":: Done!"