Create PDF with CSS and Images

Using Symfony2.3.4

I am creating PDF documents with this package: SpraedPDFGeneratorBundle , and this is its main php class (I think): PDFGenerator.php

I managed to create them just fine, but I don’t know how to set the fontPath parameter to create a CSS-modified PDF with some images in it. Here:

///XController.php $pdfGenerator = $this->get('spraed.pdf.generator'); $pdf = $pdfGenerator->generatePDF($postData/* , 'UTF-8', array(<SOME_PATH_I_GUESS>) */); 

the first parameter is the html data that will be output in PDF, the second one I guessed, but I'm not sure, and the third is fontPath.

Image also has something that I would like to learn about ...

Has anyone ever worked with this package or some other; if so, can you help me?

+7
css image pdf
source share
1 answer

Ok, I found the answer.

You ask two things: how to add images and how to add new fonts .

Adding Images

It is pretty simple. Assuming you are using Twig, you will need to do the following:

 <img src="{{ app.request.scheme ~'://' ~ app.request.httpHost ~ asset("img/MyImage.png") }}" /> 

Of course, you can also make it a macro so you don’t repeat yourself everywhere, for example.

 {% macro image(uri) %} {{ app.request.scheme ~'://' ~ app.request.httpHost ~ asset(uri) }} {% endmacro %} 

And you use it like this

 {% import '::imgurimacro.html.twig' as img %} ... <img src="{{ img.image('img/MyImage.png') }}" /> 

And it should work.

Add fonts

This is a little trickier. First make sure you have the latest version of Spraed PDF Generator. In composer.json:

 "spraed/pdf-generator-bundle": "dev-master" 

If you want to add fonts to a new PDF file, do the following:

 $pdf = $pdfGenerator->generatePDF($postData , 'UTF-8', array('C:\Windows\Fonts\Font1.ttf', 'C:\Windows\Fonts\Font2.ttf')); 

Then create the fonts folder (or any other name of your choice) in the web folder (or wherever you place your resources) and add the .ttf files there.

In your Twig file, add the following as a CSS style:

 @font-face { font-family: "MyFontFamily"; src: {{ app.request.scheme ~'://' ~ app.request.httpHost ~ asset('fonts/Font1.ttf') }}; } 

Now when you write

 <p style="font-family: MyFontFamily">Hello World!</p> 

He should print "Hello World!" using registered font in pdf.

+5
source share

All Articles