How to Convert a Text File to PDF in PHP
Using a free API, we can easily make consistent text file to PDF conversions.
We can copy from the below ready-to-run PHP code examples to structure our API call. We’ll just need a free Cloudmersive API key to authorize our requests (this will allow a limit of 800 API calls per month with no additional commitments).
Let’s start by installing the SDK. Let’s execute the below command from our command line to install with Composer:
composer require cloudmersive/cloudmersive_document_convert_api_client
Next, let’s call the function using the below code examples. We can supply our text file path in the $input_file
variable:
<?php
require_once(__DIR__ . '/vendor/autoload.php');
// Configure API key authorization: Apikey
$config = Swagger\Client\Configuration::getDefaultConfiguration()->setApiKey('Apikey', 'YOUR_API_KEY');
$apiInstance = new Swagger\Client\Api\ConvertDocumentApi(
new GuzzleHttp\Client(),
$config
);
$input_file = "/path/to/inputfile"; // \SplFileObject | Input file to perform the operation on.
try {
$result = $apiInstance->convertDocumentAutodetectToPdf($input_file);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling ConvertDocumentApi->convertDocumentAutodetectToPdf: ', $e->getMessage(), PHP_EOL;
}
?>
We can write the result of this conversion to a new PDF document.
Conveniently, we can also use this API to convert a variety of other common document formats — including all major Office document file formats (DOCX, XLSX, PPTX, etc.), over 100 image formats, HTML files, etc. — to PDF.