English Version
1. Core Concepts
This system is designed to be a flexible and extensible pipeline for converting documents from various source formats (like Markdown or HTML) into target formats (like PDF or DOCX). The architecture is built on these key principles:DocumentConverterService: This is the central orchestrator of the pipeline. It provides a fluent interface that makes the conversion process readable and easy to manage. It doesn’t perform conversions itself; it delegates tasks to the appropriate drivers.- Input Drivers: An Input Driver’s job is to take raw content from a source file (e.g., a
.mdor.htmlfile) and prepare it for rendering. This typically involves replacing placeholders with data and wrapping the content in a master Blade layout. - Output Drivers: An Output Driver’s job is to take the final, fully-rendered HTML (after Blade has processed it) and convert it into the target format’s binary content (e.g., the binary data of a PDF or DOCX file).
- Blade as the Intermediate Format: All conversions pass through a common intermediate step: a Blade view. This allows us to centralize styling (CSS) and document structure (headers, footers) in a single master layout file, ensuring consistency across all generated documents.
- Laravel Filesystem Integration: The final step of saving the document is handled by Laravel’s
Storagefacade, allowing you to save the output to any configured disk, including local storage, S3, or an S3-compatible service like MinIO.
2. Configuration
Before using the pipeline, ensure the following are configured: A. System & PHP Dependencies: Make sure you have installed the required system tools and Composer packages.- System Tool:
weasyprint(for PDF generation). - Composer Packages:
phpoffice/phpword,rockett/weasyprint,league/flysystem-aws-s3-v3.
.env)
To save files to an S3-compatible disk like MinIO, add the credentials to your .env file.
config/filesystems.php)
Define the minio disk so Laravel’s Storage facade knows how to connect to it.
config/documents.php)
This is the core configuration file for the pipeline. It maps file extensions to the driver classes that should handle them.
3. Usage Guide
You can use the pipeline via the provided Artisan command or programmatically within your application. A. Using the Artisan Command (convert:document)
This is the primary way to perform conversions from the command line.
- Convert a Markdown file to a PDF on MinIO:
- Convert an HTML file to a DOCX on the local public disk:
- Convert directly from a Blade view to a PDF:
(Assumes you have
resources/views/documents/receipt.blade.php)
- Specify a custom layout for a file-based conversion:
DocumentConverter service directly in your code for dynamic document generation.
4. Extending the Pipeline
A. Creating a New Input Driver- Create a new class in
app/Services/DocumentConversion/Drivers/Inputthat implementsInputDriverInterface. - Implement the
process()method. It must accept raw content and return a Blade-compatible string that extends a layout. - Register your new driver in
config/documents.phpwith the file extension it handles.
- Create a new class in
app/Services/DocumentConversion/Drivers/Outputthat implementsOutputDriverInterface. - Implement the
render()method. It must accept the final HTML and return the raw binary content of the converted file as a string. - Register your new driver in
config/documents.phpwith its output file extension.
5. Testing
It’s crucial to test your document generation logic. Use Laravel’sStorage::fake() to prevent actual files from being written to disk during tests.
Here is an example using Pest/PHPUnit:
Addendum 1: Advanced Spreadsheet Conversion
A.1 Using Spreadsheets as Input
The pipeline can read data from.csv and .xlsx files and render it as an HTML <table> within a target document (like a PDF or DOCX). This is ideal for generating reports from spreadsheet data.
Concept
When a spreadsheet file is used as input, the corresponding Input Driver performs the following steps:- Parses the
.csvor.xlsxfile using a dedicated spreadsheet library. - Reads all the rows and cells from the first sheet.
- Transforms this data into an HTML
<table>string. - Wraps this HTML table string within the standard Blade layout directives (
@extends,@section). - Passes this Blade string to the renderer, which then flows through the rest of the pipeline to the chosen output format.
Available Engines
The system supports multiple spreadsheet engines, configurable inconfig/documents.php. You can choose the one that best fits your needs.
MaatwebsiteInputDriver: (Default) A user-friendly, feature-rich driver using the popularmaatwebsite/excelpackage. Great for general use.OpenSpoutInputDriver: A high-performance, low-memory driver using theopenspout/openspoutpackage. Recommended for very large files.PhpSpreadsheetInputDriver: A powerful driver using the underlyingphpoffice/phpspreadsheetlibrary. Offers maximum control and feature access.
Configuration
To switch engines, simply editconfig/documents.php and point the csv and xlsx keys to your desired driver class.
Usage
The command is the same regardless of the chosen engine.A.2 Generating Spreadsheets as Output
The pipeline can also convert a source document (like Markdown or HTML) into an.xlsx file. This is useful for exporting structured and unstructured content into a spreadsheet format.
Concept
This is a more advanced conversion. When.xlsx is the target format, the Output Driver performs a unique process:
- It receives the final, fully-rendered HTML from the Blade engine.
- It parses the HTML DOM structure.
- When it encounters a
<table>element, it translates the table’s rows (<tr>) and cells (<th>,<td>) directly into spreadsheet rows and cells. - When it encounters any other block-level element (
<h1>,<p>,<ul>, etc.), it extracts the element’s text content and places it into a new spreadsheet row in the first column. - This preserves both the structured data and the textual context of the original document.
Available Engines
Like with input, you have a choice of engines for generating XLSX files.MaatwebsiteOutputDriver: (Default) Usesmaatwebsite/excelto easily build the spreadsheet from a PHP array. Very convenient and reliable.OpenSpoutOutputDriver: Usesopenspout/openspout’s streaming writer. Excellent for generating extremely large XLSX files without hitting memory limits.PhpSpreadsheetOutputDriver: Usesphpoffice/phpspreadsheetto build the document in memory. Offers deep control over cell styling, formulas, and other advanced features.
Configuration
To switch engines, edit thexlsx key in the output_drivers section of config/documents.php.
Usage
Addendum 2: Advanced XLSX Generation with Templates
A.2.1 Concept
While the standard output drivers are excellent for converting a document’s content into spreadsheet rows, the templating system provides a higher level of control over the final document’s layout and presentation. The core idea is to use a pre-designed.xlsx file as a template. This template can contain headers, footers, logos, static text, and pre-styled cells. The pipeline then injects dynamic data and content into this template.
This process is handled by a new, specialized driver: TemplatedXlsxOutputDriver. This driver is powered by the phpoffice/phpspreadsheet library, as it’s the only one capable of both reading an existing spreadsheet and modifying it.
A.2.2 Creating the XLSX Template
To use this feature, you must first create a template.xlsx file (e.g., storage/app/templates/report-template.xlsx). This file uses two types of special markers:
- Global Placeholders: For single data points like a title or a date, you can place Blade-style placeholders directly into any cell. The driver will find and replace these.
- Syntax:
{{ $variable_name }}or{{ $user.name }} - Example: A cell containing
Report for: {{ $customer_name }}
- Content Start Marker: You must designate a single cell where the main, dynamic HTML content will begin to be inserted. All content will flow downwards from this point.
- Marker:
{{CONTENT_START}}
report-template.xlsx):
| A | B | C | D | |
|---|---|---|---|---|
| 1 | {{ $report_title }} | Company Logo Here | ||
| 2 | Generated On: | {{ $generated_on }} | ||
| 3 | ||||
| 4 | Transaction Details | |||
| 5 | {{CONTENT_START}} |
A.2.3 HTML to Cell Style Mapping
When theTemplatedXlsxOutputDriver processes the HTML content, it applies basic cell styling based on the HTML tags it encounters. This adds a typographic hierarchy to your report.
<h1>,<h2>,<h3>: Text is made bold with decreasing font sizes.<b>,<strong>: Text is made bold.<i>,<em>: Text is made italic.<table>: The driver recognizes HTML tables and correctly maps<tr>,<th>, and<td>to spreadsheet rows and cells, preserving the tabular structure.
A.2.4 Configuration
To enable this feature, ensure theTemplatedXlsxOutputDriver is set as the handler for the .xlsx extension in your config/documents.php file.
A.2.5 Usage
You activate the templating feature by specifying the path to your XLSX template file. A. Using the Artisan Command Use the new--output-template option.
->usingOutputTemplate() fluent method on the DocumentConverter service.
Versi Bahasa Indonesia
1. Konsep Inti
Sistem ini dirancang untuk menjadi pipeline (alur proses) yang fleksibel dan dapat diperluas untuk mengonversi dokumen dari berbagai format sumber (seperti Markdown atau HTML) ke format target (seperti PDF atau DOCX). Arsitekturnya dibangun di atas prinsip-prinsip utama berikut:- Service
DocumentConverter: Ini adalah orkestrator pusat dari pipeline. Ia menyediakan fluent interface yang membuat proses konversi mudah dibaca dan dikelola. Service ini tidak melakukan konversi secara langsung; ia mendelegasikan tugas ke driver yang sesuai. - Input Driver: Tugas Input Driver adalah mengambil konten mentah dari file sumber (misalnya, file
.mdatau.html) dan menyiapkannya untuk di-render. Ini biasanya melibatkan penggantian placeholder dengan data dan membungkus konten dalam layout master Blade. - Output Driver: Tugas Output Driver adalah mengambil HTML final yang sudah di-render (setelah diproses oleh Blade) dan mengubahnya menjadi konten biner dari format target (misalnya, data biner dari file PDF atau DOCX).
- Blade sebagai Format Perantara: Semua konversi melewati langkah perantara yang sama: view Blade. Ini memungkinkan kita untuk memusatkan styling (CSS) dan struktur dokumen (header, footer) dalam satu file layout master, memastikan konsistensi di semua dokumen yang dihasilkan.
- Integrasi Filesystem Laravel: Langkah terakhir untuk menyimpan dokumen ditangani oleh
Storagefacade dari Laravel, memungkinkan Anda menyimpan output ke disk apa pun yang telah dikonfigurasi, termasuk penyimpanan lokal, S3, atau layanan yang kompatibel dengan S3 seperti MinIO.
2. Konfigurasi
Sebelum menggunakan pipeline, pastikan hal-hal berikut telah dikonfigurasi: A. Dependensi Sistem & PHP: Pastikan Anda telah menginstal perangkat lunak sistem dan paket Composer yang diperlukan.- Perangkat Lunak Sistem:
weasyprint(untuk pembuatan PDF). - Paket Composer:
phpoffice/phpword,rockett/weasyprint,league/flysystem-aws-s3-v3.
.env)
Untuk menyimpan file ke disk yang kompatibel dengan S3 seperti MinIO, tambahkan kredensial ke file .env Anda.
config/filesystems.php)
Definisikan disk minio agar Storage facade Laravel tahu cara terhubung dengannya.
config/documents.php)
Ini adalah file konfigurasi inti untuk pipeline. File ini memetakan ekstensi file ke kelas driver yang harus menanganinya.
3. Panduan Penggunaan
Anda dapat menggunakan pipeline melalui perintah Artisan yang disediakan atau secara terprogram di dalam aplikasi Anda. A. Menggunakan Perintah Artisan (convert:document)
Ini adalah cara utama untuk melakukan konversi dari baris perintah.
- Mengonversi file Markdown ke PDF di MinIO:
- Mengonversi file HTML ke DOCX di disk
publiclokal:
- Mengonversi langsung dari view Blade ke PDF:
(Asumsikan Anda memiliki file
resources/views/documents/receipt.blade.php)
- Menentukan layout kustom untuk konversi berbasis file:
DocumentConverter secara langsung di dalam kode Anda untuk pembuatan dokumen dinamis.
4. Memperluas Pipeline
A. Membuat Input Driver Baru- Buat kelas baru di
app/Services/DocumentConversion/Drivers/Inputyang mengimplementasikanInputDriverInterface. - Implementasikan metode
process(). Metode ini harus menerima konten mentah dan mengembalikan string yang kompatibel dengan Blade yang me-extendsebuah layout. - Daftarkan driver baru Anda di
config/documents.phpdengan ekstensi file yang ditanganinya.
- Buat kelas baru di
app/Services/DocumentConversion/Drivers/Outputyang mengimplementasikanOutputDriverInterface. - Implementasikan metode
render(). Metode ini harus menerima HTML final dan mengembalikan konten biner mentah dari file yang telah dikonversi dalam bentuk string. - Daftarkan driver baru Anda di
config/documents.phpdengan ekstensi file outputnya.
5. Pengujian (Testing)
Sangat penting untuk menguji logika pembuatan dokumen Anda. GunakanStorage::fake() dari Laravel untuk mencegah penulisan file ke disk selama pengujian.
Berikut adalah contoh menggunakan Pest/PHPUnit:
Lampiran 1: Pemrosesan Spreadsheet Tingkat Lanjut
A.1 Menggunakan Spreadsheet sebagai Input
Pipeline ini dapat membaca data dari file.csv dan .xlsx dan me-render-nya sebagai <table> HTML di dalam dokumen target (seperti PDF atau DOCX). Fitur ini ideal untuk membuat laporan dari data spreadsheet.
Konsep
Ketika file spreadsheet digunakan sebagai input, Input Driver yang sesuai akan melakukan langkah-langkah berikut:- Mem-parsing file
.csvatau.xlsxmenggunakan library spreadsheet khusus. - Membaca semua baris dan sel dari sheet pertama.
- Mengubah data ini menjadi string
<table>HTML. - Membungkus string tabel HTML ini di dalam direktif layout master Blade (
@extends,@section). - Meneruskan string Blade ini ke renderer, yang kemudian mengalir melalui sisa pipeline ke format output yang dipilih.
Engine yang Tersedia
Sistem ini mendukung beberapa engine spreadsheet, yang dapat dikonfigurasi diconfig/documents.php. Anda dapat memilih yang paling sesuai dengan kebutuhan Anda.
MaatwebsiteInputDriver: (Default) Driver yang ramah pengguna dan kaya fitur, menggunakan paket populermaatwebsite/excel. Sangat baik untuk penggunaan umum.OpenSpoutInputDriver: Driver berkinerja tinggi dengan penggunaan memori rendah, menggunakan paketopenspout/openspout. Direkomendasikan untuk file yang sangat besar.PhpSpreadsheetInputDriver: Driver yang kuat menggunakan library dasarphpoffice/phpspreadsheet. Menawarkan kontrol dan akses fitur yang maksimal.
Konfigurasi
Untuk mengganti engine, cukup editconfig/documents.php dan arahkan key csv dan xlsx ke kelas driver yang Anda inginkan.
Penggunaan
Perintah yang digunakan tetap sama, terlepas dari engine yang dipilih.A.2 Menghasilkan Spreadsheet sebagai Output
Pipeline ini juga dapat mengonversi dokumen sumber (seperti Markdown atau HTML) menjadi file.xlsx. Ini berguna untuk mengekspor konten terstruktur dan tidak terstruktur ke dalam format spreadsheet.
Konsep
Ini adalah konversi yang lebih canggih. Ketika.xlsx menjadi format target, Output Driver melakukan proses yang unik:
- Menerima HTML final yang sudah di-render sepenuhnya dari engine Blade.
- Mem-parsing struktur DOM HTML tersebut.
- Ketika menemukan elemen
<table>, ia menerjemahkan baris (<tr>) dan sel (<th>,<td>) tabel secara langsung menjadi baris dan sel spreadsheet. - Ketika menemukan elemen tingkat blok lainnya (
<h1>,<p>,<ul>, dll.), ia mengekstrak konten teks elemen tersebut dan menempatkannya ke dalam baris spreadsheet baru di kolom pertama. - Proses ini menjaga data terstruktur sekaligus konteks tekstual dari dokumen asli.
Engine yang Tersedia
Seperti halnya input, Anda memiliki pilihan engine untuk menghasilkan file XLSX.MaatwebsiteOutputDriver: (Default) Menggunakanmaatwebsite/exceluntuk membuat spreadsheet dengan mudah dari array PHP. Sangat nyaman dan andal.OpenSpoutOutputDriver: Menggunakan streaming writer dariopenspout/openspout. Sangat baik untuk menghasilkan file XLSX yang sangat besar tanpa mencapai batas memori.PhpSpreadsheetOutputDriver: Menggunakanphpoffice/phpspreadsheetuntuk membangun dokumen di dalam memori. Menawarkan kontrol mendalam atas styling sel, formula, dan fitur canggih lainnya.
Konfigurasi
Untuk mengganti engine, edit keyxlsx di bagian output_drivers pada file config/documents.php.
Penggunaan
Lampiran 2: Generate XLSX dengan XLSX Template
A.2.1 Konsep
Meskipun driver output standar sangat baik untuk mengonversi konten dokumen menjadi baris spreadsheet, sistem templating ini memberikan tingkat kontrol yang lebih tinggi atas tata letak dan presentasi dokumen akhir. Ide intinya adalah menggunakan file.xlsx yang sudah dirancang sebelumnya sebagai templat. Templat ini dapat berisi header, footer, logo, teks statis, dan sel yang sudah di-styling. Pipeline kemudian akan menyuntikkan data dan konten dinamis ke dalam templat ini.
Proses ini ditangani oleh driver baru yang terspesialisasi: TemplatedXlsxOutputDriver. Driver ini didukung oleh library phpoffice/phpspreadsheet, karena hanya library inilah yang mampu membaca file spreadsheet yang ada sekaligus memodifikasinya.
A.2.2 Membuat Templat XLSX
Untuk menggunakan fitur ini, Anda harus terlebih dahulu membuat file templat.xlsx (misalnya, storage/app/templates/report-template.xlsx). File ini menggunakan dua jenis penanda khusus:
- Placeholder Global: Untuk titik data tunggal seperti judul atau tanggal, Anda dapat menempatkan placeholder bergaya Blade langsung ke dalam sel mana pun. Driver akan menemukan dan menggantinya.
- Sintaks:
{{ $nama_variabel }}atau{{ $user.name }} - Contoh: Sebuah sel berisi
Laporan untuk: {{ $customer_name }}
- Penanda Awal Konten (Content Start Marker): Anda harus menetapkan satu sel di mana konten HTML dinamis utama akan mulai dimasukkan. Semua konten akan mengalir ke bawah dari titik ini.
- Penanda:
{{CONTENT_START}}
report-template.xlsx):
| A | B | C | D | |
|---|---|---|---|---|
| 1 | {{ $report_title }} | Logo Perusahaan | ||
| 2 | Dibuat pada: | {{ $generated_on }} | ||
| 3 | ||||
| 4 | Detail Transaksi | |||
| 5 | {{CONTENT_START}} |
A.2.3 Pemetaan Styling HTML ke Sel
KetikaTemplatedXlsxOutputDriver memproses konten HTML, ia menerapkan styling sel dasar berdasarkan tag HTML yang ditemuinya. Ini menambahkan hierarki tipografi ke laporan Anda.
<h1>,<h2>,<h3>: Teks dibuat tebal dengan ukuran font yang semakin kecil.<b>,<strong>: Teks dibuat tebal.<i>,<em>: Teks dibuat miring.<table>: Driver mengenali tabel HTML dan memetakan<tr>,<th>, dan<td>dengan benar ke baris dan sel spreadsheet, menjaga struktur tabel.
A.2.4 Konfigurasi
Untuk mengaktifkan fitur ini, pastikanTemplatedXlsxOutputDriver diatur sebagai handler untuk ekstensi .xlsx di file config/documents.php Anda.
A.2.5 Penggunaan
Anda mengaktifkan fitur templating dengan menentukan path ke file templat XLSX Anda. A. Menggunakan Perintah Artisan Gunakan opsi baru--output-template.
->usingOutputTemplate() pada service DocumentConverter.
