2011-02-25 80 views
2

我一直在使用PDF :: API2模塊來編程PDF。我在一家倉儲公司工作,我們正在嘗試從文本包裝單轉換爲PDF包裝單。裝箱單有單一訂單所需的物品清單。它運作良好,但我遇到了一個問題。目前我的程序生成一個頁面的PDF,並且它工作正常。但是現在我意識到,如果訂單中有超過30個項目,PDF將需要多個頁面。我試圖想到一個簡單的(ish)方法來做到這一點,但不能拿出一個。我能想到的唯一事情就是創建另一個頁面,並且在有多個頁面的情況下具有重新定義行項目座標的邏輯。所以我試圖看看是否有不同的方法或者我錯過了一些可以幫助我的東西,但是我沒有真正在CPAN上找到任何東西。什麼是使用Perl和PDF :: API2生成多頁PDF的最佳方法?

基本上,我需要創建一個頁面的PDF,除非有> 30項。那麼它將需要多重。

我希望這是有道理的,任何幫助都將不勝感激,因爲我對編程比較陌生。

回答

2

PDF :: API2是低級的。它並不包含大部分您認爲對文檔必需的內容,例如邊距,塊和段落。因此,我擔心你將不得不以艱難的方式做事。你可能想看看PDF :: API2 :: Simple。它可能符合您的標準,使用起來很簡單。

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

的最簡單的方法是使用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(); 
相關問題