FPDF - PHP로 PDF 만들기 5

[adsense]

목차

이 장에서는 테이블 만드는 방법에 대해서 쉽게 알려줍니다.

< ?php
require('fpdf.php');

class PDF extends FPDF
{
	//데이타를 읽는다
	function LoadData($file)
	{
		//파일을 줄단위로 읽어온다
		$lines=file($file);
		$data=array();
		foreach($lines as $line)
			$data[]=explode(';',chop($line));
		return $data;
	}

	//간단한 테이블
	function BasicTable($header,$data)
	{
		//헤더
		foreach($header as $col)
			$this->Cell(40,7,$col,1);
		$this->Ln();
		//데이터
		foreach($data as $row)
		{
			foreach($row as $col)
				$this->Cell(40,6,$col,1);
			$this->Ln();
		}
	}

	//더 나은 모양
	function ImprovedTable($header,$data)
	{
		//칼럼 너비
		$w=array(40,35,40,45);
		//헤더
		for($i=0;$i < count($header); $i++)
			$this->Cell($w[$i],7,$header[$i],1,0,'C');
		$this->Ln();
		//데이터
		foreach($data as $row)
		{
			$this->Cell($w[0],6,$row[0],'LR');
			$this->Cell($w[1],6,$row[1],'LR');
			$this->Cell($w[2],6,number_format($row[2]),'LR',0,'R');
			$this->Cell($w[3],6,number_format($row[3]),'LR',0,'R');
			$this->Ln();
		}
		//Closure line
		$this->Cell(array_sum($w),0,'','T');
	}

	//색상이 들어간 테이블
	function FancyTable($header,$data)
	{
		//색상, 라인너비, 굵은 글씨 설정
		$this->SetFillColor(255,0,0);
		$this->SetTextColor(255);
		$this->SetDrawColor(128,0,0);
		$this->SetLineWidth(.3);
		$this->SetFont('','B');

		//헤더
		$w=array(40,35,40,45);
		for($i=0;$i < count($header); $i++)
		{
			$this->Cell($w[$i],7,$header[$i],1,0,'C',1);
		}
		$this->Ln();

		//색상과 글꼴 설정을 원래대로
		$this->SetFillColor(224,235,255);
		$this->SetTextColor(0);
		$this->SetFont('');

		//데이터
		$fill=0;
		foreach($data as $row)
		{
			$this->Cell($w[0],6,$row[0],'LR',0,'L',$fill);
			$this->Cell($w[1],6,$row[1],'LR',0,'L',$fill);
			$this->Cell($w[2],6,number_format($row[2]),'LR',0,'R',$fill);
			$this->Cell($w[3],6,number_format($row[3]),'LR',0,'R',$fill);
			$this->Ln();
			$fill=!$fill;
		}
		$this->Cell(array_sum($w),0,'','T');
	}
}

$pdf=new PDF();

//칼럼 제목
$header=array('Country','Capital','Area (sq km)','Pop. (thousands)');

//데이터 읽기
$data=$pdf->LoadData('countries.txt');
$pdf->SetFont('Arial','',14);
$pdf->AddPage();
$pdf->BasicTable($header,$data);
$pdf->AddPage();
$pdf->ImprovedTable($header,$data);
$pdf->AddPage();
$pdf->FancyTable($header,$data);
$pdf->Output();
?>

[데모보기]

테이블은 셀의 집합이므로, 셀을 다루어서 테이블을 만듭니다.

첫번째 예제는 가장 간단한 방법으로 만들어졌습니다: 모든 프레임은 단순한 형태의 외곽선, 동일한 크기, 왼쪽 정렬이 되어있습니다. 간단하지만 매우 빠른 결과를 얻을 수 있습니다.두번째 예제는 몇가지를 개선했습니다: 각 칼럼은 서로 다른 너비를 가지며, 제목줄은 중간정렬, 수치는 오른쪽 정렬이 되도록 했습니다. 또한, 가로줄을 제거했습니다. 가로줄을 제거하는 것은 Cell() 메소드에 셀의 가장자리 그리는 법을 지정하는 외곽선 파라미터를 부여하면 됩니다. 파라미터로는 왼쪽(L)과 오른쪽(R)이 있습니다. 하지만 여전히, 테이블을 마무리 하는 가로선이 문제로 남아있습니다. 두가지 방법이 있습니다: 경계선 파라미터에 LRB를 이용할 때 루프에서 마지막 줄을 체크하거나, 혹은 여기서 했던 것처럼 루프가 종료된 후에 줄을 하나 더 추가하는 것입니다.

세번째 테이블은 색상을 사용한다는 점만 제외하면 두번째와 비슷합니다. 셀배경(Fill), 글꼴, 라인 등의 색상은 쉽게 지정할 수 있습니다. 줄의 색상은 투명/불투명을 변경하고 셀에 색상을 채움으로써 변경할 수 있습니다.

댓글을 남겨주세요

This site uses Akismet to reduce spam. Learn how your comment data is processed.