DEV Community

aethans
aethans

Posted on

PHP PDF generation becomes slow when creating large documents

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);
Enter fullscreen mode Exit fullscreen mode

}

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

  1. Increasing PHP timeout

set_time_limit(120);

This avoids some timeout problems, but it does not solve the performance issue.

  1. 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.

  1. 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:

  1. Should PDF generation always be moved to background jobs?

  2. Is it better to generate PDFs asynchronously even for small documents?

  3. Are there better strategies for handling large HTML-to-PDF conversions?

  4. 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)