How to capture view content in symfony for pdf output - php

I'm using Symfony and mPDF.
I'm trying to integrate both but am running into some problems.
I need to capture the content of a view but can't see how to do it.
public function executePDF(sfWebRequest $request)
{
$this->object = $this->getRoute()->getObject();
require_once 'mpdf.php';
/* Example code from mPDF site */
$mpdf=new mPDF('win-1252','A4','','',20,15,48,25,10,10);
$mpdf->useOnlyCoreFonts = true; // false is default
$mpdf->SetProtection(array('print'));
$mpdf->SetTitle("Acme Trading Co. - Invoice");
$mpdf->SetAuthor("Acme Trading Co.");
$mpdf->SetWatermarkText("Paid");
$mpdf->showWatermarkText = true;
$mpdf->watermark_font = 'DejaVuSansCondensed';
$mpdf->watermarkTextAlpha = 0.1;
$mpdf->SetDisplayMode('fullpage');
$this->setLayout(false);
$html = $this->getResponse()->getContent();
$mpdf->WriteHTML($html);
$mpdf->Output();
exit;
}
With the above example, $html is returned as an empty string. I have a view template relating to this action (PDFSuccess.php) which accesses the $object and has the HTML that mPDF will use.
Thanks for any help.
As it is just now, when accessing this action it does open a PDF correctly, but there is no content in it.
Thanks

Haven't done this in this specific context but you could try:
$html = $this->getPartial('moduleName/partialName');
... where the template is a partial (_partialName) inside a given module. As it's a partial, there's no need to switch off the layout.
You can also pass variables to it:
$html = $this->getPartial('moduleName/partialName', array('var' => 'something'));
...
If that doesn't work, here's a question relating to email templates that contains an alternative way of doing this (see the accepted answer):
Email body in Symfony 1.4 mailer?

Related

How to add watermark to every page using mpdf in laravel

I'm using niklasravnsborg/laravel-pdf package in laravel to generate a pdf. In this code i added watermark but that watermark is coming only on the last page though i wanted that to be in every page.
$pdf = PDFm::loadHtml($result->document);
$pdf->mpdf->SetWatermarkText('DRAFT');
$pdf->mpdf->showWatermarkText = true;
return $pdf->download('hdtuto.pdf');
From the documentation, it should work. Could you however, give the following a try?
$config = ['instanceConfigurator' => function($mpdf) {
$mpdf->SetWatermarkText('DRAFT');
$mpdf->showWatermarkText = true;
}]
PDF::loadHtml($result->document, $config)->download('hdtuto.pdf');
In this case, we are initialising the PDF instance with the right configuration instance, instead of doing it after loading the HTML.
mPDF doc states that
The watermark will be added to each page when the Footer is printed if the variable $showWatermark is set to 1 or true.
Try to add header/footer to your PDF and set corresponding flags
If any one trying to use blade file instead of direct html document, you can use view function which will return html content to the loadHtml method.
$config = ['instanceConfigurator' => function($mpdf) {
$mpdf->SetWatermarkText('DRAFT');
$mpdf->showWatermarkText = true;
}]
$pdf = PDF::loadHtml(view('path.to.blade_file', $blade_data), $config);
return $pdf->stream('DocumentName.pdf');
if you want to use an image as watermark
$config = ['instanceConfigurator' => function ($mpdf) {
$mpdf->SetWatermarkImage(asset('path/to/image_file'));
$mpdf->showWatermarkImage = true;
// $mpdf->watermarkImageAlpha = 0.2; // image opacity
// dd($mpdf) // show all attributes
}];
$pdf = PDF::loadHtml(view('path.to.blade_file', $blade_data), $config);
return $pdf->stream('DocumentName.pdf');

"Preview" mpdf directly to browser

I'm using mpdf and writing a bunch of HTML to the pdf object via mpdf::writeHTML(). Is there any way, rather than outputting an PDF, to simply dump it right back to the browser instead? So, rather than creating the PDF just write it out as a web page?
I want to give the user the option of a PDF or a web page, and rather than branching off for echo or writeHTML for each line, I'd like to build the document and then either output web or PDF.
EDIT TO ADD:
Something like this:
$mpdf = new mpdf();
$mpdf->writeHTML( "<p>Hello World</p>" );
$mpdf->addPage( 'L' );
$mpdf->writeHTML( "<p>Lorem ipsum egg foo yung.</p>" );
if( $_GET['format'] == 'pdf' ) {
$mpdf->output(); //spit out a PDF
} elseif ( $_GET['format'] == 'web' ) {
echo $mpdf->contents_as_html(); // write a web page
}
I'm currently writing each line to a giant string, and then either passing the string to mpdf::writeHTML() or echo; but this doesn't allow me to use various mpdf functions such as addPage(), bookmark(), and so forth.
This is what I did, per a suggestion by #CBroe. When writeHTML() is called, it writes to an internal variable $this->strHTML, and then does its normal process. If the object is cast to string, it returns $this->strHTML
class myPDF extends Mpdf {
private $strHtml = '';
public function writeHTML( $html, $mode = 0, $init = true, $close = true ) {
$this->strHtml .= $html . "\n";
return parent::writeHTML( $html, $mode, $init, $close );
}
public function __toString() {
return $this->strHtml;
}
}
You can choose the output with mPDF by changing the second parameter.
I = send the file inline to the browser.
F enter code here= save to a local file with the name given by $filename.
S = return the document as a string. $filename is ignored.
D = send to the browser and force a file download with the name given by $filename.
Output mPDF:
$mpdf->Output($filename, "I"); // Change "I" to your preferred output
If you choose output the file in your browser, just make sure that you target the output on an empty page. Otherwise it's possible that the header and footer will interfere.
Artikel mPDF output:
https://mpdf.github.io/reference/mpdf-functions/output.html

bulk pdf generation with html2pdf in codeigniter

I am using HTML2PDF library in codeigniter.I am trying to generate bulk pdf using it.
In which i am facing issue like same content in every pdf or pdf have no content.I have already did my homework.Yeah but there is always showing perfect for generated first pdf (For account :3)
As per me there is must be issue of below code :
ob_start();
require_once($template_config.'template.php'); //
$content = ob_get_contents();
ob_clean();
Issue : It works for first time but for second time it flush all the content of content variable and due to that duplicate PDF or without content PDF generate.
I have tried like below
1) create object in generatetemplate.php and pass to common.php
2) tried with include_once //getting same conent in every pdf and if i am doing echo then showing no content for 2nd and 3rd pdf
File structure :
application
controllers
generatetemplate.php
libraries
common.php
html2pdf
html2pdf.php
template.php
common.php :
function print_content($customerdata){
$this->load->library('/html2pdf/html2pdf');
$template_config=$this->config->item('template');
ob_start();
require_once($template_config.'template.php'); //
$content = ob_get_contents();
ob_clean();
$content = str_replace("<CUSTOMER_ADDRESS>",$CUSTOMER_ADDRESS,$content);
$this->CI->html2pdf->pdf->SetDisplayMode('fullpage');
$this->CI->html2pdf->writeHTML($content);
$this->CI->html2pdf->Output($download_path,"F");
}
generatetemplate.php
function __construct() {
parent::__construct();
$this->load->library("common");
$this->load->library('html2pdf');
}
function get_customer_data(){
$this->db->order_by("id","DESC");
$this->db->where('id IN (1,2,3)');
$query = $this->db->get("customers")->result_array();
foreach($query as $key=>$accountdata){
$this->common->print_content($accountdata);
}
}
Any help and ideas will be appreciated.
I have tried below code and its work for me.
Common.php
function print_content($customerdata){
$this->load->library('/html2pdf/html2pdf');
$template_config=$this->config->item('template');
ob_start();
require_once($template_config.'template.php'); //
$content = ob_get_contents();
ob_clean();
$content = str_replace("<CUSTOMER_ADDRESS>",$CUSTOMER_ADDRESS,$content);
$this->CI->html2pdf = new HTML2PDF('P','A4','en'); // Just added this line and its work for me.
$this->CI->html2pdf->pdf->SetDisplayMode('fullpage');
$this->CI->html2pdf->writeHTML($content);
$this->CI->html2pdf->Output($download_path,"F");
}

How to load multiple views to mpdf

Just a quick question. Anyone know if its possible to load multiple views from codeigniter to mpdf controller and convert it to pdf?
my controller :
`
<?php
class C_Pdf extends CI_Controller {
private $params = array();
function __construct() {
parent::__construct();
$this->params['set_tag'] = array();
$this->params['set_css'] = array();
$this->params['set_js'] = array();
$this->params['title_auto'] = true;
$this->params['title'] = '';
}
public function index(){
//this data will be passed on to the view
$data['the_content']='mPDF and CodeIgniter are cool!';
$data['other']="siema heniu cos przeszlo";
//load the view, pass the variable and do not show it but "save" the output into $html variable
$this->load->view('common/default_header',$this->params);
$html=$this->load->view('reservation/complete', $data,true);
$this->load->view('common/default_footer');
//this the the PDF filename that user will get to download
//load mPDF library
$this->load->library('m_pdf');
//actually, you can pass mPDF parameter on this load() function
$pdf = $this->m_pdf->load();
//generate the PDF!
$pdf->WriteHTML($html);
//offer it to user via browser download! (The PDF won't be saved on your server HDD)
$pdf->Output();
}
}?>
i want to add footer and header from other view.
Just prefetch the header and footer templates into variables and pass their parsed strings to the main view ,like this:
$data['header'] = $this->load->view('common/default_header',$this->params, true);
$data['footer'] = $this->load->view('common/default_footer', true);
$html = $this->load->view('reservation/complete', $data, true);
Notice the third parameter to true so that you get the view in a string instead of sending it to output (most commonly the client's browser).
Then in your main template, place the $header and $footer variables wherever you need.

Laravel 5 Include blade templates dynamically (replace div)

I have a CMS where users can create and edit their own content in their websites. I also provide the possibility to include forms and galleries by simply replacing specific Div's in their content.
In the past I simply exploded the content on these Div's to an array, replaced the whole Div's with the needed html code (by using PHP's include) to show the form or gallery at that exact position, imploded the whole array to a string again (html) and used in the website.
Now I am trying to achieve the same in Laravel 5:
// example plugins div in HTML
// ******************************
<div class="plugin form"></div>
// PageController.php
// ******************************
$page = Page::where(('url', '=', "home")->first();
$page->text = Helpers::getPlugins($page->text);
// Helpers.php (a non default custom class with functions)
// ******************************
public static function getPlugins($page)
{
$dom = new DOMDocument();
$dom->loadHTML($page, LIBXML_HTML_NOIMPLIED);
$x = $dom->getElementsByTagName("div");
foreach ($x as $node)
{
if (strstr($node->getAttribute('class'), "plugin"))
{
$plugin = explode(" ",$node->getAttribute('class'));
$filename = base_path() . "/resources/views/plugins/" . trim($plugin[1]) . ".blade.php";
if (is_file($filename))
{
ob_start();
include($filename);
ob_get_contents();
$node->nodeValue = ob_get_clean();
}
else
{
$node->nodeValue = "Plugin <strong>".$node->getAttribute('class')."</strong> Not found</div>";
}
}
}
return $dom->saveHTML();
}
Sofar so good, the content is returned but what I get is all the pure text blade markup instead of the Laravel generated html which I want to use.
I think there is a way this could work but I cannot come to think of it.
Try manually building the template by using the method BladeCompiler->compile(), read more here
Edit: I think the facade Blade::compile() will give you access to this function too, just add use Blade at the top of the file.

Categories