Convert an uploaded file to PDF

So currently there is a form i have, all the code and everything is written. Now what i want help is…there is a flie upload, it can be an image, word or pdf. i need to covert this file to pdf.

I am aware of TCPDF, PHPWord and Imagick. I wanted to know if there is a kirby specific way?

Welcome @chrisdsouza

I have not used this plugin of mine in production for a while but you could still give it a try. It should work for both k3 and k4.

1 Like

Thanks for the reply. However, I am looking for a free option.

25 conversions / day are free. but depending on the scope of your project that might not be enough

It will be more than 25 :frowning:.

No, there isn’t. This is pretty specific and stuff for a plugin rather than core.

ok thanks for the reply

I got a solution..just thought of putting the code out here:

function convertToPDF($filePath, $fileName, $fileType)
    {
        try {
            switch ($fileType) {
                case 'image/jpeg':
                case 'image/png':
                    // Use TCPDF to convert images to PDF
                    $pdf = new TCPDF();
                    $pdf->AddPage();
                    $pdf->Image($filePath, 0, 0, 0, 0, '', '', '', true, 300, '', false, false, 0, false, false, false);
                    $pdfContent = $pdf->Output('', 'S');
                    break;

                case 'application/msword':
                case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document':
                    // Use PHPWord to convert Word documents to PDF
                    $phpWord = PhpWordIOFactory::load($filePath);

                    // Configure PHPWord to use Dompdf
                    PhpWordSettings::setPdfRendererName(PhpWordSettings::PDF_RENDERER_DOMPDF);
                    PhpWordSettings::setPdfRendererPath('.');

                    // Create the PDF writer and capture the output in memory
                    $pdfWriter = PhpWordIOFactory::createWriter($phpWord, 'PDF');
                    ob_start();
                    $pdfWriter->save('php://output');
                    $pdfContent = ob_get_clean();
                    break;

                case 'application/pdf':
                    // For PDF, read the file content
                    $pdfContent = file_get_contents($filePath);
                    if ($pdfContent === false) {
                        throw new Exception('Failed to read PDF file.');
                    }
                    break;

                default:
                    throw new Exception('Unsupported file type!');
            }

            // Encode the PDF content to Base64
            $base64PDF = base64_encode($pdfContent);

            // Return the Base64 encoded PDF
            return $base64PDF;
        } catch (Exception $e) {
            echo "Error: " . $e->getMessage();
        }
    }

This is the just the core code.