Download generated pdf after ajax post - php

I'm working with Wordpress and I'm trying to generate a PDF in php after ajax post. I need to open my generated file in another window. I'm using this functions :
$('#my_button').on('click' , function(e){
e.preventDefault();
array = [];
jQuery.post( filter_params.ajaxurl, {
'action': 'create_pdf',
'array': array,
},
function(response){
//$('#w').empty();
//$('#w').append(response);
window.open("data:application/pdf," + response);
})
.success(function(data){
});
});
add_action( 'wp_ajax_create_pdf', 'create_pdf' );
add_action( 'wp_ajax_nopriv_create_pdf', 'create_pdf' );
function create_pdf() {
$array = $_POST['array'];
$pdf = new myPDF();
$pdf->AliasNbPages();
$pdf->AddPage('L', 'A4', 0);
$pdf->headerTable();
$pdf->viewTable( $array);
$pdf->Output();
die();
}

to make that we should store the generated pdf temporarily and open a new tab in the success function with the path of the generated pdf file.
function create_pdf() {
$array = $_POST['array'];
$pdf = new myPDF();
$pdf->AliasNbPages();
$pdf->AddPage('L', 'A4', 0);
$pdf->headerTable();
$pdf->viewTable( $array);
$pdf->Output('output.pdf','F');
die();
}

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

FPDF error while creating class

I've a problem with creation af the class needed for outputting JSON data to PDF. The PHP file is as following:
<?php
header('Content-type: text/json');
ob_start();
require('fpdf.php');
class PDF extends FPDF{
// Colored table
function FancyTable($PDFtabHead, $PDFtabData)
{
// stuff with table works if tested with another PHP page
}
} // END -class
$PDFtabHead = json_decode(($_POST['PDFtabHead']), true);
$PDFtabData = json_decode(($_POST['PDFtabData']), true);
$pdf = new PDF();
$pdf->SetFont('Arial','',12);
$pdf->AddPage();
$pdf->FancyTable($PDFtabHead,$PDFtabData);
$pdf->Output();
echo json_encode(array("res"=>$PDFtabHead)); // Only to chek if outputs something
ob_end_flush();
?>
The caller function from my JS file is:
$.ajax({
type: "POST",
async: false,
url: './FPDF/PDF.php',
dataType: 'json',
data: {PDFtabHead: tabHead, PDFtabData: tabData},
success: function (response) {
var res = response.res;
console.log("ok return: "+res);
} // success
,
error: function() {
console.log("ERROR CONNECTING TO ./FPDF/PDF.php");
}// error
}); // ajax
tabHead and tabData are correct, this is the output of tabData :
["05:22","0043","22:31","200201","05:22","0044","22:31", ......]
The call to PDF.php always ends with error, outputting to console : ERROR CONNECTING TO ./FPDF/PDF.php
If I test it from another test page that doesn't send data in JSON format, but a normal PHP Array it works. Obviously I have to change to
$PDFtabHead = ($_POST['PDFtabHead']);
$PDFtabData = ($_POST['PDFtabData']);
in this case PDF page is rendered correctly.
Similarly if I delete the class declaration, and simply return back to my JS page the JSON array, it works; doesn't print PDF it's clear but the Array is returned as expected
OK I've got the solution at the FPDF forum
http://www.fpdf.org/?go=forum&i=56364&t=56363, Oliver's answer is
Don't return a PDF from an AJAX call.

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.

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