FPDF - PHP로 PDF 만들기 3

[adsense]

목차

3. 줄바꿈과 색상

다음은 양쪽 정렬된 문단을 출력하는 예제입니다. 이 예제는 색상의 사용법도 같이 다룹니다.

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

class PDF extends FPDF
{
	function Header()
	{
		global $title;

		//Arial bold 15
		$this->SetFont('Arial','B',15);
		//제목의 너비와 위치 계산
		$w=$this->GetStringWidth($title)+6;
		$this->SetX((210-$w)/2);
		//프레임과 배경색, 글꼴 색상 지정
		$this->SetDrawColor(0,80,180);
		$this->SetFillColor(230,230,0);
		$this->SetTextColor(220,50,50);
		//프레임의 두께 지정 (1 mm)
		$this->SetLineWidth(1);
		//제목
		$this->Cell($w,9,$title,1,1,'C',1);
		//줄바꿈
		$this->Ln(10);
	}

	function Footer()
	{
		//하단에서 1.5 cm 지점
		$this->SetY(-15);
		//Arial italic 8
		$this->SetFont('Arial','I',8);
		//회색으로 글꼴 색상 지정
		$this->SetTextColor(128);
		//페이지 번호
		$this->Cell(0,10,'Page '.$this->PageNo(),0,0,'C');
	}

	function ChapterTitle($num,$label)
	{
		//Arial 12
		$this->SetFont('Arial','',12);
		//배경색
		$this->SetFillColor(200,220,255);
		//제목
		$this->Cell(0,6,"Chapter $num : $label",0,1,'L',1);
		//줄바꿈
		$this->Ln(4);
	}

	function ChapterBody($file)
	{
		//텍스트를 읽어들임
		$f=fopen($file,'r');
		$txt=fread($f,filesize($file));
		fclose($f);
		//Times 12
		$this->SetFont('Times','',12);
		//양쪽정렬된 문단 출력
		$this->MultiCell(0,5,$txt);
		//줄바꿈
		$this->Ln();
		//이탤릭
		$this->SetFont('','I');
		$this->Cell(0,5,'(end of excerpt)');
	}

	function PrintChapter($num,$title,$file)
	{
		$this->AddPage();
		$this->ChapterTitle($num,$title);
		$this->ChapterBody($file);
	}
}

$pdf=new PDF();
$title='20000 Leagues Under the Seas';
$pdf->SetTitle($title);
$pdf->SetAuthor('Jules Verne');
$pdf->PrintChapter(1,'A RUNAWAY REEF','20k_c1.txt');
$pdf->PrintChapter(2,'THE PROS AND CONS','20k_c2.txt');
$pdf->Output();
?>

[데모보기]

GetStringWidth() 메소드를 이용하면 현재 폰트에서의 문자열의 길이를 얻을 수 있습니다. 이 길이는 제목 주변에 그릴 프레임의 너비와 위치 등을 구하는데 사용합니다. SetDrawColor(), SetFillColor(), SetTextColor() 등을 이용해서 색상을 설정했으며, SetLineWidth() 메소드를 이용해서 선의 굵기를 1mm로 정해주었습니다(기본값은 2mm). 마지막이 되어서야 cell을 출력했는데, 가장 마지막 파라미터가 1로 설정되면 색상이 채워진 cell을 그립니다. 각 문단을 출력하기 위해 MultiCell() 메소드를 사용하는데, 이 메소드를 사용하면 문자가 각 라인의 끝에 도달할 때 자동으로 줄바꿈을 하고 현재의 cell 아래에 새로운 cell을 생성합니다. 글자는 기본적으로 양쪽 정렬(justified)이 적용됩니다.

위 코드를 보면 두 가지의 문서속성(혹은 문서정보) - 제목(SetTitle())과 작성자(SetAuthor()) - 이 정의되어있습니다. 문서속성은 두가지 방법으로 볼 수 있는데, 하나는 Acrobat Reader에서 메인메뉴의 파일(File) -> 문서 속성(Document info) -> 설명(General)으로 가서 보는 것이고, 다른 하나는 플러그인에서도 가능한 방법으로 세로 스크롤바 상단(화면상에선 우측 상단)의 화살표를 클릭해서 문서 속성(Document info)을 선택하는 것입니다.

댓글을 남겨주세요

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