【问题标题】:What's the best method to generate Multi-Page PDFs with Perl and PDF::API2?使用 Perl 和 PDF::API2 生成多页 PDF 的最佳方法是什么?
【发布时间】:2011-02-25 15:02:30
【问题描述】:

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

基本上,除非有超过 30 个项目,否则我需要创建单页 PDF。那么它需要是多个。

我希望这是有道理的,任何帮助都将不胜感激,因为我对编程还比较陌生。

【问题讨论】:

    标签: perl pdf


    【解决方案1】:

    由于您已经拥有适用于单页 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;
    }
    

    主要是将页面模板与订单项分开,这样您就可以轻松地开始新页面而无需重复代码。

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        【解决方案3】:

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

        【讨论】:

          【解决方案4】:

          最简单的方法是使用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();
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2017-08-06
            • 2020-03-11
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多