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
Related
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
code at controller side is given below
try {
$this->load->library('m_pdf');
$querytype = "advance_search";
$showdata = [];
$pdfFilePath = utf8_decode("download_pdf.pdf");
ob_start();
$body= $this->load->view('result/pdf_generation', $this->common_advance_search($querytype),false); //here i am loading view for pdf
$this->m_pdf->pdf->WriteHTML($body);
$this->m_pdf->pdf->Output(FCPATH.$pdfFilePath,'F');// till here i can see the data in view
$result = ob_get_clean();
$response = array(
'op' => 'ok',
'file' => "data:application/pdf;base64,".base64_encode($result)
);
die(json_encode($response));
}
catch(\Mpdf\MpdfException $e) {
echo $e->getMessage();
}
Ajax Code
$.ajax({
url : "<?php echo base_url(); ?>"+scr,
method:"POST",
data:formData,
contentType: false,
cache: false,
processData:false,
dataType:'json'
}).done(function(data){ // here i am able to download the pdf in the browser
var $a = $("<a>");
$a.attr("href",data.file);
$("body").append($a);
$a.attr("download","file."+ext);
$a[0].click();
$a.remove();
});
result is given below
check result (screen shot added here)
with this code, it is giving me a currpted PDF file, i am able to get data and 'Export as pdf'. I have checked whether it is passing data from view, and yes it is doing so. But don't know what is the matter . I is printing everything outside it is working fine, Can anyone please let me know what should I do?
I am trying to add a from with a CKeditor widget imbedded via an AJAX request. The request itself works fine and returns the general partial view as I want it. Except for the Ckeditor widget, a normal textbox is return instead.
When the item is added to the group and the page is reloaded, the same partialView is being rendered (in a foreach with all group-items) and this time the CKeditor is nicely in place.
Posted my controller, initialization of the CKeditor and Scipt with AJAX request below. (The CKeditor is inlcuded in the _ContentItemHtml view)
I have taken a look at this, but I cannot call any CKeditor functions from JS since it is loaded as a widget.
Controller Action
public function actionCreateHtml($contentitemgroupid)
{
$model = new ContentItemHtml();
if (isset(Yii::$app->request->post()['ContentItemHtml'])) {
$item = Yii::$app->request->post()['ContentItemHtml'];
$model->contentitemgroupid = $contentitemgroupid;
$model->title = $item['title'];
$model->body = $item['body'];
$model->save();
// return $this->redirect(['edit', 'id' => $model->contentitemgroupid]);
}
else
return $this->renderPartial('_ContentItemHtml', ['model' => $model]);
}
Active form in view:
echo $form->field($model, 'body')->widget(CKEditor::className(), [
'preset' => 'custom',
'clientOptions' => [
'height' => 200,
'toolbarGroups' => [
['name' => 'basicstyles', 'groups' => ['basicstyles', 'cleanup']],
['name' => 'paragraph', 'groups' => ['templates', 'list']],
['name' => 'mode']]
]])->label(false);
Script.js
$('#addNewContentItem').on('click', function (e) {
e.preventDefault();
var url = 'create-' + $('#itemSelector').val().toLowerCase() + '?contentitemgroupid=' + $('#itemSelector').attr('contentitemgroupid');
$.ajax({
type: 'POST',
url: url,
cache: false,
success: function(res) {
$('.contentItemsManager').append('<div class="ContentItemContainer row">' + res + '</div>');
AddSaveEventListener();
AddSaveMediafileEventListener();
AddRemoveEventListener();
}
});
});
Use renderAjax instead of renderPartial. From the docs:
[renderAjax] Renders a view in response to an AJAX request.
This method is similar to renderPartial() except that it will inject into the rendering result with JS/CSS scripts and files which are registered with the view. For this reason, you should use this method instead of renderPartial() to render a view to respond to an AJAX request.
I am trying to append text to CJuiDialog widget in Js code, In CJuiDialog content i have two buttons ,
Dialog Widget code,
<?php
$this->beginWidget('zii.Widgets.jui.CJuiDialog',array(
'id'=>'update_tasks',
'options'=>array(
'title'=>'Create Tasks',
'autoOpen'=>false,
'modal'=>false,
'width'=>500,
'height'=>300,
),
));
?>
<table cellspacing="20">
<tr>
<td><?php echo CHtml::button('Add to Current Pending Tasks',array('id'=>'AddPendingTasks'));?></td><td style = "width : 20px"></td>
<td><?php echo CHtml::button('Add to Tasks',array('id'=>'AddTasks'));?></td>
</tr>
</table>
<?php $this->endWidget();?>
Am opening this dialog inside JS code on another button action,
$('.updatetask_btn').click(function(){
var filterid = $(this).closest('tr').find('select')[0].options[$(this).closest('tr').find('select')[0].selectedIndex].value;
var filtername = $(this).closest('tr').find('select')[0].options[$(this).closest('tr').find('select')[0].selectedIndex].text;
document.getElementById('filter-id').value = filterid;
var div = document.getElementById('update_tasks');
div.innerHTML = '<label><b>'+$('#camp-name').val()+' - '+filtername+'</b></label><br>'+div.innerHTML ;
//----- Here am appending text to the dialog dynamically ---
$('#update_tasks').dialog('open');
});
Appending text blocks the two button actions in CjuiDialog content . both button onclick action not working when i append text here. Please give me any idea.
Actually I didn't fully understood your needs but I always do this way:
You need to understand and adapt to your needs.
In main view
Yii::app()->clientScript->scriptMap['jquery.js'] = false;
Yii::app()->clientScript->scriptMap['jquery.min.js'] = false;
Yii::app()->clientScript->scriptMap['jquery-ui.js'] = false;
Yii::app()->clientScript->scriptMap['jquery-ui.min.js'] = false;
....
$this->beginWidget('zii.widgets.jui.CJuiDialog', array(
'id'=>'addot-dialog',
'options'=>array(
'title' => 'Aggiungi OT',
'autoOpen' => false,
'width' => 600,
'height' => 'auto',
'closeOnEscape' => true,
// 'close' => 'js:function() { $("table.items").find("tbody tr div.log-active").removeClass("log-active").addClass("log-inactive"); }'
)
));
$this->endWidget('zii.widgets.jui.CJuiDialog');
?>
.....
$loadurlvendita = Yii::app()->createUrl("/otpos/otVendita/",
array("idot" => $this->idot, "codfis" => $this->codfis));
....
on click here I open and fill let dialog with .load() from another view with render partial
CHtml::link('','',
array('class'=>'be-icon vendita','style'=>'display:block;float:right;padding-right:6px;',
'onClick'=>'$("#venditaot-'.$this->idot.'").dialog("open").load(\''.$loadurlvendita.'\');'
)).
controller
public function actionOtVendita($idot, $codfis) {
$proprietari = Otpos::model()->getOtposProprietari($idot);
$this->renderPartial('vendita', array('idot' => $idot, 'codfis' => $codfis, 'proprietari' => $proprietari), false, true);
}
I hoe it'll help in some way other wise clear better your needs.
I'm trying to create a gallery plugin for Wordpress and I'm using Plupload to upload some images.
Before user can uploading images for a new gallery, the gallery name must be added. Since I'm using drag and drop, I need to abort the file upload if the gallery name i empty.
I've tried various solution, but I'm not able to stop the file upload (I think).
At the bottom in my SJ script, I'm doing a check on dragover. Where I want to abort is marked with //HERE FILE UPLOAD MUST ABORT.
But I'm not sure if this is the right place. Can anyone tell me where I can abort the upload on dragover (and drop)?
// PHP code - I'm adding this data here, because I need some WP data
function plupload_init() {
//$image_size = get_option('sim_gallery_max_width_height');
$plupload_arr = array(
'runtimes' => 'html5,silverlight,flash,html4,browserplus,gears',
'browse_button' => 'plupload-browse-button', // will be adjusted per uploader
'container' => 'plupload-upload-ui', // will be adjusted per uploader
'drop_element' => 'drag-drop-area', // will be adjusted per uploader
'file_data_name' => 'async-upload', // will be adjusted per uploader
'multiple_queues' => true,
'max_file_size' => wp_max_upload_size() . 'b',
'url' => admin_url('admin-ajax.php'),
'flash_swf_url' => includes_url('js/plupload/plupload.flash.swf'),
'silverlight_xap_url' => includes_url('js/plupload/plupload.silverlight.xap'),
'filters' => array(array('title' => __('Image files'), 'extensions' => 'jpg,jpeg,gif,png')),
'multipart' => true,
'urlstream_upload' => true,
'multi_selection' => false, // will be added per uploader
// additional post data to send to our ajax hook
'multipart_params' => array(
'_ajax_nonce' => "", // will be added per uploader
'action' => 'plupload_action', // the ajax action name
'imgid' => 0 // will be added per uploader
)
);
?>
<script type="text/javascript">
var plupload_config_vars = <?php echo json_encode($plupload_arr); ?>;
</script>
<?php
}
// JS scrip
function init_image_upload() {
if(jQuery('#image-upload').length == 0)
return;
var plupload_config = JSON.parse(JSON.stringify(plupload_config_vars));
var uploader = new plupload.Uploader(plupload_config);
// Control gallery name
control_gallery_name();
uploader.bind('Init', function(up){});
uploader.init();
// a file was added in the queue
uploader.bind('FilesAdded', function(up, files){
});
// Change border color on drop zone
function drop_area_visual_feedback(up) {
var uploaddiv = jQuery('#plupload-upload-ui');
if ( up.features.dragdrop) {
uploaddiv.addClass('drag-drop');
jQuery('#drag-drop-area').bind('dragover.wp-uploader', function(){ // dragenter doesn't fire right :(
if(!jQuery('input[name="gallery-name"]').val()) {
jQuery('label.missing-name').removeClass('hidden');
//HERE FILE UPLOAD MUST ABORT
} else {
uploaddiv.addClass('drag-over');
}
}).bind('dragleave.wp-uploader, drop.wp-uploader', function(){
uploaddiv.removeClass('drag-over');
});
} else {
uploaddiv.removeClass('drag-drop');
jQuery('#drag-drop-area').unbind('.wp-uploader');
}
}
}
Have you tried putting your code in the FilesAdded handler, like this ?
// a file was added in the queue
uploader.bind('FilesAdded', function(up, files){
if(!jQuery('input[name="gallery-name"]').val()) {
jQuery('label.missing-name').removeClass('hidden');
up.splice(0);
}
});