PDF Invoice HTML Template
December 21, 2024 · AI Conversations
### HTML Template for MPDF
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Invoice</title>
<style>
body {
font-family: Arial, sans-serif;
line-height: 1.6;
}
.header, .footer {
text-align: center;
}
.content {
margin: 0 auto;
max-width: 800px;
}
.table {
width: 100%;
border-collapse: collapse;
}
.table th, .table td {
border: 1px solid #ddd;
padding: 8px;
}
.table th {
background-color: #f2f2f2;
text-align: left;
}
.right-align {
text-align: right;
}
</style>
</head>
<body>
<div class="header">
<h1>INVOICE</h1>
</div>
<div class="content">
<h2>Company Information</h2>
<p>feedback4you GmbH<br>
Birkenfeldstr. 8<br>
85649 Brunnthal<br>
Germany<br>
VAT: DE123451234<br>
Email: billing@feedback4you.com</p>
<h2>Customer Information</h2>
<p>Customer Name: [First Name] [Last Name]<br>
Address: [Address], [Zip Code] [City], [Country]<br>
Customer Number: 0001500<br>
Invoice Number: 2024/11/14/1<br>
Invoice Date: 14.11.2024</p>
<h2>Services</h2>
<table class="table">
<thead>
<tr>
<th>Service</th>
<th>Order ID</th>
<th>QTY</th>
<th>Price/Unit</th>
<th>Net</th>
<th>19% VAT</th>
<th>Gross</th>
</tr>
</thead>
<tbody>
<tr>
<td>[Project name 1]</td>
<td>[Order ID]</td>
<td>[QTY]</td>
<td>[Price/unit]</td>
<td>[Net]</td>
<td>[19% VAT]</td>
<td>[Gross]</td>
</tr>
<tr>
<td>[Project name 2]</td>
<td>[Order ID]</td>
<td>[QTY]</td>
<td>[Price/unit]</td>
<td>[Net]</td>
<td>[19% VAT]</td>
<td>[Gross]</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="4" class="right-align">Total</td>
<td>[Net total]</td>
<td>[19% VAT]</td>
<td>[Gross total]</td>
</tr>
</tfoot>
</table>
<h2>Payment</h2>
<p>The payment will be processed through electronic payment methods.</p>
<h2>Bank Details</h2>
<p>[Bank name]<br>
IBAN: [IBAN]<br>
BIC/SWIFT: [BIC/SWIFT]</p>
</div>
<div class="footer">
<p>This is an automatically generated invoice and is valid without a manual signature.</p>
</div>
</body>
</html>
### Generating PDF with MPDF
Here is the PHP code snippet to generate the PDF using the HTML template above:
require_once __DIR__ . '/vendor/autoload.php';
$mpdf = new MpdfMpdf();
$html = file_get_contents('path/to/invoice-template.html'); // Load the HTML content
$html = str_replace(['[First Name]', '[Last Name]', '[Address]', '[Net total]'],
['John', 'Doe', '123 Main Street', '100.00'], $html); // Replace placeholders
$mpdf->WriteHTML($html);
$mpdf->Output('invoice.pdf', 'D'); // Output as download
Replace placeholders in the HTML with actual data dynamically using PHP. Let me know if you need further assistance!
### Updated HTML Template with Background Image
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Invoice</title>
<style>
body {
font-family: Arial, sans-serif;
line-height: 1.6;
background-image: url('path/to/your-background-image.jpg'); /* Path to your image */
background-size: cover; /* Adjust to ensure the image covers the entire page */
background-position: center; /* Center the background image */
background-repeat: no-repeat; /* Prevent the image from repeating */
color: #000; /* Ensure text is visible on the background */
}
.header, .footer {
text-align: center;
}
.content {
margin: 0 auto;
max-width: 800px;
background: rgba(255, 255, 255, 0.9); /* Add a white semi-transparent background for readability */
padding: 20px;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
.table {
width: 100%;
border-collapse: collapse;
}
.table th, .table td {
border: 1px solid #ddd;
padding: 8px;
}
.table th {
background-color: #f2f2f2;
text-align: left;
}
.right-align {
text-align: right;
}
</style>
</head>
<body>
<div class="header">
<h1>INVOICE</h1>
</div>
<div class="content">
<h2>Company Information</h2>
<p>feedback4you GmbH<br>
Birkenfeldstr. 8<br>
85649 Brunnthal<br>
Germany<br>
VAT: DE123451234<br>
Email: billing@feedback4you.com</p>
<h2>Customer Information</h2>
<p>Customer Name: [First Name] [Last Name]<br>
Address: [Address], [Zip Code] [City], [Country]<br>
Customer Number: 0001500<br>
Invoice Number: 2024/11/14/1<br>
Invoice Date: 14.11.2024</p>
<h2>Services</h2>
<table class="table">
<thead>
<tr>
<th>Service</th>
<th>Order ID</th>
<th>QTY</th>
<th>Price/Unit</th>
<th>Net</th>
<th>19% VAT</th>
<th>Gross</th>
</tr>
</thead>
<tbody>
<tr>
<td>[Project name 1]</td>
<td>[Order ID]</td>
<td>[QTY]</td>
<td>[Price/unit]</td>
<td>[Net]</td>
<td>[19% VAT]</td>
<td>[Gross]</td>
</tr>
<tr>
<td>[Project name 2]</td>
<td>[Order ID]</td>
<td>[QTY]</td>
<td>[Price/unit]</td>
<td>[Net]</td>
<td>[19% VAT]</td>
<td>[Gross]</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="4" class="right-align">Total</td>
<td>[Net total]</td>
<td>[19% VAT]</td>
<td>[Gross total]</td>
</tr>
</tfoot>
</table>
<h2>Payment</h2>
<p>The payment will be processed through electronic payment methods.</p>
<h2>Bank Details</h2>
<p>[Bank name]<br>
IBAN: [IBAN]<br>
BIC/SWIFT: [BIC/SWIFT]</p>
</div>
<div class="footer">
<p>This is an automatically generated invoice and is valid without a manual signature.</p>
</div>
</body>
</html>
### Key Changes
1. **`background-image` Property**: The `body` now includes a `background-image` set to a file path (e.g., `'path/to/your-background-image.jpg'`). Replace this with the actual path to your image.
2. **Background Styling**:
– `background-size: cover;` ensures the image scales to cover the entire viewport.
– `background-position: center;` centers the image.
– `background-repeat: no-repeat;` prevents the image from repeating.
3. **Semi-transparent Content Area**:
– The `.content` section has a `background: rgba(255, 255, 255, 0.9);` style to ensure readability.
Let me know if you need assistance integrating this into your MPDF workflow or further customization!
";
$html.='
##Company_Name##
'.$clientDetails->first_name.' '.$clientDetails->last_name.'
INVOICE
Customer number
'.$clientno.'
Invoice number
'.date("Y-m")."/".$clientno.'/1
Invoice date
'.date('d.y.Y').'
VAT
342QWE
Hi '.$fullname.'
Thank you for choosing ##Company_Name##. We have prepared an invoice for the following services:
Service
Order ID
QTY
Price/unit
Net
19% VAT
Gross
';
$netTotal = '0';
$grossTotal = '0';
foreach ($invoices as $inv)
{
if(is_array($inv) && !is_null($inv))
{
$netTotal = $netTotal + $inv['total_price'];
$grossTotal = $grossTotal + ($inv['total_price']+$inv['vat_amount']);
$html .= '
'.$inv['project_name'].'
'.$inv['order_id'].'
'.$inv['cntTotalAmount'].'
€'.$inv['perUnitPrice'].'
€'.$inv['total_price'].'
€'.$inv['vat_amount'].'
€'.($inv['total_price']+$inv['vat_amount']).'
';
}
}
$html .= '
Total
€'.number_format($netTotal, 2).'
[19% VAT]
€'.number_format($grossTotal, 2).'
Reverse-Charge
The service date corresponds with the invoice date.
The payment will be processed through electronic payment method:
Credit Card
If you have any questions or require assistance, our customer service is here to help:
##Email##
feedback4you GmbH
VAT DE123451234
Birkenfeldstr. 8
85649 Brunnthal
Germany
##Email##
Commerzbank München
IBAN DE43 7004 0041 0220 8692 00
BIC: COBADEFFXXX
';
/*$html.="
Feedback4you is an offer from
##Company_Name##
##Address1##
##Pincode## ##CityName##
Tel: ##Phone##
Fax: +49 89 12 50 90 501
##Email##
www.feedback2you.com
##Company_Name## | ##Address1## ##Address2## | ##Pincode## ##CityName##
".$clientDetails->first_name.' '.$clientDetails->last_name."
".$clientDetails->address1."
".$clientDetails->address2."
".$clientDetails->zip_code."
".$clientDetails->city."
Customer Number: $clientno
Invoice Number: ".date("Y-m")."/".$clientno."/1
Invoice Date: ".Date('d.y.Y')."
Vat: 342QWE
INVOICE
Dear ".$fullname.",
Thank you for your order with ##Company_Name##. We are invoicing you for the following services:
Service
Order ID
Net
19% Vat
Gross
";
foreach ($invoices as $inv)
{
if(is_array($inv) && !is_null($inv))
{
$html.="
".$inv['project_name']."
".$inv['order_id']."
".$inv['total_price']." €
".$inv['vat_amount']." €
".($inv['total_price']+$inv['vat_amount'])." €
";
}
}
$html.="
Reverse-Charge
Leistungsdatum entspricht dem Rechnungsdatum. Bitte überweisen Sie den fälligen Rechnungsbetrag sofort nach Rechnungserhalt, unter Angabe der Rechnungsnummer, an die folgende Kontoverbindung:
Commerzbank München
BIC: COBADEFFXXX
IBAN: DE43 7004 0041 0220 8692 00
Wenn Sie Fragen zu dieser Rechnung haben, ist unser Kundenservice für Sie da:
##Phone##
##Email##
This invoice has been generated automatically and is valid without a signature.
";*/
$find = array("##Company_Name##","##Address1##","##Pincode##","##CityName##","##Phone##","##Email##","##Country##");
$replace = array('DCD Service Gmbh','Stefan-George-Ring 24','D-81929','Munchen',"+49 89 12 50 90 528","info@feedback4you.com","Germany");
$html = str_replace($find, $replace, $html);
$mpdf = app('mpdf');
$mpdf->SetDisplayMode('fullpage');
$stylesheet="
<style>
body{ background:url(./img/invoice_bg.jpg) no-repeat; background-size:cover}
.table_invoice{ width:1080px; margin:100px auto 100px; font-family:arial; font-size:20px; line-height:28px}
table.table {
width: 100%;
border-collapse: separate;
border-spacing: 0;
}
table.table thead tr, table.table tfoot tr {
background-color: white;
border-radius: 20px;
padding: 10px;
}
table.table thead tr th{text-align:left; padding:10px 20px}
table.table tfoot tr td{text-align:left; padding:10px 20px; font-weight:bold;}
table.table td{ color: #090607;}
table.table tbody tr {
padding: 10px 0;
}
table.table tbody td {
padding: 20px 10px;
}
table.table tbody tr + tr {
margin-top: 10px;
}
table.table thead th:first-child, tfoot td:first-child {
border-top-left-radius: 20px;
border-bottom-left-radius: 20px;
}
table.table thead th:last-child, table.table tfoot td:last-child {
border-top-right-radius: 20px;
border-bottom-right-radius: 20px;
}
table.table tbody td {
padding: 10px 20px;
}
.cardBtn{ color:#fff; color:#fff; font-size:24px; border-radius:30px; text-decoration:none;
background:#1f75ff; padding:10px 40px; font-weight:bold;
}
</style>
";
$header = '';
$footer = '';
$mpdf->WriteHTML($stylesheet, 1);
$mpdf->SetHTMLHeader($header, '', true);
$mpdf->SetHTMLFooter($footer);
$mpdf->WriteHTML($html,2);
// Output the PDF (inline in the browser)
// Output PDF as a string
$pdfContent = $mpdf->Output('', 'S');
$filename=date('Ymd').'invoice_report.pdf';
above background image not working
### 1. Ensure the Path to the Image is Correct
MPDF requires an absolute path for images. If you're using a relative path (e.g., `./img/invoice_bg.jpg`), MPDF may not locate the file correctly. Convert the path to an absolute path:
$backgroundImage = public_path('img/invoice_bg.jpg'); // Ensure the image is in your public directory
### 2. Embed the Background Image Correctly
Use the MPDF `SetWatermarkImage` method or update the CSS with the corrected path.
#### Using CSS with Corrected Path
Update your `background` property in the CSS as follows:
$stylesheet = "
<style>
body {
background: url('".url('img/invoice_bg.jpg')."') no-repeat;
background-size: cover;
}
</style>";
Here:
– `url('img/invoice_bg.jpg')` uses Laravel's `url` helper to generate the full URL to the image.
#### Using MPDF `SetWatermarkImage`
MPDF also supports a watermark-style background. Add this line after initializing MPDF:
$mpdf->SetWatermarkImage($backgroundImage);
$mpdf->showWatermarkImage = true;
This approach applies the image as a watermark, which works well for page backgrounds.
### 3. Verify File Permissions
Ensure the image file has the correct read permissions. If the web server (e.g., Apache) cannot access the image, MPDF will not render it.
### 4. Complete Example
Here's the complete fixed code snippet:
$backgroundImage = public_path('img/invoice_bg.jpg'); // Absolute path to the image
$mpdf = app('mpdf');
$mpdf->SetDisplayMode('fullpage');
// Set the watermark image as the background
$mpdf->SetWatermarkImage($backgroundImage);
$mpdf->showWatermarkImage = true;
// Add CSS
$stylesheet = "
<style>
body {
font-family: Arial, sans-serif;
color: #000;
}
.table_invoice { width: 1080px; margin: 100px auto; font-family: Arial; font-size: 20px; line-height: 28px; }
table.table { width: 100%; border-collapse: separate; border-spacing: 0; }
table.table thead th { padding: 10px 20px; background-color: #f2f2f2; }
</style>";
$mpdf->WriteHTML($stylesheet, 1);
// Add the content
$mpdf->WriteHTML($html, 2);
// Output the PDF
$mpdf->Output();
### 5. Test the PDF
– Verify the `img/invoice_bg.jpg` file exists and is readable.
– Open the PDF to confirm the background image is applied correctly.
Let me know if you need further help!
—
### Solution 1: Use an Absolute Path for the Background Image
MPDF needs the full filesystem path for local images or a complete URL for remote images. Update the CSS `background` property with the correct path:
#### Generate an Absolute Path in Laravel
Use Laravel's `public_path` or `url` helper:
$backgroundImagePath = public_path('img/invoice_bg.jpg'); // For local filesystem path
$backgroundImageUrl = url('img/invoice_bg.jpg'); // For URL
#### Updated CSS with Absolute Path
Set the `background` CSS property with the correct URL:
$stylesheet = "
<style>
body {
background: url('".$backgroundImageUrl."') no-repeat;
background-size: cover;
}
</style>";
—
### Solution 2: Embed the Image as Base64
If you prefer embedding the image directly into the PDF, convert the image into Base64 format and include it in the CSS.
#### Convert Image to Base64
Use PHP to encode the image:
$imagePath = public_path('img/invoice_bg.jpg');
$imageData = base64_encode(file_get_contents($imagePath));
$imageBase64 = 'data:image/jpeg;base64,' . $imageData;
#### CSS with Base64 Image
Embed the Base64 string in the CSS:
$stylesheet = "
<style>
body {
background: url('".$imageBase64."') no-repeat;
background-size: cover;
}
</style>";
—
### Solution 3: Use MPDF's Watermark Feature
MPDF has a `SetWatermarkImage` function that works well for setting a page-wide background.
#### Example
$mpdf->SetWatermarkImage(public_path('img/invoice_bg.jpg')); // Use absolute path
$mpdf->showWatermarkImage = true;
—
### Final Implementation
Here’s the complete example:
$mpdf = app('mpdf');
// Absolute path or URL to the image
$backgroundImageUrl = url('img/invoice_bg.jpg');
// CSS with background image
$stylesheet = "
<style>
body {
background: url('".$backgroundImageUrl."') no-repeat;
background-size: cover;
}
.content { font-family: Arial, sans-serif; color: #000; }
</style>";
// Write CSS
$mpdf->WriteHTML($stylesheet, 1);
// Your HTML content
$html = '<div class="content"><h1>Invoice</h1><p>This is a sample invoice.</p></div>';
// Write HTML
$mpdf->WriteHTML($html, 2);
// Output PDF
$mpdf->Output();
—
### Verify:
1. Ensure the image file exists and is readable (check file permissions).
2. Use a fully qualified URL or absolute path to the image.
3. Test with both CSS and `SetWatermarkImage` methods to see which works best for your needs.
Let me know if this resolves your issue!
'.$clientDetails->first_name.' '.$clientDetails->last_name.'
INVOICE
Customer number
'.$clientno.'
Invoice number
'.date("Y-m")."/".$clientno.'/1
Invoice date
'.date('d.y.Y').'
VAT
342QWE
Hi '.$fullname.'
Thank you for choosing ##Company_Name##. We have prepared an invoice for the following services:
Service
Order ID
QTY
Price/unit
Net
19% VAT
Gross
';
$netTotal = '0';
$grossTotal = '0';
foreach ($invoices as $inv)
{
if(is_array($inv) && !is_null($inv))
{
$netTotal = $netTotal + $inv['total_price'];
$grossTotal = $grossTotal + ($inv['total_price']+$inv['vat_amount']);
$html .= '
'.$inv['project_name'].'
'.$inv['order_id'].'
'.$inv['cntTotalAmount'].'
€'.$inv['perUnitPrice'].'
€'.$inv['total_price'].'
€'.$inv['vat_amount'].'
€'.($inv['total_price']+$inv['vat_amount']).'
';
}
}
$html .= '
Total
€'.number_format($netTotal, 2).'
[19% VAT]
€'.number_format($grossTotal, 2).'
Reverse-Charge
The service date corresponds with the invoice date.
The payment will be processed through electronic payment method:
Credit Card
If you have any questions or require assistance, our customer service is here to help:
##Email##
feedback4you GmbH
VAT DE123451234
Birkenfeldstr. 8
85649 Brunnthal
Germany
##Email##
Commerzbank München
IBAN DE43 7004 0041 0220 8692 00
BIC: COBADEFFXXX
replace php to placehodler above
### Updated HTML Template
<!DOCTYPE html>
<html>
<body>
<table class="table_invoice">
<tr>
<td height="55"></td>
</tr>
<tr>
<th style="text-align:left; padding:30px 30px">
<img width="300" src="{{logo_url}}" alt="Feedback Logo" />
</th>
</tr>
<tr>
<td height="80"></td>
</tr>
<tr>
<td>
<table style="width:100%; padding:0 30px">
<tr>
<td style="width:65%;">
<strong style="font-size:22px">{{company_name}}</strong><br />
{{client_first_name}} {{client_last_name}}<br />
</td>
<td style="text-align:right; width:35%">
<div style="text-align:left; width:325px; display:inline-block">
<span style="font-size:80px; margin-bottom:30px;">INVOICE</span><br />
<table style="width:100%; padding-top:25px">
<tr>
<td style="text-align:left">Customer number</td>
<td style="text-align:right">{{customer_number}}</td>
</tr>
<tr>
<td style="text-align:left">Invoice number</td>
<td style="text-align:right">{{invoice_number}}</td>
</tr>
<tr>
<td style="text-align:left">Invoice date</td>
<td style="text-align:right">{{invoice_date}}</td>
</tr>
<tr>
<td style="text-align:left">VAT</td>
<td style="text-align:right">{{vat_number}}</td>
</tr>
</table>
</div>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td height="80"></td>
</tr>
<tr>
<td style="padding:0 30px;">Hi {{full_name}}</td>
</tr>
<tr>
<td height="10"></td>
</tr>
<tr>
<td style="padding:0 30px;">Thank you for choosing {{company_name}}. We have prepared an invoice for the following services:</td>
</tr>
<tr>
<td height="30"></td>
</tr>
<tr>
<td>
<table class="table" border="0" cellspacing="0" cellpadding="5" style="padding:0 20px;">
<thead>
<tr style="margin-bottom:50px">
<th>Service</th>
<th>Order ID</th>
<th>QTY</th>
<th>Price/unit</th>
<th>Net</th>
<th>19% VAT</th>
<th>Gross</th>
</tr>
</thead>
<tbody style="font-size:18px">
<tr>
<td height="10"></td>
</tr>
{{#each services}}
<tr>
<td>{{service_name}}</td>
<td>{{order_id}}</td>
<td>{{quantity}}</td>
<td>€{{price_per_unit}}</td>
<td>€{{net_price}}</td>
<td>€{{vat}}</td>
<td>€{{gross_price}}</td>
</tr>
{{/each}}
</tbody>
<tfoot>
<tr>
<td colspan="4" style="font-weight: bold;">Total</td>
<td style="font-weight: bold;">€{{total_net}}</td>
<td style="font-weight: bold;">€{{total_vat}}</td>
<td style="font-weight: bold;">€{{total_gross}}</td>
</tr>
</tfoot>
</table>
</td>
</tr>
<tr>
<td height="45"></td>
</tr>
<tr>
<td style="padding:0 30px;">
Reverse-Charge<br /><br />
The service date corresponds with the invoice date.<br /><br />
The payment will be processed through electronic payment method:
</td>
</tr>
<tr>
<td height="35"></td>
</tr>
<tr>
<td>
<a href="#" style="display: inline-block; width: 210px; height: 48px; color: #fff; font-size: 20px; text-decoration: none; line-height: 48px; background-color: #1f75ff; text-align: center; font-weight: bold;">Credit Card</a>
</td>
</tr>
<tr>
<td height="25"></td>
</tr>
<tr>
<td style="padding:0 30px; line-height:30px">
If you have any questions or require assistance, our customer service is here to help:<br />
{{email}}<br /><br />
</td>
</tr>
<tr>
<td height="100"></td>
</tr>
<tr style="border-top:#ccc solid 1px">
<td>
<table border="0" cellspacing="0" cellpadding="5" style="width:100%; border-top:#ccc solid 1px; padding:30px 30px">
<tr>
<td style="width:33%; vertical-align:top; font-size:18px; line-height:26px">
{{company_name}}<br />
VAT {{vat_number}}
</td>
<td style="width:32%; vertical-align:top; font-size:18px; line-height:26px">
{{address_line_1}}<br />
{{address_line_2}}<br />
{{country}}<br />
{{email}}
</td>
<td style="width:34%; vertical-align:top; font-size:18px; line-height:26px">
{{bank_name}}<br />
IBAN {{iban}}<br />
BIC: {{bic}}
</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>
—
### Placeholder Explanation
1. **General Details**:
– `{{logo_url}}`, `{{company_name}}`, `{{client_first_name}}`, `{{client_last_name}}`, etc., for company and client details.
2. **Invoice Details**:
– `{{customer_number}}`, `{{invoice_number}}`, `{{invoice_date}}`, etc.
3. **Service Table**:
– Use `{{#each services}} … {{/each}}` to loop through the services (if using a templating engine).
4. **Totals**:
– `{{total_net}}`, `{{total_vat}}`, `{{total_gross}}` for invoice totals.
5. **Footer Details**:
– `{{email}}`, `{{bank_name}}`, `{{iban}}`, `{{bic}}`.
This structure makes it easier to replace placeholders with dynamic data before generating the PDF. Let me know if you need further help!
—
### Step 1: Download the Switzer Font
1. Download the Switzer font files (TTF, OTF, or WOFF formats) from a trusted source like Google Fonts or a font provider.
2. Place the font files in your Laravel project, ideally under `public/fonts/Switzer`.
—
### Step 2: Register the Font in MPDF
MPDF requires fonts to be registered in its configuration. Add the font as follows:
#### Example Directory Structure
/public/fonts/Switzer
- Switzer-Regular.ttf
- Switzer-Bold.ttf
- Switzer-Italic.ttf
#### Configuration Code
$mpdf = app('mpdf');
// Specify font directory
$fontDirs = $mpdf->getFontDirs();
$fontDirs[] = public_path('fonts/Switzer');
$mpdf->setFontDirs($fontDirs);
// Register Switzer font
$fontData = $mpdf->getFontData();
$fontData['switzer'] = [
'R' => 'Switzer-Regular.ttf', // Regular font
'B' => 'Switzer-Bold.ttf', // Bold font
'I' => 'Switzer-Italic.ttf', // Italic font
'BI' => 'Switzer-BoldItalic.ttf' // Bold Italic font (if available)
];
$mpdf->setFontData($fontData);
—
### Step 3: Apply the Font in HTML
You can now use the `Switzer` font in your styles:
$stylesheet = "
<style>
body {
font-family: 'switzer', sans-serif;
}
.title {
font-family: 'switzer', sans-serif;
font-size: 24px;
font-weight: bold;
}
</style>";
$mpdf->WriteHTML($stylesheet, 1);
—
### Step 4: Generate the PDF
$html = "
<div>
<h1 class='title'>This is a Switzer Font Heading</h1>
<p>This is a paragraph using the Switzer font.</p>
</div>";
$mpdf->WriteHTML($html, 2);
$mpdf->Output();
—
### Verify the Output
1. Ensure the font files are accessible in the specified directory.
2. Check the font rendering in the generated PDF.
Let me know if you encounter any issues!
—
### Correct Way to Add Custom Fonts in MPDF
#### Step 1: Place the Font Files
1. Create a directory to store your custom fonts, e.g., `public/fonts/Switzer`.
2. Add the font files, e.g.:
/public/fonts/Switzer
- Switzer-Regular.ttf
- Switzer-Bold.ttf
- Switzer-Italic.ttf
- Switzer-BoldItalic.ttf
—
#### Step 2: Define the Font Configuration
MPDF uses the `fontdata` array for custom fonts. Add the font data like this:
require_once __DIR__ . '/vendor/autoload.php'; // Ensure MPDF is autoloaded
$mpdf = new MpdfMpdf([
'tempDir' => storage_path('app/mpdf'), // Temp directory for MPDF
]);
// Add your custom font directory
$defaultFontConfig = (new MpdfConfigConfigVariables())->getDefaults();
$fontDirs = $defaultFontConfig['fontDir'];
$fontDirs[] = public_path('fonts/Switzer');
$defaultFontData = (new MpdfConfigFontVariables())->getDefaults();
$fontData = $defaultFontData['fontdata'];
// Add Switzer font
$fontData['switzer'] = [
'R' => 'Switzer-Regular.ttf', // Regular
'B' => 'Switzer-Bold.ttf', // Bold
'I' => 'Switzer-Italic.ttf', // Italic
'BI' => 'Switzer-BoldItalic.ttf' // Bold Italic (if available)
];
// Reinitialize MPDF with custom font settings
$mpdf = new MpdfMpdf([
'fontDir' => $fontDirs,
'fontdata' => $fontData,
'default_font' => 'switzer' // Set Switzer as the default font
]);
—
#### Step 3: Use the Font in Your HTML
Apply the custom font in your CSS:
$stylesheet = "
<style>
body {
font-family: 'switzer', sans-serif;
}
h1 {
font-family: 'switzer', sans-serif;
font-size: 24px;
font-weight: bold;
}
</style>";
$mpdf->WriteHTML($stylesheet, 1);
—
#### Step 4: Generate the PDF
Render your content with the Switzer font:
$html = "
<div>
<h1>Invoice</h1>
<p>This text is rendered using the Switzer font.</p>
</div>";
$mpdf->WriteHTML($html, 2);
$mpdf->Output('invoice.pdf', 'I'); // Output to browser
—
### Notes:
1. **Temp Directory**: Ensure the `tempDir` path is writable by the web server.
2. **Font Accessibility**: Ensure the font files are readable by the web server.
3. **Fallback Font**: If you don’t set a default font (`default_font`), MPDF will fall back to its built-in fonts like `dejavusans`.
Let me know if you face any further issues!
—
### Step 1: Place the Font Files
1. Store your custom font files (e.g., TTF format) in a publicly accessible directory, such as `public/fonts/Switzer`.
Example:
/public/fonts/Switzer
- Switzer-Regular.ttf
- Switzer-Bold.ttf
- Switzer-Italic.ttf
- Switzer-BoldItalic.ttf
—
### Step 2: Define the Font with `@font-face` in CSS
Use the `@font-face` rule in a “ tag to define the font family:
$stylesheet = "
<style>
@font-face {
font-family: 'Switzer';
src: url('" . public_path('fonts/Switzer/Switzer-Regular.ttf') . "') format('truetype');
font-weight: normal;
font-style: normal;
}
@font-face {
font-family: 'Switzer';
src: url('" . public_path('fonts/Switzer/Switzer-Bold.ttf') . "') format('truetype');
font-weight: bold;
font-style: normal;
}
@font-face {
font-family: 'Switzer';
src: url('" . public_path('fonts/Switzer/Switzer-Italic.ttf') . "') format('truetype');
font-weight: normal;
font-style: italic;
}
@font-face {
font-family: 'Switzer';
src: url('" . public_path('fonts/Switzer/Switzer-BoldItalic.ttf') . "') format('truetype');
font-weight: bold;
font-style: italic;
}
body {
font-family: 'Switzer', sans-serif;
}
h1 {
font-family: 'Switzer', sans-serif;
font-weight: bold;
}
</style>";
—
### Step 3: Embed CSS and Content in MPDF
Use the above CSS and include your HTML content:
require_once __DIR__ . '/vendor/autoload.php'; // Ensure MPDF is autoloaded
$mpdf = new MpdfMpdf();
// Write the CSS to MPDF
$mpdf->WriteHTML($stylesheet, 1);
// Your HTML content
$html = "
<div>
<h1>Invoice</h1>
<p>This text is rendered using the Switzer font.</p>
</div>";
// Write the HTML to MPDF
$mpdf->WriteHTML($html, 2);
// Output the PDF
$mpdf->Output('invoice.pdf', 'I'); // Display inline in the browser
—
### Notes:
1. **Path to Fonts**: Ensure the `public_path()` function resolves correctly to the absolute path of the font files.
2. **TTF Format**: Use the `truetype` format (`format('truetype')`) for MPDF compatibility.
3. **Web-Accessible Fonts**: If the fonts are stored in a public directory (like `/public/fonts`), you can use URLs instead of file paths:
src: url('" . url('fonts/Switzer/Switzer-Regular.ttf') . "') format('truetype');
—
### Troubleshooting
– **Font Not Displaying**: Check the file permissions of the font files to ensure they are readable.
– **Fallback Font**: If MPDF cannot load the custom font, it will fall back to the default font (`dejavusans`).
Let me know if you need further clarification!