Skip to content

Instantly share code, notes, and snippets.

@jef-sure
Created May 25, 2017 16:42
Show Gist options
  • Save jef-sure/23e967e7c843d722601ef7cb8669f672 to your computer and use it in GitHub Desktop.
Save jef-sure/23e967e7c843d722601ef7cb8669f672 to your computer and use it in GitHub Desktop.
use PDF::Haru;
use strict;
use warnings;
# create new document
my $pdf = PDF::Haru::New();
#$pdf->LoadTTFontFromFile("/usr/share/fonts/truetype/msttcorefonts/arial.ttf",1);
# add page
my $page = $pdf->AddPage();
# set page size and orientation
$page->SetSize(HPDF_PAGE_SIZE_A4, HPDF_PAGE_PORTRAIT);
my $font = $pdf->GetFont("Helvetica", "StandardEncoding");
$page->SetFontAndSize($font, 24);
my $page_width = $page->GetWidth();
my $page_height = $page->GetHeight();
my $zero_width = $page->TextWidth("0");
my $template_width = $page->TextWidth("0" x 6);
sub one_equation {
my ($x, $y) = @_;
my $sign = ("-", "+")[rand 2];
my ($a, $b);
if ($sign eq "-") {
$a = 1 + int rand 20;
$b = 1 + int rand $a - 1;
} else {
$a = 1 + int rand 19;
$b = 1 + int rand 18 - $a;
}
my $text = "$a $sign $b";
my $tw = $page->TextWidth($text);
my $xo = ($template_width - $tw) / 2;
$page->BeginText();
$page->TextOut($x + $xo, $y, $text);
$page->TextOut($x + $template_width, $y, "=");
$page->EndText();
}
for (my $x = 0; $x < $page_width; $x += int($page_width / 3)) {
for (my $y = 30; $y < $page_height - $page_height / 20; $y += int $page_height / 20) {
one_equation($x, $y);
}
}
# save the document to a file
$pdf->SaveToFile("filename.pdf");
# cleanup
$pdf->Free();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment