Skip to content

Instantly share code, notes, and snippets.

@jberger
Last active June 26, 2020 04:27
Show Gist options
  • Save jberger/4a24545aa1652239be712f65d9f9cc72 to your computer and use it in GitHub Desktop.
Save jberger/4a24545aa1652239be712f65d9f9cc72 to your computer and use it in GitHub Desktop.
Extracted from old code, not necessarily recommended
sub _html_to_pdf {
my $cb = ref $_[-1] eq 'CODE' ? pop : undef;
my ($c, $html, $opts) = @_;
$opts||={};
require PDF::WebKit;
PDF::WebKit->configure(sub {
# default `which wkhtmltopdf`
my $exe= $c->executable( 'wkhtmltopdf' );
$_->wkhtmltopdf($exe);
});
my $enc = Mojo::Util::encode 'UTF-8', $html;
my $kit = PDF::WebKit->new(
\$enc,
'page-size' => 'Letter',
'print-media-type' => 'yes',
%{$opts},
);
return $kit->to_pdf unless $cb; #blocking
require Mojo::IOLoop;
require Mojo::IOLoop::ForkCall;
my $fc = Mojo::IOLoop::ForkCall->new;
Mojo::IOLoop->delay(
sub { $fc->run(sub{ $kit->to_pdf }, shift->begin) },
sub {
my ($delay, $err, $pdf) = @_;
die $err if $err;
$c->$cb(undef, $pdf);
},
)->catch(sub{ $c->$cb($_[1], undef) })->wait;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment