Mojo::PDF - Generate PDFs with the goodness of Mojo!


    # Just render text. Be sure to call ->end to save your document
    Mojo::PDF->new('mypdf.pdf')->text('Viva la Mojo!', 306, 396)->end;

    # Let's get fancy pants:
    Mojo::PDF->new('myawesome.pdf', page_size => [612, 792])

        ->mixin('template.pdf')   # add a pre-made PDF page from a template

        # Render text with standard fonts
        ->font('Times-Bold')->size(24)->color(0, 0, .7)
            ->text('Mojo loves PDFs', 612/2, 500, 'center')

        # Render text with custom TTF fonts
            galaxie    => 'fonts/GalaxiePolaris-Book.ttf',
            galaxie_it => 'fonts/GalaxiePolaris-BookItalic.ttf',
            ->text('Weeee', 20.4, 75 )
            ->text('eeee continuing same line!')
            ->text('Started a new line!', 20.4 )

        # Render a table
            at        => [20.4, 268],
            data      => [
                [ qw{Product  Description Qty  Price  U/M} ],



Mojotastic, no-nonsense PDF generation.


Note: due to the way PDF::Reuse, which is used under the hood, is implemented, it's not possible to simultaneously handle multiple Mojo::PDF objects, as all of the internal PDF::Reuse output variables are shared. Thus, Mojo::PDF merely provides a more convenient interface for PDF::Reuse, rather than being a truly object-oriented way to produce PDFs.


Unless otherwise indicated, all methods return their invocant.


    my $pdf = Mojo::PDF->new('myawesome.pdf');
    my $pdf = Mojo::PDF->new('myawesome.pdf', page_size => [$x, $y]);

Creates a new Mojo::PDF object. Takes one mandatory argument: the filename of the PDF you want to generate, followed by optional key/value attributes.

If filename is not specified or undef, the PDF will be output to STDOUT. An IO::String object can be specified to output the PDF into a variable:

    # IO::String
    my $pdf = Mojo::PDF->new(IO::String->new(my $pdf_bytes));
    $pdf->text('Viva la Mojo!', 306, 396)->end;

    # Then use the bytes somewhere:
    open my $fh, '>', 'the.pdf' or die $!;
    print $fh $pdf_bytes;
    close $fh;


Array reference containing the XxY page size in pixels. Defaults to [612, 792] (US-Letter).



Finish rendering your PDF and save it.


        galaxie    => 'fonts/GalaxiePolaris-Book.ttf',
        galaxie_it => 'fonts/GalaxiePolaris-BookItalic.ttf',

Adds TTF fonts to the document. Key/value pairs specify the arbitrary name of the font (for you to use with "font") and the path to the TTF file.

You cannot use any of the names of the "DEFAULT FONTS" for your custom fonts.


    $pdf->color(.5, .5, .3);
    $pdf->color('#abc');   # same as #aabbcc
    $pdf->color;           # same as #000

Specifies active color. Takes either an RGB tuple or a hex colour. Defaults to black.




Sets active font family. Takes the name of either one of the "DEFAULT FONTS" or one of the custom fonts included with "add_fonts". Note that "DEFAULT FONTS" do not support Unicode.



    $pdf->mixin('template.pdf', 3);

Adds a page from an existing PDF to your currently active page, so you can use it as a template and render additional things on it. Takes one mandatory argument, the filename of the PDF to include. An optional second argument specifies the page number to include (starting from 1), which defaults to the first page.

Note: If you get an error along the lines of can't be used as a form. See the documentation under prForm how to concatenate streams, it likely means the PDF is not compatible with this feature. The details are described in PDF::Reuse::prForm documentation. I had to convert my InDesign-generated PDFs with Win2PDF "printer" to get them to work with this method.



Add a new blank page to your document and sets it as the currently active page.


        'cat.jpg',     # use scalar ref (\$data) to provide raw bytes instead
        x     => 42,   # place at X points from the left of page
        y     => 100,  # place at Y points from the top  of page
        scale => .5    # scale image by this factor

Add a JPEG image to the active page (other formats currently unsupported). Takes the filename (string) or raw image bytes (in a scalar ref) as the first argument, the rest are key-value pairs: the x for X position, y for Y position, and scale as the scale factor for the image.


    $pdf->raw("0 0 m\n10 10 l\nS\nh\n");

Use prAdd to "add whatever you want to the current content stream".

See, for example, section 4.4.1 on page 196 of the Adobe Acrobat SDK PDF Reference Manual.


        bold  => { re => qr/\*\*(.?)\*\*/, font => 'galaxie_bold' },
        shiny => {
            re    => qr/!!(.?)!!/,
            font  => 'galaxie_bold',
            color => '#FBBC05',
            size  => 30,
    ->text('Normal **bold text** lalalala !!LOOK SHINY!!')
    ->rule( shiny => undef )
    ->text('!!no longer shiny!!')

Sets rules for bits of text when rendering with "text" or "table". Available overrides are "font", "color", and "size". To disable a rule, set its value to undef.



    $pdf->size; # set to 12

Specifies active font size in points. Defaults to 12 points.


        at        => [20.4, 268],
        data      => [
            [ qw{Product  Description Qty  Price  U/M} ],

        border         => [.5, '#CFE3EF'],
        header         => 'galaxie_bold',
        max_height     => [ 744, sub {
            my ( $data, $conf, $pdf ) = @_;
            $conf->{at}[1] = 50;
        } ],
        min_width      => 571.2,
        padding        => [3, 6],
        row_height     => 24,
        str_width_mult => 1.1,

Render a table on the current page. Takes these arguments:


    at => [20.4, 268],

An arrayref with X and Y point values of the table's top, left corner.


    data => [
        [ qw{Product  Description Qty  Price  U/M} ],

An arrayref of rows, each of which is an arrayref of strings representing table cell values. Setting "header" will render first row as a table header. Cells that are undef/empty string will not be rendered. Text in cells is rendered using "text".


    border => [.5, '#CFE3EF'],

Optional. Takes an arrayref with the width (in points) and colour of the table's borders. Color allows the same values as "color" method. Defaults to: [.5, '#ccc']

    header => 'galaxie_bold',

Optional. Takes the same value as "font". If set, the first row of /data will be used as table header, rendered centered using header font. Not set by default.


        at         => [20.4, 300],
        data       => $data,
        max_height => [ 744, sub {
            my ( $data, $conf, $pdf ) = @_;
            $conf->{at}[1] = 50; # start table higher on subsequent pages
            $pdf->page;          # start a new page
            $data;               # render remaining rows

Optional. Takes an arrayref with two arguments: the maximum height (in points) the table should reach and the callback to use when not all rows could fit. The return value of the callback will be used as the new collection of rows to render. The @_ will contain remaining rows to render, hashref of the options you've passed to table method, and the Mojo::PDF object.


    min_width => 571.2,

Optional. Table's minimum width in points (zero by default). The largest column will be widened to make the table at least this wide.


    padding => [3],          # all sides 3
    padding => [3, 6],       # top/bottom 3, left/right 6
    padding => [3, 6, 4],    # top 3, left/right 6, bottom 4
    padding => [3, 6, 4, 5], # top 3, right 6, bottom 4, left 5

Optional. Specifies cell padding (in points). Takes an arrayref of 1 to 4 numbers, following the same convention as the CSS property.


    row_height => 24,

Optional. Specifies the height of a row, in points. Defaults to 1.4 times the current font size.


    str_width_mult => 1.1,
    str_width_mult => { 10 => 1.1, 20 => 1.3, inf => 1.5 },

Optional. Cell widths will be automatically computed based on the width of the strings they contain. Currently, that computation works reliably only for the Times, Courier, and Helvetica "font" families. All other fonts will be computed as if they were sized same as Helvetica. For those cases, use str_width_mult as a multiplier for the detected character width.

You can use a hashref to specify different multipliers for strings of different lengths. The values are multipliers and keys specify the maximum length this multiplier applies to. You can use positive infinity (inf) too:

    str_width_mult => { 10 => 1.1, 20 => 1.3, inf => 1.5 },
    # mult is 1.1 for strings 0-10 chars
    # mult is 1.3 for strings 11-20 chars
    # mult is 1.5 for strings 20+ chars


    $p->text($text_string, $x, $y, $alignment, $rotation);

    $p->text('Mojo loves PDFs', 612/2, 500, 'center', 90);
    $p->text('Lorem ipsum dolor sit amet, ', 20 );
    $p->text('consectetur adipiscing elit!');

    use Text::Fold qw/fold_text/;
    $p->text( fold_text $giant_amount_of_text, 42 ); # new lines work!

Render text with the currently active "font", "size", and "color". $alignment specifies how to align the string horizontally on the $x point; valid values are left (default), center, and right. $rotation is the rotation of the text in degrees. You can use new line characters (\n) to render text on multiple lines.

Subsequent calls to text can omit $x and $y values with these effects: omit both to continue rendering where previous text finished; omit just $y, to render on the next line from previous call to text. Note: determination of the $x reliably works only for the Times, Courier, and Helvetica "font" families. All other fonts will be computed as if they were sized same as Helvetica.


These fonts are available by default. Note that they don't support Unicode.





You can use their abbreviated names:






PDF::Reuse, PDF::Create, and PDF::WebKit


Fork this module on GitHub:


To report bugs or request features, please use

If you can't access GitHub, you can email your request to bug-Mojo-PDF at



Stefan Adams


You can use and distribute this module under the same terms as Perl itself. See the LICENSE file included in this distribution for complete details.