Debug School

rakesh kumar
rakesh kumar

Posted on

how to convertWordToPDF in laravel

why we use Settings::setPdfRendererPath
why we use time().'-'.$file->getClientOriginalName() in laravel
why we use IOFactory::createWriter in laravel

To convert a Word document to a PDF in Laravel, you can use the PhpOffice\PhpWord and dompdf/dompdf packages. Here are the step-by-step instructions:

1.Install the required packages using Composer:

composer require phpoffice/phpword dompdf/dompdf
Enter fullscreen mode Exit fullscreen mode

2.Create a new route in your Laravel application to handle the conversion:

Route::get('/convert-word-to-pdf', function () {
    // Code to convert Word to PDF goes here
});
Enter fullscreen mode Exit fullscreen mode

3.Load the Word document into the PhpWord object:

use PhpOffice\PhpWord\IOFactory;
use PhpOffice\PhpWord\Settings;

Settings::setPdfRendererPath(base_path('vendor/dompdf/dompdf'));
Settings::setPdfRendererName('DomPDF');

$phpWord = IOFactory::load(public_path('document.docx'));
Enter fullscreen mode Exit fullscreen mode

4.Save the PhpWord object as a PDF file:

$objWriter = IOFactory::createWriter($phpWord, 'PDF');
$objWriter->save(public_path('document.pdf'));
Enter fullscreen mode Exit fullscreen mode

5.Return the PDF file to the user:

return response()->file(public_path('document.pdf'));
Enter fullscreen mode Exit fullscreen mode

Here's the complete example:

use PhpOffice\PhpWord\IOFactory;
use PhpOffice\PhpWord\Settings;

Settings::setPdfRendererPath(base_path('vendor/dompdf/dompdf'));
Settings::setPdfRendererName('DomPDF');

Route::get('/convert-word-to-pdf', function () {
    $phpWord = IOFactory::load(public_path('document.docx'));

    $objWriter = IOFactory::createWriter($phpWord, 'PDF');
    $objWriter->save(public_path('document.pdf'));

    return response()->file(public_path('document.pdf'));
});
Enter fullscreen mode Exit fullscreen mode

why we use Settings::setPdfRendererPath

Settings::setPdfRendererPath is a method used in the PHP library "Dompdf" to set the path to the PDF rendering engine executable file. This method is used when you want to generate PDF files from HTML documents using Dompdf.

When you call the method, you need to pass in the path to the PDF rendering engine executable file as a string. Here's an example:

use Dompdf\Dompdf;
use Dompdf\Options;

// Instantiate the Dompdf class
$dompdf = new Dompdf();

// Set the options for the Dompdf class
$options = new Options();
$options->set('isRemoteEnabled', true);

// Set the path to the PDF rendering engine executable file
$options->set('pdfRendererPath', '/usr/bin/wkhtmltopdf');

// Assign the options to the Dompdf class
$dompdf->setOptions($options);

// Load the HTML document you want to convert to PDF
$html = file_get_contents('document.html');

// Convert the HTML document to PDF
$dompdf->loadHtml($html);
$dompdf->render();

// Save the PDF file to disk
file_put_contents('document.pdf', $dompdf->output());
Enter fullscreen mode Exit fullscreen mode

Image description

Image description

In this example, we're using the "wkhtmltopdf" PDF rendering engine, and we're setting the path to its executable file using the Settings::setPdfRendererPath method. We're then using Dompdf to convert an HTML document to PDF, and saving the resulting PDF file to disk.

Note that the specific path to the PDF rendering engine executable file will depend on your system configuration. You may need to adjust the path accordingly.
why we use time().'-'.$file->getClientOriginalName() in laravel
In Laravel, time().'-'.$file->getClientOriginalName() is commonly used to generate a unique filename for uploaded files. This is done to prevent filename conflicts in cases where multiple users upload files with the same name, or when a user uploads multiple files with the same name.

The time() function returns the current Unix timestamp, which is a unique number that represents the current date and time. By appending this timestamp to the original filename using a hyphen, we can ensure that the resulting filename is unique.

Here's an example of how to use this approach to generate a unique filename for an uploaded file in Laravel:

use Illuminate\Http\Request;

// ...

public function upload(Request $request)
{
    // Get the uploaded file from the request
    $file = $request->file('file');

    // Generate a unique filename
    $filename = time().'-'.$file->getClientOriginalName();

    // Store the file in the filesystem
    $file->storeAs('uploads', $filename);

    // ...
}
Enter fullscreen mode Exit fullscreen mode

Image description

In this example, we're using the storeAs() method to store the uploaded file in the "uploads" directory of the filesystem using the generated filename. This ensures that each uploaded file has a unique filename and avoids conflicts with existing files.

why we use IOFactory::createWriter in laravel

In Laravel, IOFactory::createWriter is a method from the PHPExcel library that is used to create Excel files. It is often used to generate Excel files containing data from a database query, an API response or any other data source.

Here is an example of how to use IOFactory::createWriter to create an Excel file in Laravel:

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\IOFactory;

// Create a new Spreadsheet object
$spreadsheet = new Spreadsheet();

// Add some data to the spreadsheet
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1', 'Name');
$sheet->setCellValue('B1', 'Email');
$sheet->setCellValue('C1', 'Phone');

// Retrieve data from database
$data = DB::table('users')->get();

// Loop through the data and add it to the spreadsheet
foreach ($data as $key => $value) {
    $sheet->setCellValue('A' . ($key+2), $value->name);
    $sheet->setCellValue('B' . ($key+2), $value->email);
    $sheet->setCellValue('C' . ($key+2), $value->phone);
}

// Create a new Excel writer
$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');

// Set the headers to download the Excel file
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="users.xlsx"');
header('Cache-Control: max-age=0');

// Output the Excel file to the browser
$writer->save('php://output');

Enter fullscreen mode Exit fullscreen mode

Image description

Image description

In this example, we first create a new Spreadsheet object and add some data to it. We then retrieve data from a database using Laravel's query builder and add it to the spreadsheet using a foreach loop.

Next, we create a new Excel writer using IOFactory::createWriter and pass in the Spreadsheet object and the file format (in this case, Xlsx). We then set the headers to download the Excel file and output it to the browser using the save method of the writer object.

Overall, IOFactory::createWriter is a useful method in Laravel for generating Excel files containing data from various sources

IOFactory::createWriter is a method from the PHPWord library that is used to create Word files, while converting Word to PDF involves a different library called TCPDF. Therefore, IOFactory::createWriter is not directly involved in converting Word to PDF in Laravel.

However, it is still possible to use both libraries together to convert Word files to PDF in Laravel. Here's an example of how to do it:

use PhpOffice\PhpWord\IOFactory;
use \TCPDF;

// Load the Word document
$phpWord = IOFactory::load('path/to/document.docx');

// Create a new PDF object
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

// Set the document metadata
$pdf->SetCreator('Creator');
$pdf->SetAuthor('Author');
$pdf->SetTitle('Title');
$pdf->SetSubject('Subject');

// Add a new page to the PDF
$pdf->AddPage();

// Get the document as HTML
$xmlWriter = IOFactory::createWriter($phpWord, 'HTML');
$html = $xmlWriter->getWriterPart('Document')->write();

// Write the HTML to the PDF
$pdf->writeHTML($html, true, false, true, false, '');

// Output the PDF to the browser
$pdf->Output('document.pdf', 'I');
Enter fullscreen mode Exit fullscreen mode

Image description

Image description

In this example, we first load the Word document using IOFactory::load and create a new TCPDF object. We then set the metadata for the PDF and add a new page to it.

Next, we use IOFactory::createWriter to get the document as HTML and write it to the PDF using the writeHTML method of the TCPDF object. Finally, we output the PDF to the browser using the Output method of the TCPDF object.

Overall, although IOFactory::createWriter is not directly involved in converting Word to PDF, it can still be used to obtain the document as HTML, which can then be written to a PDF using a different library such as TCPDF.

Top comments (0)