【问题标题】:TCPDF : Set margin between several images get by 'foreach' methodTCPDF:通过“foreach”方法设置多个图像之间的边距
【发布时间】:2015-09-13 03:53:51
【问题描述】:

我正在使用 TCPDF,我正在尝试将行和列设置为通过 foreach 方法获取的 pdf 图像上的排版。 这是我的代码:

$imagesValues = get_post_meta( $post->ID, 'image');
foreach ( $imagesValues as $imageItem ) { 
    foreach ( $imageItem as $imageID ) { 
        $imageURL = wp_get_attachment_url($imageID); // gets photo URL
        $pdf->Image($gallerieURL, $x, $y, $w, $h, 'JPG', '', '', false, 300, '', false, false, 0, false, false, false); 
    } 
}

编辑

我已经做到了:

$x = 115;
$y = 35;
$w = 25;
$h = 50;
foreach ( $imagesValues as $imageItem) { 
  foreach ( $imageItem as $imageID) { 
    $imageURL = wp_get_attachment_url($imageID); // gets photo URL
    $x = 115;
    for ($i = 0; $i < 2; ++$i) {
      $pdf->Image( $imageURL, $x, $y, $w, $h, 'JPG', '', '', false, 300, '', false, false, 0, false, false, false);
      $x += 27; // new column
    }
    $y += 52; // new row
  }   
}

但相同的图像会重复自己

【问题讨论】:

  • 您可以尝试使用 $w 和 $h 以及 $fitbox,请参阅此处:tcpdf.org/doc/code/…
  • 是的,但问题是有几个图像。如何为每个参数设置不同的参数?
  • 您之前已经定义了这些变量:$w, $h 所以只需在循环中重新定义它们。如果您将这些包含在数据源中会更容易,所以也许$imageValues 也可以在其中包含这些信息,从而使其在循环迭代中可用?如果我所说的让您感到困惑,请阅读多维数组。
  • 非常感谢,我现在就试试这个!
  • 没问题,如果你遇到困难我可以给你一个简单的例子,让我知道。

标签: php foreach tcpdf


【解决方案1】:

我建议您将数据源更改为:

array (
  0 => array (
    'w'=>320,
    'h'=>240
  ),
  1 => array (
    'w'=>300,
    'h'=>250
  ) 
)

不过没关系,你只需要在这里做一点计算:

// Assuming that 115 is the width of the row
$x = 0;
// Assuming that 52 is the height of each
$y = 0;
$w = 25;
$h = 50;

// We start on 1 image, there are 4 images in each row
$imageCounter = 1;

foreach ( $imagesValues as $imageItem) { 
  foreach ( $imageItem as $imageID) { 
    // gets photo URL
    $imageURL = wp_get_attachment_url($imageID);
    // Calculate the column and row specifications
    switch ($imageCounter) {
      // First column
      case 1: 
        $x = 0;
        $imageCounter ++;
      break;
      case 2: 
        $x = 27;
        $imageCounter ++;
      break;
      case 3: 
        $x = 54;
        $imageCounter ++;
      break;
      case 4: 
        $x = 81;
        // Reset the image counter back to 1 for the new row
        $imageCounter = 1;
        // New row
        $y += 52;
      break;
    }
    $pdf->Image( $imageURL, $x, $y, $w, $h, 'JPG', '', '', false, 300, '', false, false, 0, false, false, false);
  }       
}

【讨论】:

  • 哎呀,看到更新。您只需要在该行的第 1、第 2 和第 3 张图像上增加计数器。