使用Perl和PDF :: API2生成多页PDF的最佳方法是什么?

时间:2011-02-25 15:02:30

标签: perl pdf

我一直在使用PDF :: API2模块来编写PDF。我在一家仓储公司工作,我们正在尝试从文本装箱单转换到PDF装箱单。装箱单包含单个订单所需的物料清单。它工作得很好,但我遇到了一个问题。目前我的程序生成单页PDF,一切正常。但现在我意识到如果订单中有超过30个项目,PDF将需要多个页面。我试图想出一个简单的方法来做到这一点,但却找不到一个。我唯一能想到的就是创建另一个页面,并且如果有多个页面,则需要重新定义行项目坐标的逻辑。所以我试图看看是否有一种不同的方法或我遗漏的东西可能有所帮助,但我并没有在CPAN上找到任何东西。

基本上,我需要创建单页PDF,除非有> 30项。然后它需要是多个。

我希望这很有道理,任何帮助都会非常感激,因为我对编程比较陌生。

4 个答案:

答案 0 :(得分:3)

由于您已经拥有适用于单页PDF的代码,因此将其更改为适用于多页PDF的应该不会太难。

尝试这样的事情:

use PDF::API2;

sub create_packing_list_pdf {
    my @items = @_;
    my $pdf = PDF::API2->new();
    my $page = _add_pdf_page($pdf);

    my $max_items_per_page = 30;
    my $item_pos = 0;
    while (my $item = shift(@items)) {
        $item_pos++;

        # Create a new page, if needed
        if ($item_pos > $max_items_per_page) {
            $page = _add_pdf_page($pdf);
            $item_pos = 1;
        }

        # Add the item at the appropriate height for that position
        # (you'll need to declare $base_height and $line_height)
        my $y = $base_height - ($item_pos - 1) * $line_height;

        # Your code to display the line here, using $y as needed
        # to get the right coordinates
    }

    return $pdf;
}

sub _add_pdf_page {
    my $pdf = shift();

    my $page = $pdf->page();

    # Your code to display the page template here.
    #
    # Note: You can use a different template for additional pages by
    # looking at e.g. $pdf->pages(), which returns the page count.
    #
    # If you need to include a "Page 1 of 2", you can pass the total
    # number of pages in as an argument:
    # int(scalar @items / $max_items_per_page) + 1

    return $page;
}

主要是从订单项中拆分页面模板,这样您就可以轻松启动新页面,而无需重复代码。

答案 1 :(得分:2)

PDF :: API2是低级别的。它没有您认为文档所需的大部分内容,例如边距,块和段落。因此,我担心你将不得不艰难地做事。您可能想要查看PDF :: API2 :: Simple。它可能符合您的标准,并且使用起来很简单。

答案 2 :(得分:1)

我使用PDF::FromHTML进行类似的工作。似乎是reasonable选择,我想我手动定位不是太大。

答案 3 :(得分:1)

最简单的方法是使用PDF-API2-Simple

my @content;
my $pdf = PDF::API2::Simple->new(file => "$name");
$pdf->add_font('Courier');
$pdf->add_page();
foreach $line (@content)
{
    $pdf->text($line, autoflow => 'on');
}
$pdf->save();
相关问题