2024-03-27 Convert text file to PDF

I just couldn't find a good way to turn a text file into a PDF. Within Emacs, ps-print-buffer is hard to configure and my two specific problems were the following:

I wasted some time trying to write something in Bash, turned to Perl and wasted some more time trying to figure out why the encodings were all wrong except when the encodings were OK but Perl gave me a warning for every multi-byte character. So frustrating.

The solution ended up not being decoding and encoding the bytes in the Perl script but to use the --encoding option for weasyprint. In this case, it wasn't Perl's fault, it was my fear of Perl's encoding issues that led my down endless variations of binmode, :utf8, decode_utf8 and encode_utf8. But I think I have it, now.

This is what I ended up with:

I created a script called to-pdf with the following:

#!/usr/bin/env perl
use Modern::Perl;
use File::Basename;

if (@ARGV == 0) {
  die "Usage: to-pdf file.txt ...\n";
}

for (@ARGV) {
  open(my $text, "<", $_) or die "Cannot read $_\n";
  my ($name, $path, $suffix) = fileparse($_, ".txt");
  open(my $html, "|-") || exec "weasyprint", "--encoding", "utf-8", "-", "$path$name.pdf";

  print $html <<'BEG';


BEG

  for (<$text>) { print $html $_ }; # copy text

  print $html <<'END';
END }

​#Administration ​#Printing ​#PDF

=> paps

paps /var/log/README | ps2pdf - test.pdf
xdg-open test.pdf

Actually, on my system the default font is too big. I had to use this:

paps --font="Iosevka 12" /var/log/README | ps2pdf - test.pdf

Cool!

Proxy Information
Original URL
gemini://alexschroeder.ch/2024-03-27-to-pdf
Status Code
Success (20)
Meta
text/gemini
Capsule Response Time
161.018555 milliseconds
Gemini-to-HTML Time
0.430295 milliseconds

This content has been proxied by September (3851b).