logo

Blade (PHP)

This guide explains how to generate an HTML string using PHP's Blade template engine and convert it to PDF by sending it to pdfg's API.

Technical Overview

  1. Create a Blade template
  2. Pass data to the template to generate an HTML string
  3. Send the generated HTML string to pdfg's API to convert it to PDF

Sample

Defining the Template

{{-- templates/invoice.blade.php --}}
<!DOCTYPE html>
<html>
  <head></head>
  <body>
    <div class="invoice">
      <h1>Invoice</h1>
      <table>
        <thead>
          <tr>
            <th>Item</th>
            <th>Amount</th>
          </tr>
        </thead>
        <tbody>
          @foreach ($items as $item)
            <tr>
              <td>{{ $item['name'] }}</td>
              <td>{{ $item['price'] }} USD</td>
            </tr>
          @endforeach
        </tbody>
      </table>
      <p class="total">Total: {{ $total }} USD</p>
    </div>
  </body>
</html>

Using the Template and Generating PDF

<?php
// generate_pdf.php
require 'vendor/autoload.php';
use Illuminate\View\Factory;
use Illuminate\View\FileViewFinder;
use Illuminate\View\Engines\CompilerEngine;
use Illuminate\View\Engines\EngineResolver;
use Illuminate\View\Compilers\BladeCompiler;
use Illuminate\Filesystem\Filesystem;

// Configure Blade engine
$files = new Filesystem;
$compiler = new BladeCompiler($files, 'cache');
$resolver = new EngineResolver;
$resolver->register('blade', function () use ($compiler) {
    return new CompilerEngine($compiler);
});
$finder = new FileViewFinder($files, ['templates']);
$factory = new Factory($resolver, $finder, new Illuminate\Events\Dispatcher);

// Prepare data
$items = [
    ['name' => '商品A', 'price' => 1000],
    ['name' => '商品B', 'price' => 2000],
];
$total = 3000;

// Generate HTML string
$html = $factory->make('invoice', [
    'items' => $items,
    'total' => $total,
])->render();

// Request to pdfg's API
$ch = curl_init('https://api.pdfg.net/v1');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Authorization: Bearer YOUR_API_KEY'
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
    'html' => $html,
    'pdfOptions' => [
        'format' => 'A4'
    ]
]));

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

// Save PDF
if ($httpCode === 200) {
    file_put_contents('invoice.pdf', $response);
}