Laravel word to pdf

In this article, we will learn how to convert Word to PDF In Laravel. Recently, one of our clients wants to develop functionality in Laravel & Vue based CMS.

In that, he wants to upload a Word document as a template, and then we need to replace some data into the Word file. After that Word file should be converted into a PDF file and make available for the user to download. After googling for some time, We have found very nice libraries for Laravel at GitHub, PHP Word, and DOMPDF Wrapper for Laravel-dompdf.

Here I am going to share how can you easily install that package and convert your Word file To PDF with dynamic data in Laravel.

I can say you, its easy !! We have made it very simple and step by step.

Let’s start. We are preassuming that you already have a Laravel project set up on your machine either it’s a fresh installation or an existing Laravel application.

Laravel: Convert Word To PDF

01 Installing Packages

Most of the Laravel developers know the term “Packages”, if not then read the following definition:

A package is a piece of reusable code that can be dropped into any application and be used without any tinkering to add functionality to that code. You don’t need to know what is happening inside, only what the API for the class(es) are so that you can archive your goal

We don’t need to worry about the packages. It has some files and code inside it but one thing is for sure that it will solve our problem faster than we might think.

We hope you are now clear with the packages. Let’s go ahead.

To install a package you need to first have Composer on your machine. A Composer is a PHP package manager that is used to download and install packages for our projects.

It’s very easy to install the composer. Have a look here and follow the steps and you are good to go https://getcomposer.org/download/

Now, open your command-line tool and navigate it to the directory, our is laravel-demos where your project installed. We are using Git Bash as a command-line tool, you can use your own or you can install Git Bash from here as per your OS: https://git-scm.com/downloads

Install Package In Laravel To Convert Word To Doc

Run the following commands one by one:

composer require barryvdh/laravel-dompdf
composer require phpoffice/phpword

Now, wait until your installation finishes the process

laravel package install

You are now done with packages installations. Let’s move on next step.

02 Register Service Provider In config/app.php

To register the service provider, open the config/app.php file. And add the following line in 'providers' array at the end:

'providers' => [
 .....
 BarryvdhDomPDFServiceProvider::class,
]

Also, add the following line to the 'aliases' array at the end. You can use any aliases as you want like we have used ‘PDF’ but you can also use aliases like ‘DoPDF’, ‘myPDF’, ‘PF’, etc

We shouldn’t worry about the aliases, It’s just a short form of service provider class so that we don’t need to write the whole path while using it in Controllers. Hope you are getting it. Great!

'aliases' => [
 .....
 'PDF' => BarryvdhDomPDFFacade::class,
]

03 Register Route In routes/web.php

Open the routes/web.php file to add or register a new route. You can create routes as per your Controller and Method. Here, we have DocumentController, and in that, we have convertWordToPDF() method. So now our route will look like as below:

Route::get('/document/convert-word-to-pdf', 'DocumentController@convertWordToPDF')->name('document.wordtopdf');

Now, add that route to any anchor or button.

<a href="{{ route('document.wordtopdf') }}">Convert Word To PDF</a>

04 Create Controller

Now, we are moving forward to the end of this tutorial so hold tight and let’s move on.

Let’s now create a controller. You can create it by copying any other controller code or run the following command in your command-line tool.

php artisan make:controller DocumentController

After running the above command a new file has been created into your app/Http/Controllers/DocumentController.php

Open the controller file and write down the following code into it.

app/Http/Controllers/DocumentController.php

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;
use PDF;

class DocumentController extends Controller
{
    public function convertWordToPDF()
    {
    	    /* Set the PDF Engine Renderer Path */
	    $domPdfPath = base_path('vendor/dompdf/dompdf');
	    PhpOfficePhpWordSettings::setPdfRendererPath($domPdfPath);
	    PhpOfficePhpWordSettings::setPdfRendererName('DomPDF');
	    
	    //Load word file
	    $Content = PhpOfficePhpWordIOFactory::load(public_path('result.docx')); 

	    //Save it into PDF
	    $PDFWriter = PhpOfficePhpWordIOFactory::createWriter($Content,'PDF');
	    $PDFWriter->save(public_path('new-result.pdf')); 
	    echo 'File has been successfully converted';
    }
}

Now, put the result.docx file into your public folder

Now access the URL /document/convert-word-to-pdf and hit the Convert Word To PDF button. It will save a PDF file into your public directory with a new name new-result.pdf. Hurray! Drum the roll.

Laravel: Dynamically Change The Content In Word File And Convert To PDF

There is some requirement where you need to replace some text in the Doc file prior to converting to the PDF file. In that situation use the setValue() function provided by the PHPWord library.

Let’s say, we have a Word file with following text:

${date}

Dear Sir/Madam,

Re:  ${title} ${firstname} ${lastname} 

I’d be grateful if you could also send me information on the plan detailed above, together with any other plans that I may hold with you.

Please note that all the placeholder should be prefix with $ and wrap with {} braces like ${date}.

Now, we want to replace all the above placeholder with the text. So your Controller should look like below:

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;
use PDF;

class DocumentController extends Controller
{
    /* Laravel Convert Word To PDF Tutorial
     * By ScratchCode.io
     */
    public function convertWordToPDF()
    {
    	/* Set the PDF Engine Renderer Path */
	    $domPdfPath = base_path('vendor/dompdf/dompdf');
	    PhpOfficePhpWordSettings::setPdfRendererPath($domPdfPath);
	    PhpOfficePhpWordSettings::setPdfRendererName('DomPDF');
	    
	    /*@ Reading doc file */
        $template = newPhpOfficePhpWordTemplateProcessor(public_path('result.docx'));

        /*@ Replacing variables in doc file */
        $template->setValue('date', date('d-m-Y'));
        $template->setValue('title', 'Mr.');
        $template->setValue('firstname', 'Scratch');
        $template->setValue('lastname', 'Coder');

        /*@ Save Temporary Word File With New Name */
        $saveDocPath = public_path('new-result.docx');
        $template->saveAs($saveDocPath);
        
        // Load temporarily create word file
        $Content = PhpOfficePhpWordIOFactory::load($saveDocPath); 

        //Save it into PDF
        $savePdfPath = public_path('new-result.pdf');

        /*@ If already PDF exists then delete it */
        if ( file_exists($savePdfPath) ) {
            unlink($savePdfPath);
        }

        //Save it into PDF
	    $PDFWriter = PhpOfficePhpWordIOFactory::createWriter($Content,'PDF');
	    $PDFWriter->save($savePdfPath); 
	    echo 'File has been successfully converted';

	    /*@ Remove temporarily created word file */
        if ( file_exists($saveDocPath) ) {
            unlink($saveDocPath);
        }
    }
}

And after the Laravel converting Word To PDF your PDF will look like below:

25-12-2020

Dear Sir/Madam,

Re: Mr. Scratch Coder

I’d be grateful if you could also send me information on the plan detailed above, together with any other plans that I may hold with you.

Tips For Laravel Convert Word To PDF

You might have some formatting issues while converting from Word To PDF. Don’t panic, it happens. If you can’t able to solve it yourself then raise the issue here: https://github.com/PHPOffice/PHPWord/issues

Additionally, read our guide:

  1. Best Way to Remove Public from URL in Laravel
  2. Error After php artisan config:cache In Laravel
  3. Specified Key Was Too Long Error In Laravel
  4. AJAX PHP Post Request With Example
  5. How To Use The Laravel Soft Delete
  6. How To Add Laravel Next Prev Pagination
  7. cURL error 60: SSL certificate problem: unable to get local issuer certificate
  8. Difference Between Factory And Seeders In Laravel
  9. Laravel: Increase Quantity If Product Already Exists In Cart
  10. How To Calculate Age From Birthdate
  11. How to Convert Base64 to Image in PHP
  12. Check If A String Contains A Specific Word In PHP
  13. How To Find Duplicate Records in Database
  14. Laravel Send Mail From Localhost

That’s it for now. We hope this article helped you in Laravel Convert Word To PDF process.

Please let us know in the comments if everything worked as expected, your issues, or any questions. If you think this article saved your time & money, please do comment, share, like & subscribe. Thank you in advance. 🙂 Keep Smiling! Happy Coding!

How To Convert Word To PDF In Laravel.png
How To Convert Word To PDF In Laravel.png

In this post, we’ll learn the way to convert Word to PDF In Laravel. Sometimes we’d like to implement this feature in web applications. In that, he will upload a word file, and we will convert that word file into a PDF using the Laravel library.

We will use two libraries for the word to PDF conversion. the primary one is PHPWord and the other is LARAVEL-DOMPDF.

PHPWord is a library written in pure PHP that gives a collection of classes to put in writing and browse from different document file formats. The present version of PHPWord supports Microsoft Office Open XML (OOXML or OpenXML), OASIS Open Document Format for Office Applications (OpenDocument or ODF), and Rich Text Format (RTF), HTML, and PDF.

DOMPDF is a wrapper for Laravel, and It offers robust performance for PDF conversion in Laravel applications spontaneously.

Step 1: Create Laravel Project.
composer create-project laravel/laravel doc-to-pdf --prefer-dist
Step 2: Install the below library one by one.
composer require barryvdh/laravel-dompdf
composer require phpoffice/phpword
Step 3: Register Service Provider In config/app.php.

To register the service provider, open the config/app.php file. And add the following line in the ‘providers‘ array at the end and also add aliases array at the end.

'providers' => [
 .....
 BarryvdhDomPDFServiceProvider::class,
]

'aliases' => [
 .....
 'PDF' => BarryvdhDomPDFFacade::class,
]

Step 3: Create Route in web.php.

Open the routes/web.php file and create the below route.

use AppHttpControllersConvertController;

Route::get('/doc-to-pdf', [ConvertController::class, 'convertDocToPDF']);
Step 4: Create Controller.
php artisan make:controller ConvertController

After creating the controller open it and below the line of code.

<?php

namespace AppHttpControllers;
use IlluminateHttpRequest;
use PDF;

class ConvertController extends Controller
{
    public function convertDocToPDF(){
         $domPdfPath = base_path('vendor/dompdf/dompdf');
         PhpOfficePhpWordSettings::setPdfRendererPath($domPdfPath);
         PhpOfficePhpWordSettings::setPdfRendererName('DomPDF'); 
         $Content = PhpOfficePhpWordIOFactory::load(public_path('sample.docx')); 
         $PDFWriter = PhpOfficePhpWordIOFactory::createWriter($Content,'PDF');
         $PDFWriter->save(public_path('doc-pdf.pdf')); 
         echo 'File has been successfully converted';
    }
}

Now, put the sample.docx file into your public folder.

Step 5: Add the Below link to the view file.
 <a href="{{ url('convert-word-to-pdf') }}">Convert Word To PDF</a>

Event Calendar Example In Laravel.                       Laravel Autocomplete Search Using Typeahead JS.

In this post, we’ll learn the way to convert Word to PDF In Laravel. Sometimes we’d like to implement this feature in web applications. In that, he will upload a word file, and we will convert that word file into a PDF using the Laravel library.

We will use two libraries for the word to PDF conversion. the primary one is PHPWord and the other is LARAVEL-DOMPDF.

PHPWord is a library written in pure PHP that gives a collection of classes to put in writing and browse from different document file formats. The present version of PHPWord supports Microsoft Office Open XML (OOXML or OpenXML), OASIS Open Document Format for Office Applications (OpenDocument or ODF), and Rich Text Format (RTF), HTML, and PDF.

DOMPDF is a wrapper for Laravel, and It offers robust performance for PDF conversion in Laravel applications spontaneously.

Step 1: Create Laravel Project.

composer create-project laravel/laravel doc-to-pdf –prefer-dist

Step 2: Install the below library one by one.

composer require barryvdh/laravel-dompdf
composer require phpoffice/phpword

Step 3: Register Service Provider In config/app.php.

To register the service provider, open the config/app.php file. And add the following line in the ‘providers‘ array at the end and also add aliases array at the end.

‘providers’ => [
…..
BarryvdhDomPDFServiceProvider::class,
]

‘aliases’ => [
…..
‘PDF’ => BarryvdhDomPDFFacade::class,
]

Step 3: Create Route in web.php.

Open the routes/web.php file and create the below route.

use AppHttpControllersConvertController;

Route::get(‘/doc-to-pdf’, [ConvertController::class, ‘convertDocToPDF’]);

Step 4: Create Controller.

php artisan make:controller ConvertController

After creating the controller open it and below the line of code.

<?php

namespace AppHttpControllers;
use IlluminateHttpRequest;
use PDF;

class ConvertController extends Controller
{
public function convertDocToPDF(){
$domPdfPath = base_path(‘vendor/dompdf/dompdf’);
PhpOfficePhpWordSettings::setPdfRendererPath($domPdfPath);
PhpOfficePhpWordSettings::setPdfRendererName(‘DomPDF’);
$Content = PhpOfficePhpWordIOFactory::load(public_path(‘sample.docx’));
$PDFWriter = PhpOfficePhpWordIOFactory::createWriter($Content,’PDF’);
$PDFWriter->save(public_path(‘doc-pdf.pdf’));
echo ‘File has been successfully converted’;
}
}

Now, put the sample.docx file into your public folder.

Step 5: Add the Below link to the view file.

<a href=”{{ url(‘convert-word-to-pdf’) }}”>Convert Word To PDF</a>

Event Calendar Example In Laravel.                       Laravel Autocomplete Search Using Typeahead JS.

The post How To Convert Word To PDF In Laravel appeared first on PHPFOREVER.

You can use the PHPWord library to read the contents of a .docx file, and then use another library such as Dompdf or mPDF to convert the contents to a .pdf file.
Here is an example:

use PhpOfficePhpWordIOFactory;
use DompdfDompdf;

$phpWord = IOFactory::load('path/to/file.docx');

$dompdf = new Dompdf();
$dompdf->loadHtml($phpWord->saveHTML());
$dompdf->render();
$dompdf->stream();

You can also use the package like «phpoffice/phpword» and «barryvdh/laravel-dompdf»

composer require phpoffice/phpword
composer require barryvdh/laravel-dompdf

and then use them in the controller to convert docx to pdf

use PhpOfficePhpWordPhpWord;
use BarryvdhDomPDFFacade as PDF;

$phpWord = new PhpWord();
$phpWord->loadTemplate('path/to/file.docx');

$pdf = PDF::loadView('view', compact('phpWord'))->save('path/to/file.pdf');

In this post, we will learn the way to convert Word to PDF in Laravel. Sometimes we want to implement this feature in web applications. In doing so, it will upload a word file, and we will convert the word file to a PDF file using the Laravel library.

We will use two directories to convert the word to PDF. The main one is PHPWord And the other is LARAVEL-DOMPDF.

PHPWord Is a directory written in pure PHP that gives a collection of classes to upload in writing and browse through various file file formats. The current version of PHPWord supports Microsoft Office Open XML (OOXML or OpenXML), OASIS Open Document Format for Office applications (OpenDocument or ODF), and Rich Text Format (RTF), HTML and PDF.

DOMPDF Is a shell for Laravel, and it offers powerful performance for converting PDF in Laravel applications spontaneously.

Step 1: Create a Laravel project.
composer create-project laravel/laravel doc-to-pdf --prefer-dist
Step 2: Install the directory down one by one.
composer require barryvdh/laravel-dompdf
composer require phpoffice/phpword
Step 3: Register a service provider in config / app.php.

To register your service provider, open e config / app.php file. And add the following line in ‘Suppliers‘Array at the end and also add Nicknames Array at the end.

'providers' => [
 .....
 BarryvdhDomPDFServiceProvider::class,
]

'aliases' => [
 .....
 'PDF' => BarryvdhDomPDFFacade::class,
]

Step 3: Create a route in web.php.

open The tracks / web.php File and create the route below.

use AppHttpControllersConvertController;

Route::get('/doc-to-pdf', [ConvertController::class, 'convertDocToPDF']);
Step 4: Create a controller.
php artisan make:controller ConvertController

After creating the controller open it and below the line of code.

<?php

namespace AppHttpControllers;
use IlluminateHttpRequest;
use PDF;

class ConvertController extends Controller
{
    public function convertDocToPDF(){
         $domPdfPath = base_path('vendor/dompdf/dompdf');
         PhpOfficePhpWordSettings::setPdfRendererPath($domPdfPath);
         PhpOfficePhpWordSettings::setPdfRendererName('DomPDF'); 
         $Content = PhpOfficePhpWordIOFactory::load(public_path('sample.docx')); 
         $PDFWriter = PhpOfficePhpWordIOFactory::createWriter($Content,'PDF');
         $PDFWriter->save(public_path('doc-pdf.pdf')); 
         echo 'File has been successfully converted';
    }
}

Now, put the sample.docx File in your public folder.

Step 5: Add the link below to the view file.
 <a href="https://phpforever.com/laravelexample/how-to-convert-word-to-pdf-in-laravel/{{ url("convert-word-to-pdf') }}">Convert Word To PDF</a>

Example of an event calendar in Laravel. Laravel Autocomplete search using Typeahead JS.

Source

The Pdf Gear

Build Status
Latest Stable Version
Total Downloads
License

This project started life as a DOCX templating engine. It has now envolved to
also support converting HTML to PDF using a headless version of webkit,
phantomjs.

The DOCX templating is great for documents that end clients update and manage
over time, particularly text heavy documents. For example I use it to auto
generate some legal contracts, where simple replacements are made for attributes
like First Name, Last Name, Company Name & Address. The client, an insurance
company, can provide updated template word documents that might contain subtle
changes to policies & other conditions.

The HTML to PDF engine is great for cases where greater control over the design
of the document is required. It’s also more natural for us programmers, using
standard HTML & CSS, with a splash of Javscript.

How to Install

Installation via composer is easy:

composer require gears/pdf:*

You will also need to add the following to your root composer.json file.

"scripts":
{
	"post-install-cmd": ["PhantomInstaller\Installer::installPhantomJS"],
	"post-update-cmd": ["PhantomInstaller\Installer::installPhantomJS"]
}

DOCX: If you are going to be using the DOCX templating you will need to
install either libre-office-headless or unoconv on your host.

How to Use, the basics

Both APIs are accessed through the main Pdf class.

To convert a word document into a PDF without any templating:

$pdf = GearsPdf::convert('/path/to/document.docx');

To save the generated PDF to a file:

GearsPdf::convert('/path/to/document.docx', '/path/to/document.pdf');

To convert a html document into a PDF:

$pdf = GearsPdf::convert('/path/to/document.html');

NOTE: The save to file works just the same for a HTML document.

DOCX Templating

By default the DOCX backend defaults to using libre-office-headless,
to use unoconv, override the converter like so:

$document = new GearsPdf('/path/to/document.docx');
$document->converter = function()
{
	return new GearsPdfDocxConverterUnoconv();
};
$document->save('/path/to/document.pdf');

NOTE: Currently the HTML backend only uses phantomjs.

There are several templating methods for the DOCX engine.
The first is setValue, this replaces all instances of
${FOO} with BAR

$document->setValue('FOO', 'BAR');

To clone an entire block of DOCX xml, you surround your block with tags like:
${BLOCK_TO_CLONE} & ${/BLOCK_TO_CLONE}. Whatever content is
contained inside this block will be repeated 3 times in the generated PDF.

$document->cloneBlock('BLOCK_TO_CLONE', 3);

If you need to replace an entire block with custom DOCX xml you can.
But you need to make sure your XML conforms to the DOCX standards.
This is a very low level method and I wouldn’t normally use this.

$document->replaceBlock('BLOCK_TO_REPLACE', '<docx><xml></xml></docx>');

To delete an entire block, for example you might have particular
sections of the document that you only want to show to certian users.

$document->deleteBlock('BLOCK_TO_DELETE');

Finally the last method is useful for adding new rows to tables.
Similar to the cloneBlock method. You place the tag in first cell
of the table. This row is the one that gets cloned.

$document->cloneRow('ROW_TO_CLONE', 5);

For more examples please see the Unit Tests.
These contain the PHP code to generate the final PDF along with the original DOCX templates.

NOTE: The HTML to PDF converter does not have these same templating functions.
Obviously it’s just standard HTML that you can template how ever you like.

HTML PhantomJs Print Environment

This is still in development and subject to radical change.
So I won’t document this section just yet…

Credits

The DOCX templating code originally came from
PHPWord

You may still like to use PHPWord to generate your DOCX documents.
And then use this package to convert the generated document to PDF.


Developed by Brad Jones — brad@bjc.id.au

Понравилась статья? Поделить с друзьями:
  • Latin word for community
  • Laravel export to excel
  • Latin word for clothing
  • Laravel excel style cells
  • Latin word for clever