I am working on a PHP-based worksheet generation system and recently ran into a performance problem.
The application generates printable PDF files based on user-selected options.
The workflow is:
User selects options
↓
Server generates data
↓
PHP creates PDF
↓
User downloads the file
The problem is that the generation time increases significantly when the document contains many items.
For example:
- 100+ exercises
- multiple pages
- answer pages
- custom layouts
Current implementation
The frontend sends a POST request to the PDF generation endpoint:
$result = http_post(
"https://www.wativate.com/?api",
[
"operation" => "addition",
"questions" => 100,
"include_answers" => true
]
);
The server receives the parameters and starts generating the PDF.
A simplified version:
function generateWorksheetPDF($options)
{
$problems = generateProblems(
$options['questions']
);
$html = renderHTML($problems);
return createPDF($html);
}
The current approach works well for small files.
However, when generating larger worksheets, I notice several problems:
- High CPU usage
- Long response time
- Occasional timeout errors
For example:
Small document:
20 questions → 2 seconds
Large document:
200 questions → 20+ seconds
Things I have tried
- Increasing PHP timeout
set_time_limit(120);
This avoids some timeout problems, but it does not solve the performance issue.
- Caching generated files
I tried saving generated PDFs:
$filename = md5(
json_encode($options)
) . ".pdf";
If the same options are requested again, the existing file can be reused.
This helps repeated requests, but the first generation is still slow.
- Moving PDF generation to background jobs
I am considering changing the architecture.
Current:
HTTP Request
↓
Generate PDF
↓
Return File
Possible:
HTTP Request
↓
Create Task
↓
Queue Worker
↓
Generate PDF
↓
Download Later
My questions
For a PHP application that generates dynamic PDFs:
Should PDF generation always be moved to background jobs?
Is it better to generate PDFs asynchronously even for small documents?
Are there better strategies for handling large HTML-to-PDF conversions?
Would splitting the document generation process into smaller tasks improve performance?
I would appreciate any suggestions from developers who have built similar document generation systems.
Top comments (0)