File Conversion in PHP, Laravel and Go With One API
PHP and Go apps usually convert files by shelling out to a command line tool installed next to the app: an office suite for Word to PDF, an image tool for photos, a headless browser for HTML. Each one is a large install, a source of stuck processes and another thing to patch. With the PrivConvert file conversion API and its official SDKs, the conversion is one function call and your servers stay small. This guide covers plain PHP, a queued Laravel job and a Go HTTP handler.
PHP
composer require privconvert/privconvert
export PRIVCONVERT_API_KEY=pk_live_... New accounts can start a free trial of 25 conversions without a card. The tool id is the same slug you see in the site's URLs:
use PrivConvert\PrivConvert;
$pc = new PrivConvert(); // reads PRIVCONVERT_API_KEY
$pc->convert('word-to-pdf', 'contract.docx')->save('contract.pdf');
$pc->convert('heic-to-jpg', 'IMG_0420.HEIC', ['quality' => 85])->save('photo.jpg');
$pc->convertBatch('png-to-jpg', ['a.png', 'b.png', 'c.png'])->save('images.zip'); The file can be a path, an open stream or a string you already have in memory (File::fromString). Options such as quality go in the third argument. A batch of up to 20 files comes back as one ZIP.
Laravel: convert in a queued job
Register the client once so it can be injected anywhere:
// app/Providers/AppServiceProvider.php
use PrivConvert\PrivConvert;
public function register(): void
{
$this->app->singleton(PrivConvert::class, fn () => new PrivConvert(config('services.privconvert.key')));
}
// config/services.php
'privconvert' => ['key' => env('PRIVCONVERT_API_KEY')], Then convert in a queued job rather than in the upload request. The user gets an instant response, a slow document never ties up a web worker, and the queue retries temporary failures for you:
// app/Jobs/ConvertToPdf.php
namespace App\Jobs;
use App\Models\Document;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\Storage;
use PrivConvert\Exception\BadRequestException;
use PrivConvert\Exception\ConversionFailedException;
use PrivConvert\Exception\UnsupportedTypeException;
use PrivConvert\File;
use PrivConvert\PrivConvert;
class ConvertToPdf implements ShouldQueue
{
use Queueable;
public int $tries = 3;
public array $backoff = [10, 60];
public function __construct(public Document $document) {}
public function handle(PrivConvert $pc): void
{
$source = Storage::get($this->document->path);
try {
$pdf = $pc->convert('word-to-pdf', File::fromString($source, $this->document->name));
} catch (BadRequestException | UnsupportedTypeException | ConversionFailedException $e) {
$this->document->update(['status' => 'failed', 'error' => $e->getMessage()]);
return; // the file itself is the problem: retrying will not help
}
$pdfPath = preg_replace('/\.\w+$/', '.pdf', $this->document->path);
Storage::put($pdfPath, $pdf->content);
$this->document->update(['status' => 'ready', 'pdf_path' => $pdfPath]);
}
}
// in the upload controller
$document = Document::create([
'path' => $request->file('file')->store('documents'),
'name' => $request->file('file')->getClientOriginalName(),
]);
ConvertToPdf::dispatch($document); Note the split in the error handling. When the file itself is the problem (not a Word document, damaged, password protected) the job marks it failed and stops, because a retry would fail again. Rate limits and server errors are thrown, so Laravel retries them with the backoff you set. The SDK already retries short rate limit responses on its own before that.
Go
go get github.com/toprivHQ/privconvert-go The main module uses only the standard library. Here is a complete HTTP service that accepts a Word document and returns the PDF:
package main
import (
"errors"
"io"
"log"
"net/http"
"github.com/toprivHQ/privconvert-go"
)
func main() {
pc, err := privconvert.New() // reads PRIVCONVERT_API_KEY
if err != nil {
log.Fatal(err)
}
http.HandleFunc("POST /to-pdf", func(w http.ResponseWriter, r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, 50<<20)
f, hdr, err := r.FormFile("file")
if err != nil {
http.Error(w, "missing file", http.StatusBadRequest)
return
}
defer f.Close()
data, err := io.ReadAll(f)
if err != nil {
http.Error(w, "upload too large", http.StatusRequestEntityTooLarge)
return
}
res, err := pc.Convert(r.Context(), "word-to-pdf",
privconvert.File{Name: hdr.Filename, Data: data}, nil)
switch {
case errors.Is(err, privconvert.ErrBadRequest),
errors.Is(err, privconvert.ErrUnsupportedType),
errors.Is(err, privconvert.ErrConversionFailed):
http.Error(w, "this document could not be converted", http.StatusUnprocessableEntity)
return
case errors.Is(err, privconvert.ErrRateLimit):
http.Error(w, "busy, try again shortly", http.StatusServiceUnavailable)
return
case err != nil:
http.Error(w, "conversion service error", http.StatusBadGateway)
return
}
w.Header().Set("Content-Type", "application/pdf")
w.Write(res.Content)
})
log.Fatal(http.ListenAndServe(":8080", nil))
} Errors are matched with errors.Is, so mapping them to your own status codes is a short switch. The request context is passed through, so a client that disconnects cancels the conversion too.
Many files at once
files := make([]privconvert.File, 0, 20)
for _, p := range paths[:min(20, len(paths))] {
data, err := os.ReadFile(p)
if err != nil {
return err
}
files = append(files, privconvert.File{Name: filepath.Base(p), Data: data})
}
zip, err := pc.ConvertBatch(ctx, "word-to-pdf", files, nil)
if err != nil {
return err
}
if zip.Partial() {
log.Printf("%d files skipped, see PRIVCONVERT-ERRORS.txt in the ZIP", zip.FailedCount())
}
return zip.Save("pdfs.zip") One batch counts as a single request against your per-minute rate limit. If a few files in the batch fail, the rest are still converted and the ZIP lists what was skipped.
Files already in cloud storage
If uploads land in S3, Google Cloud Storage, Azure, Cloudflare R2 or Backblaze B2, both SDKs can read the file from the bucket and write the result back in one call (convertStorage in PHP, ConvertStorage in Go). The transfer happens from your server with your own credentials, which are never sent to us.
Long conversions
Most conversions finish in a second or two. For large presentations or long documents, submit an async job and either wait for it in a worker or receive a signed webhook when it is done. Webhooks vs polling explains when to pick which.
What happens to the files
Files sent for direct conversion are processed in memory and the result is returned in the same response. Nothing is written to disk and no copy is kept. Every PDF we return also has the producing software and timestamps removed from its metadata, so your documents do not advertise how they were made. More in a file conversion API that does not store files.
Using Python or Node.js instead? See how to convert DOCX to PDF in Node.js and Python.
FAQ
Do I need an office suite, image tools or a headless browser on my server?
No. The conversion runs on our side, so your PHP or Go app only needs the SDK. There is nothing to install in your containers and nothing to patch when a document format changes.
Which PHP and Go versions are supported?
The PHP SDK needs PHP 8.1 or newer and works with any framework, including Laravel and Symfony. The Go SDK uses only the standard library in its main module, so it adds no dependencies to your build.
Can I convert files that are already in S3, Google Cloud Storage or Azure?
Yes. Both SDKs have a storage helper that reads the file from your bucket and writes the result back, using your own credentials. Your cloud keys are never sent to us.
What about long conversions like large presentations?
Submit them as async jobs and either wait in a worker or receive a signed webhook when the result is ready. Both SDKs include job and webhook verification helpers.
Are files stored?
Direct conversions are processed in memory and returned in the same response, with nothing written to disk. Async job results wait in memory, encrypted with a key only you hold, for up to 30 minutes, and the SDKs delete them as soon as they are downloaded.