PHP code example of ren1244 / pdfwriter

1. Go to this page and download the library: Download ren1244/pdfwriter library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

ren1244 / pdfwriter example snippets


$pdf = new PDFWriter; //建立 PDFWriter 物件
$pdf->addPage('A4'); //添加空白頁面
$pdf->output();

//新增寬 20 cm 高 15 cm 的頁面
$pdf->addPage(200, 150);

//新增一張 A4 大小的頁面,預設是直向
$pdf->addPage('A4');

//新增一張 A4 大小的頁面,橫向
$pdf->addPage('A4H');

$fp = fopen('output.pdf', 'wb');
$pdf->output($fp);
fclose($fp);

// 把「目前單位」設定為 "cm"
PageMetrics::$unit = "cm";

// 把 0.5 pt 轉換為「目前單位」
PageMetrics::getUnit(0.5);

// 把 0.25 「目前單位」轉換 pt
PageMetrics::getPt(0.25);

$pdf = new PDFWriter;
$pdf->addPage('A4');

// 添加字型(此時會自動設定目前字型為 Times-Roman 12pt)
$pdf->font->addFont('Times-Roman');
// 設定字型(Times-Roman 14pt)
$pdf->font->setFont('Times-Roman', 14);
// 設定要寫入的矩形區域: left, top, width, height (單位是「目前單位」,此時是 mm)
$pdf->text->setRect(10, 10, 100, 100);
//寫入文字
$pdf->text->addText('Hello');

$pdf->output();

$pdf->font->setFont([
    'Times-Roman' => 12, // 優先使用 Times-Roman 12pt
    'Noto-Sans' => 14,   // 如果缺字,用 Noto-Sans 14pt 替代
]);

$pdf = new PDFWriter;
$pdf->addPage('A4');

// 這邊用到自訂字型,請參考前面的說明
// 第二個參數設為 true 開啟直書功能
$pdf->font->addFont('SourceHanSansTC-Regular', true);
// 設定字型(Times-Roman 14pt)
$pdf->font->setFont('SourceHanSansTC-Regular', 14);
// 設定要寫入的矩形區域: left, top, width, height (單位是「目前單位」,此時是 mm)
$pdf->text->setRect(10, 10, 100, 100);
// 用 addTextV 寫入直書文字
$pdf->text->addTextV("關關雎鳩,在河之洲。\n窈窕淑女,君子好逑。");

$pdf->output();

/**
 * 畫一條從 (10, 10) 到 (20, 30) 的直線,線寬是 1 pt
 * 這邊單位都是「目前單位」,所以指定線寬時使用 PageMetrics::getUnit
 */
$pdf->postscriptGragh->addPath('10 10 m 20 30 l S', PageMetrics::getUnit(1));

// 把 jpg 圖片畫在 ($x, $y) 的位置,長寬依照原本的尺寸
$pdf->image->addImage("example.jpg", $x, $y);

// 把 png 圖片畫在 ($x, $y) 的位置,並指定長寬
$pdf->image->addImage("example.png", $x, $y, $width, $height);

/** 
 * 把 png 圖片畫在 ($x, $y) 的位置
 * 當長寬只指定一個的時候,另一個請設定為 false,此時會等比例縮放
 */
$pdf->image->addImage("example.png", $x, $y, false, $height);

$imageContent = file_get_contents("example.png");
$pdf->image->addImageRaw($imageContent, $x, $y, $width, $height);

// 建立一個書籤,當點擊時會跳到第 2 頁,從頂部往下算 10 unit 的位置
$pdf->addOutline("第一章", 2, 10);

/**
 * 建立一個書籤,當點擊時會跳到第 3 頁,從頂部往下算 10 unit 的位置
 * 樣式被設定為「斜體 + 粗體」,顏色為紅色(#FF0000)
 */
$pdf->addOutline("第二章", 3, 10, Outline::ITALIC | Outline::BOLD, "FF0000");

// 紀錄 addOutline 回傳的值,這是一個 Outline 物件
$chapter1 = $pdf->addOutline("第一章", 2, 10);

// Outline 物件本身也可以建立書籤,參數最多可以有 5 個,說明參考「簡易書籤」的部分
$chapter1->addOutline("第一節", 2, 15);

// 若不指定第幾頁,則點擊後無任何效果,可以單純作為資料夾
$other = $pdf->addOutline("其他");
$other->addOutline("參考文件", 10, 10);
shell
php script/addFont.php {filename} [{outname}]