Image background does not appear on pdf - TCPDF Laravel 8 - php

I have a problem, I can't show the background image on the pdf, the output is only white blank pdf. I've checked the path to the background image and it's accessible. However, when you want to use it as a background, the image will not appear in the pdf.
I'm using laravel 8 with tcpdf ^^ Please help
public function savePDF($id)
{
$dokumen = Sertifikat::where('id',$id)->first();
$path = Storage::url('dokumen/').$dokumen->image;
PDF::SetTitle("Certificate");
PDF::AddPage('L','A4');
PDF::setImageScale(1);
PDF::SetAutoPageBreak(false, 0);
PDF::Image($path, 0, 0, 210, 297, '', '', '', false, 300, '', false, false, 0);
$view = \View::make('sertifikat.view', ['sertifikat'=>$dokumen]);
$html_content = $view->render();
PDF::writeHTML($html_content, true, false, true, false, '');
// D is the change of these two functions. Including D parameter will avoid
// loading PDF in browser and allows downloading directly
PDF::Output('Certificate.pdf');
}
Controller
https://pastebin.com/8RhNB5LF
View
https://pastebin.com/gPFMUGJi
Error section on the website
https://afgalaxy.com/sertifikat

Related

In the model, click on the button to download the pdf file, But not working (Laravel)

I have products. Products have 1product(model).If user click button download pdf in model. I create function create pdf but not working.
Pdf Generator function in this controller
public static function pdf_g(){
// HTML
$html = '<h1>This html</h1>';
// CREATE NEW PDF
$mpdf = new Mpdf();
// WRITE HTML
$mpdf->WriteHTML($html);
// DEST: D - DOWNLOAD
return $mpdf->Output('asd.pdf', 'D');
}
Controller SEND RESPONSE->JSON mpdf
public function show_cadastre(Folder $folder,Cadastre $cadastre){
// GET THIS CADASTRE ID VALDOS
$get_valdos = Valdos_matmenys::where('KAD_ID', $cadastre->ID)->first();
// GET VISAS_PLOTAS
$visas_plotas = round($get_valdos->PLOTAS_K / 10000, 2);
// GET MISKO
$misko = round($get_valdos->MISK / 10000, 2);
// GET Vandens plotas
$vandens = round($get_valdos->PLOTAS_V / 10000, 2) ;
// GET KITO PLOTO
$kito_ploto = round($visas_plotas - ($misko + $vandens), 2);
// GET Girininkija
$girininkija = $cadastre->GIRININKIJ;
// GET Apskirtis
$apskirtis = Savivaldybe::where('SAV_ID', $cadastre->SAV_ID)->first();
$apskirtis_pav = $apskirtis->apskritis;
// GET Uredija
$uredija = Uredija::where('ured', $cadastre->ured)->first();
$ured_pavadinimas = $uredija->pavadinimas;
// GET Rajonas
$raj = Cadastre::getRagion($cadastre->RAJ);
// GET MAP
$mapUrl = Cadastre::GenerateMap($cadastre->NTR_ID, array('style' => 'ORTOFOTO_TIK_VALDA', 'offsetRatio' => 0.3))[0];
// GET BACKGROUND
$backgroundUrl = Cadastre::GenerateMap($cadastre->NTR_ID, array('style' => 'ORTOFOTO_TIK_VALDA', 'offsetRatio' => 0.3))[1];
// CREATE PDF FOR Zemelapis is virsaus
// PDF DOWNLOAD
$mpdf = self::pdf_g();
return response()->json(array(
'cadastre' => $cadastre,
'visas_plotas' => $visas_plotas,
'misko' => $misko,
'vandens' => $vandens,
'kito_ploto' => $kito_ploto,
'girininkija' => $girininkija,
'apskirtis_pav' => $apskirtis_pav,
'ured_pavadinimas' => $ured_pavadinimas,
'raj' => $raj,
'mapUrl' => $mapUrl,
'backgroundUrl' => $backgroundUrl,
'mpdf' => $mpdf
));
}
Html button (this button is in the model)
<a id="pdfMapFromTop" class="text-center text-decoration-none text-smooth-dark p-1">
<span class="align-self-center">
<i class="fa fa-file-pdf text-danger"></i>
</span>
<span class="text-default-dark small align-self-center d-inline-flex flex-column">Žemėlapis_iš_viršaus.pdf</span>
</a>
Jquery model show.
$.ajax({
type: "GET",
crossDomain: true,
url: '/dashboard/folder/' + folder_id + '/cadastre/' + cadastre_id,
success: function (data) {
console.log(data)
// KODASTRINES NUMERIS
$('#ID').text(data.cadastre.ID);
// get visas_plotas
$('#visas_plotas').text(data.visas_plotas + 'ha');
// get misko
$('#misko').text(data.misko + 'ha');
// get vandens
$('#vandens').text(data.vandens + 'ha');
// get kito_ploto
$('#kito_ploto').text(data.kito_ploto + 'ha');
// get girininkija
$('#girininkija').text(data.girininkija);
// get apskirtis
$('#apskirtis').text(data.apskirtis_pav);
// get uredija
$('#uredija').text(data.ured_pavadinimas);
// get rajonas
$('#rajonas').text(data.raj);
// get map url (img)
$('#mapUrl').attr('src', data.mapUrl);
// get map backgroundUrL (img)
$('#backgroundUrl').attr('src', data.backgroundUrl);
// If click this button download pdf
$('#pdfMapFromTop').on('click', function () {
return data.mpdf;
})
// Show this model
$('#show-cadastre-model-xl').modal('show');
},
// error: function (error) {
// console.log(error);
// }
});
The problem is when I click to open the model. Shows such incomprehensible text in the console.
Help please! Thanks all!!!!
this is your raw pdf data!
all you need is to load it to a blade
look at here
$license = license::findOrFail($id);
$data = [
'license' => $license,
'user' => Auth::user(),
'labels' => LicValues::where('license_id',$id)->get()
];
return PDF::loadView('print', $data)->download('print.pdf');
i wrote this couple weeks ago .dont know its your package or not but solution is same
i loaded my data in blade called print and then download it as pdf
read your package documentaion and issues you will find your solution
Looks like your response doesn't have necessary headers. Tell browser, that the response is PDF and it should be downloaded. You are passing text/html here.
Pass this:
Content-type:application/pdf
Check this:
correct PHP headers for pdf file download
Bonus:
This is the best method to generate/store/download the PDFs.
The DOMPDF Laravel wrapper.
https://github.com/barryvdh/laravel-dompdf

How do you save a PDF with FDPF using parameters?

I have this button, that is tied to this function:
$('#genPDF').click(function () {
var str = "hText=something" +
"&cText=also something";
$.ajax({
url: "/wp-content/themes/mytheme/indexpdf.php",
data: str,
cache: false,
success: function (result) {
console.log("Success!");
$("#pdfobject").attr("src", "/wp-content/themes/mytheme/flyer.pdf");
var container = document.getElementById("pdfContainer");
var content = container.innerHTML;
container.innerHTML = content;
}
});
});
To explain what the successful ajax code does, first outputs "success!" in the console, which the browser does, then replaces a certain div on the page with a revised link (refreshing a certain part of the page).
This above code works, and makes it's way over to indexpdf.php, which is:
<?php
$hText = trim(isset($_GET['hText']) ? $_GET['hText'] : '');
$cText = trim(isset($_GET['cText']) ? $_GET['cText'] : '');
require_once('fpdf.php');
require_once('fpdi.php');
// initiate FPDI
$pdf = new FPDI();
$pdf->AddPage();
$pdf->setSourceFile("TestFlyer.pdf");
$tplIdx = $pdf->importPage(1);
$pdf->useTemplate($tplIdx, 10, 10, 100);
$pdf->SetFont('Helvetica');
$pdf->SetTextColor(255, 0, 0);
$pdf->SetXY(30, 30);
$pdf->Write(0, $hText.$cText);
$pdf->Output("D","flyer.pdf");
?>
The problem is, it's supposed to take testflyer.pdf, load it's first page and write my passed in arguments into it. THEN, save itself as flyer.pdf.
It's not saving, I don't know what's doing on or what the problem is.
All PDF's and PHP files above are in the /mytheme/ folder.
If you want to save the PDF, set the dest parameter as F:
So,
$pdf->Output("D","flyer.pdf");
must be:
$pdf->Output("F","flyer.pdf");
And reformat your write line as:
$pdf->Write(0, "$hText $cText");
According to the documentation, destination where to send the document. It can be one of the following:
I: send the file inline to the browser. The PDF viewer is used if available.
D: send to the browser and force a file download with the name given by name.
F: save to a local file with the name given by name (may include a path).
S: return the document as a string.
The default value is I.

Export List View Data to Pdf

I am using Clist View to show data such list top post on facebook. Now there is a download option . I want to download Clist view data in pdf format . I search on google but i don't find and best example. What should i do to download data of clist view in pdf format.
List view widget:
$this->widget('zii.widgets.CListView', array(
'dataProvider' => $data_top_posts,
'id' => 'tbl-top-posts',
'itemView' => '_top_posts',
'template' => '{items}',
'beforeAjaxUpdate' => 'js:function(id, data){
$("#" + id + " .items span.empty").html("Loading... Please wait.");
}',
'afterAjaxUpdate' => 'js:function(){
setProgressBar("#tbl-top-posts");
}',
'viewData' => array(
'id' => 'tbl-top-posts',),
));
There is no build-in function for such thing. But you can make that:
Use HTML template to print out your view and than pass that content to TCPDF
Example
$pdf->AddPage();
$html = $this->renderPartial('view', ['params'], true);
// output the HTML content
$pdf->writeHTML($html, true, 0, true, 0);
$pdf->lastPage();
$pdf->Output('example_021.pdf', 'I');
Make image from current view and pass that image to TCPDF.
Example
html2canvas(document.getElementById('area')).then(function(canvas) {
var data = canvas.toDataURL();
$.ajax({
url: 'savePDF.php',
type: 'post',
data: {imageSrc: data}
});
});
You can use any other HTML to PDF tool, not only TCPDF.
Resources:
TCPDF, DomPDF
Html2Canvas

Action doesn't execute after ajax post

I'm trying to generate a pdf file with an image and a highcharts image in it.
This is what I do when I click on a button:
('#button').click(function() {
var quizid = <?php echo json_encode($quizid); ?>;
var chart = Highcharts.charts[0];
canvg(document.getElementById('canvas'), chart.getSVG())
var canvas = document.getElementById("canvas");
var img = canvas.toDataURL("image/png");
//document.write('<img src="'+img+'"/>');
// AJAX CALL TO ACTION
$.ajax({
url: '/results/savepdf',
type:"POST",
data: {quizid: quizid, image: img},
success: function(data) {
console.log("ajax call succces");
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
});
In my action I have:
public function savepdfAction(){
$this->_helper->layout->disableLayout();
$this->_helper->viewRenderer->setNoRender();
if(isset($_POST['quizid']))
$quizid = $_POST['quizid'];
if(isset($_POST['image']))
$image = $_POST['image'];
// SAVE THE PDF OR WORD
// INCLUDE TCPDF LIBRARY
require_once 'tcpdf/tcpdf.php';
try {
// create new PDF document
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Nicola Asuni');
$pdf->SetTitle('TCPDF Example 009');
$pdf->SetSubject('TCPDF Tutorial');
$pdf->SetKeywords('TCPDF, PDF, example, test, guide');
$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.' 009', PDF_HEADER_STRING);
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
$pdf->AddPage();
$pdf->setJPEGQuality(75);
$imgdata = base64_decode('iVBORw0KGgoAAAANSUhEUgAAABwAAAASCAMAAAB/2U7WAAAABlBMVEUAAAD///+l2Z/dAAAASUlEQVR4XqWQUQoAIAxC2/0vXZDrEX4IJTRkb7lobNUStXsB0jIXIAMSsQnWlsV+wULF4Avk9fLq2r8a5HSE35Q3eO2XP1A1wQkZSgETvDtKdQAAAABJRU5ErkJggg==');
$pdf->Image('#'.$imgdata);
$pdf->Image('/images/logo.png', 25, 40, 154, 25, 'PNG', 'http://www.surveyanyplace.com', '', true, 150, '', false, false, 1, false, false, false);
$horizontal_alignments = array('L', 'C', 'R');
$vertical_alignments = array('T', 'M', 'B');
$pdf->Output('example_009.pdf', 'I');
}
catch (Exception $e) {
die ('Application error: ' . $e->getMessage());
}
}
As you can see I just want to show a pdf file without the parameters that were sent (Just to test).
This doesn't work ....
When I try this without the ajax call it works fine ...
I got this response:
TCPDF ERROR: Some data has already been output, can't send PDF file
I searched for the error and read that you have can fix this by putting ob_end_clean(); before your $pdf->Output('example_009.pdf', 'I');. And when I did that I got another reponse that you can watch here.
Since a .pdf file is binary data, you shouldn't use an Ajax request. After a quick search I found this jQuery plugin:
jQuery Plugin for Requesting Ajax-like File Downloads
It's a very small function and it generates a temporary form with hidden fields that it submits. Maybe not the most beautiful solution, but it should work. Haven't tested it though...

How to set landscape orientation using HTML2PDF

How to change the page orientation of pdf file generated via HTML2PDF to landscape...?
By default, it is opening as Portrait format. I have changed it in html2pdf.class, but nothing changed.Please help me..
This is the php code:
require('../../includes/html2pdf/html2fpdf.php');
$pdf=new HTML2FPDF('L','mm','A3');
$pdf->AddPage();
$pdf->setFont("arial",'',8);
$pdf->WriteHTML($data);
$pdf->Output("outstanding.pdf","I");
Using L as the constructor parameter should work just fine. Don't mess with the class internals.
This is my only code and it works fine. Try using the newest release: HTML2PDF.
// convert to PDF
require_once('../../vendor/html2pdf_v4.03/html2pdf.class.php');
try
{
$html2pdf = new HTML2PDF('L', 'A4', 'en');
$html2pdf->setDefaultFont('Arial');
$html2pdf->writeHTML($html, false);
$html2pdf->Output('output.pdf', 'D');
}
catch(HTML2PDF_exception $e) {
echo $e;
exit;
}
Or you can add orientation on tag.
<page orientation="landscape" format="A5" > Landscape </page>
Check out http://demo.html2pdf.fr/examples/pdf/exemple04.pdf for more example.
This solution also is very good and it's in the documentation:
var element = document.getElementById('element-to-print');
var opt = {
margin: 1,
filename: 'myfile.pdf',
image: { type: 'jpeg', quality: 0.98 },
html2canvas: { scale: 2 },
jsPDF: { unit: 'in', format: 'letter', orientation: 'portrait' }
};
// New Promise-based usage:
html2pdf().set(opt).from(element).save();
// Old monolithic-style usage:
html2pdf(element, opt);

Categories