How to Convert Plain Text to PDF with PHP

Use PHP to transform plain text into a styled, tagged PDF with preserved lines or reflowed paragraphs.
Share this page

This PHP tutorial converts a plain text upload through the pdfRest Convert to PDF API Tool. The sample retains source line breaks and supplies the page, font, language, and tagging options needed for consistent PDF output.

Why Convert Plain Text to PDF with PHP?

PHP applications frequently build case notes, order summaries, and form-derived records as simple text. Plain text is easy to generate, but users may need a formal download that can be emailed, annotated, printed, or stored with other customer documents.

A case-management portal illustrates the need: after an agent completes an intake workflow, PHP can assemble the submitted answers and system notes into a text summary. Converting that file to PDF creates a durable case artifact with a title, controlled margins, and predictable pagination, avoiding a manually assembled document for every submission.

Preserve mode is appropriate when each answer or label must remain on its own line. Reflow mode is available when the generated content should read as continuous prose, giving the portal control over readability without changing the underlying source format.

PHP Code Example for Converting Plain Text to PDF

require 'vendor/autoload.php';

use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Utils;

// By default, we use the US-based API service. This is the primary endpoint for global use.
$apiUrl = "https://api.pdfrest.com";

/* For GDPR compliance and enhanced performance for European users, you can switch to the EU-based service by uncommenting the URL below.
 * For more information visit https://pdfrest.com/pricing#how-do-eu-gdpr-api-calls-work
 */
//$apiUrl = "https://eu-api.pdfrest.com";

$inputPath = '/path/to/sample.txt';
$options = json_decode('{"title":"Structured Content Sample","language":"en-US","enable_tagging":true,"page_setup":{"size":"Letter","orientation":"portrait","margin":{"top":36,"right":42,"bottom":36,"left":42}},"style":{"font":"Arial","heading_font":"Arial","code_font":"Courier","text_size":11,"text_color_rgb":[34,34,34],"heading_scale":1.35,"table":{"column_width_weights":[2,3,2],"keep_header_with_first_row":true,"repeat_headers_on_overflow":true,"show_borders":true,"border_width":0.75,"border_color_rgb":[180,188,200],"header_fill_color_rgb":[33,64,98],"header_text_color_rgb":[255,255,255],"row_fill_color_rgb":[250,250,252],"alternate_row_fill_color_rgb":[235,240,246],"cell_padding":{"top":6,"right":8,"bottom":6,"left":8}}},"plain_text":{"line_handling":"preserve"}}', true);

// This sample converts plain text input to a tagged PDF through multipart /pdf.
// It demonstrates structured_text_options and the format-specific conversion options.
$multipart = [
  ['name' => 'file', 'contents' => Utils::tryFopen($inputPath, 'r'), 'filename' => basename($inputPath)],
  ['name' => 'structured_text_options', 'contents' => json_encode($options)],
  ['name' => 'output', 'contents' => 'pdf_from_text'],
];
$response = (new Client())->post($apiUrl . '/pdf', ['headers' => ['Api-Key' => 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx', 'Accept' => 'application/json'], 'multipart' => $multipart]);
echo $response->getBody();

Source: View the sample on GitHub

Breaking Down the Code

This PHP Plain Text example relies on Guzzle for HTTP and PSR-7 stream utilities for the upload. When using the code outside this repository, add the client with composer require guzzlehttp/guzzle.

require 'vendor/autoload.php';
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Utils;

The PHP endpoint excerpt keeps regional routing explicit for this Plain Text operation:

// By default, we use the US-based API service. This is the primary endpoint for global use.
$apiUrl = "https://api.pdfrest.com";

/* For GDPR compliance and enhanced performance for European users, you can switch to the EU-based service by uncommenting the URL below.
 * For more information visit https://pdfrest.com/pricing#how-do-eu-gdpr-api-calls-work
 */
//$apiUrl = "https://eu-api.pdfrest.com";

PHP opens the .txt source as a PSR-7 stream and includes its filename in the multipart part. The extension selects Plain Text processing without duplicating the format in the options JSON.

$inputPath = '/path/to/sample.txt';
$options = json_decode('{"title":"Structured Content Sample","language":"en-US","enable_tagging":true,"page_setup":{"size":"Letter","orientation":"portrait","margin":{"top":36,"right":42,"bottom":36,"left":42}},"style":{"font":"Arial","heading_font":"Arial","code_font":"Courier","text_size":11,"text_color_rgb":[34,34,34],"heading_scale":1.35,"table":{"column_width_weights":[2,3,2],"keep_header_with_first_row":true,"repeat_headers_on_overflow":true,"show_borders":true,"border_width":0.75,"border_color_rgb":[180,188,200],"header_fill_color_rgb":[33,64,98],"header_text_color_rgb":[255,255,255],"row_fill_color_rgb":[250,250,252],"alternate_row_fill_color_rgb":[235,240,246],"cell_padding":{"top":6,"right":8,"bottom":6,"left":8}}},"plain_text":{"line_handling":"preserve"}}', true);

The array decoded into $options is serialized as pdfRest’s structured_text_options. It describes the PDF title and language, explicitly turns on tagging, chooses Letter portrait pages with 36-point margins, and provides typography plus Plain Text-specific styling.

{
  "plain_text": {
    "line_handling": "preserve"
  }
}

preserve keeps every normalized source line and its spacing in a preformatted block. Windows and legacy carriage-return line endings are normalized consistently. The alternative reflow joins consecutive nonblank lines into paragraphs, using blank lines as paragraph boundaries; reflow is the default when the field is omitted. Only those two values are accepted. When horizontal alignment matters, select a monospaced body font because preserve mode retains characters and spacing but does not force a particular font.

The sample also carries style.table because the repository uses one broad structured-text profile. Plain Text does not create a table, so those table colors, borders, widths, and padding have no effect and may be omitted from a text-only integration.

The PHP multipart array assigns name and contents values to the Plain Text stream, serialized structured_text_options, and requested output name.

// It demonstrates structured_text_options and the format-specific conversion options.
$multipart = [
  ['name' => 'file', 'contents' => Utils::tryFopen($inputPath, 'r'), 'filename' => basename($inputPath)],
  ['name' => 'structured_text_options', 'contents' => json_encode($options)],
  ['name' => 'output', 'contents' => 'pdf_from_text'],
];
$response = (new Client())->post($apiUrl . '/pdf', ['headers' => ['Api-Key' => 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx', 'Accept' => 'application/json'], 'multipart' => $multipart]);
echo $response->getBody();

Guzzle prepares and submits the Plain Text multipart body with the API key. The response body contains generated-resource information on success and service error details when the conversion cannot be completed.

  ['name' => 'file', 'contents' => Utils::tryFopen($inputPath, 'r'), 'filename' => basename($inputPath)],
  ['name' => 'structured_text_options', 'contents' => json_encode($options)],
  ['name' => 'output', 'contents' => 'pdf_from_text'],
];
$response = (new Client())->post($apiUrl . '/pdf', ['headers' => ['Api-Key' => 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx', 'Accept' => 'application/json'], 'multipart' => $multipart]);
echo $response->getBody();

Beyond the Tutorial

PHP systems can generate PDFs from exported notes, server reports, and plain-text correspondence while preserving deliberate spacing where it matters. Tagged output supports structural interpretation, but further evaluation is required before making an accessibility claim.

The conversion profile can be shortened for applications that do not need the full sample styling. Try a representative source in API Lab, and verify available controls in the Convert to PDF API documentation.

Generate a self-service API Key now!
Create your FREE API Key to start processing PDFs in seconds, only possible with pdfRest.