Html to pdf download in laravel 5 - pdf

I am usin barryvdh/laravel-dompdf to convert html page to pdf download.
But I have little problem. here is my code.
I would like to download in "show" as /sale/{id}.
In controller
public function pdf(Request $request,$id)
{
$sale = Sale::find($id);
view()->share('sale', $sale);
if ($request->has('download')) {
$pdf = PDF::loadview('sale.slip_out_show');
$pdf->stream();
return $pdf->download('saleslip_out.pdf');
}
return view('sale.slip_out_show');
}
in view
Download PDF
In routes
Route::get('pdf', array('as' => 'pdf', 'uses' => 'SaleController#pdf'));
but this error found
ErrorException in SaleController.php line 105:
Missing argument 2 for App\Http\Controllers\SaleController::pdf()

The problem is the passing argument on pdf(Request $request,$id) method.
You have to pass at least 2 parameter on following href link:
Pass the download Sales ID
Download PDF
In route
Route::get('pdf/{id}', array('as' => 'pdf', 'uses' => 'SaleController#pdf'));

This code will download a pdf file with defined content
*
$pdf = App::make('dompdf.wrapper');
$pdf->loadHTML($message);
return $pdf->download($file_name);
*

Related

Fileinput issue in ActiveForm when updating via Yii 2

I am using Yii2 framwork. My file upload function worked well when I upload a single img, while when I click the posed article and I only want to update the post again(Suppose I didn't want to update the img, I only want to update other contents). But I found my uploaded file were replaced with an empty value(varchar type) when I click view. my uploaded img can't show out.
I do tried to fixed by myself as below, But the existing file value can't be saved when I click the submit button.
<?php
if (($post->file) != "") {
echo $form->field($post, 'file')->textInput()->hint('My currently uploaded file')->label('My Photo') ;
}
else{
echo $form->field($post, 'file')->fileInput()->hint('To upload a new file')->label('My Photo') ;
}
?>
When I click submit button, my existing file was gone.
Is there any good way to fix it.
Thanks for your opinions in advance.
Use another variable in your model for upload a file.
For example use file_field name for get file from submitted and store in file field.
class PostModel extends Model
{
/**
*
* #var UploadedFile
*/
public $file_field;
public function rules() {
return [
['file_field', 'file'],
];
}
}
echo $form->field($post, 'file_field')->fileInput()->hint('To upload a new file')->label('My Photo') ;
$post->file_field = UploadedFile::getInstance($post, 'file_field');
For upload new file check the file_field:
if ($post->file_field) {
// $post->file old file
// Save $post->file_field and store name in $post->file
}
Add a rule to your model rules:
[['file'], 'file', 'skipOnEmpty' => true, 'extensions' => 'png, jpg'],
and check for an empty upload in your controller:
if (Yii::$app->request->isPost) {
$ok = true;
// process your other fields...
...
// process image file only if there is one
$post->file= UploadedFile::getInstance($post, 'file');
if ($post->file && $post->upload()) {
}
if ($ok) {
return $this->redirect(...);
}
}
See Yii2 docs and the Yii2 guide for detailed infos about file upload.

Adobe PDF Embed API Save Content To Base64

Using Adobe PDF Embed API, you can register a callback:
this.adobeDCView = new window.AdobeDC.View(config);
this.adobeDCView.registerCallback(
window.AdobeDC.View.Enum.CallbackType.SAVE_API, (metaData, content, options) => {
})
Content is according to the docs here: https://www.adobe.io/apis/documentcloud/dcsdk/docs.html?view=view
content: The ArrayBuffer of file content
When I debug this content using chrome inspector, it shows me that content is a Int8Array.
Normally when we upload a pdf file, the user selects a file and we read as dataURI and get base64 and push that to AWS. So I need to convert this PDF's data (Int8Array) to Base64, so I can also push it to AWS.
Everything I have found online uses UInt8Array to base64, and I don't understand how to go from Int8Array to UInt8Array. I would think you can just add 128 to the signed int to get a ratio between 0-256, but this doesn't seem to work.
I have tried using this:
let decoder = new TextDecoder('utf8');
let b64 = btoa(decoder.decode(content));
console.log(b64);
But I get this error:
ERROR DOMException: Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range.
Please help me figure out how to go from Int8Array to Base64.
I use the function in this answer.
For Embed API, use the "content" parameter from the save callback as the input to the function.
You can see a working example at this CodePen. The functional part is below.
adobeDCView.registerCallback(
AdobeDC.View.Enum.CallbackType.SAVE_API,
function (metaData, content, options) {
/* Add your custom save implementation here...and based on that resolve or reject response in given format */
var base64PDF = arrayBufferToBase64(content);
var fileURL = "data:application/pdf;base64," + base64PDF;
$("#submitButton").attr("href", fileURL);
/* End save code */
return new Promise((resolve, reject) => {
resolve({
code: AdobeDC.View.Enum.ApiResponseCode.SUCCESS,
data: {
/* Updated file metadata after successful save operation */
metaData: { fileName: urlToPDF.split("/").slice(-1)[0] }
}
});
});
},
saveOptions
);

KeystoneJS Cloudinary image upload

I am using the latest version of KeystoneJS and have a form working to add a record to the database.
I'm having trouble getting image uploads to work.
My model conatains:
heroImage: { type: Types.CloudinaryImage, autoCleanup : true },
My form includes:
<input type="file" accept="image/*" id="heroImage" name="heroImage_upload" className='field-upload'>
and my middleware for saving the form simply includes:
view.on('post', {action: 'save'}, function(next)
{
var newProperty = new Property.model(req.body);
console.log(newProperty);
newProperty.save(function(err, body)
{});
});
which works great for all field's except the file upload.
I've tried adding:
newProperty.heroImage = req.files['heroImage'];
which leaves heroImage as null.
I also tried creating a cloudinaryImage but this causes an error:
var img = new CloudinaryImage(req.files['heroImage']);
It all works fine when I use the KeystoneJS admin dashboard to upload images. Can someone please explain how I should use the cloudinaryImage field type in my own form?
Thanks
Not sure if this will help, but there is a note at the bottom of the docs:
http://keystonejs.com/docs/database/#fieldtypes-cloudinaryimage
"Remember that if you are uploading images to a CloudinaryImage field using an HTML form, you need to specify enctype="multipart/form-data" in your form tag."
Have you included that in your form?
Update:
So, the following should work, assuming your model is called MyModel, and your form data uses the same object keys as your model. (i.e. the image for your heroImage field should be provided as heroImage in the POST data).
var MyModel = keystone.list('MyModel');
view.on('post', {action: 'save'}, function(next)
{
var item = new MyModel.model();
data = req.body;
item.getUpdateHandler(req).process(data, function(err) {
// Handle error
}
}
Keystone should then handle all the specific cloudinary stuff internally.
Here is a way to do it with cloudinary.v2
untested keystone
cloudinary.v2.uploader.upload(base64_file_data, (err, result) => {
var newMyModel = new MyModel.model(model_data);
newMyModel.image = result;
let updater = newMyModel.getUpdateHandler(req);
updater.process(newMyModel, {
fields: image
}, err => {...})
})
tested mongoose
cloudinary.v2.uploader.upload(base64_file_data, (err, result) => {
var newMyModel = new MyModel.model(model_data);
newMyModel.image = result;
newMyModel.save(err => {...})
})

Can't print to PDF in Slim Framework, Twig, and DomPDF

I have been struggling with this and I can't get it to work, despite that in some other posts they say you can use the Twig's render() function, I get the folowing error:
Requested HTML document contains no data. Dompdf\Exception
My code so far is:
use Dompdf\Dompdf;
$app->post('/my/path/for/printing',function()use($app){
//echo '<p>printing to pdf ... ☺</p>';
$request=$app->request;
/* code for retrieving data from the database ... done.*/
$variables = [
'param1' => $param1,
'param2' => $param2,
];
$dompdf = new Dompdf();
$content = $app->render('path/for/the/view.print.twig', $variables);
$dompdf->loadHtml($content);
$dompdf->render();
$dompdf->stream('sample.pdf');
})->name('my.path.for.printing');
If I render my view, the data is displayed correctly. But with dompdf is not working.
Does anybody know how to fix this?
Otherwise, can you explain with an example of any other package how to print a Twig view in PDF?
render() doesn't return the HTML. Try:
$content = $app-view->fetch('path/for/the/view.print.twig', $variables);

"Controller method not found." Laravel error. How can I figure out what method was called that it couldn't find?

I started using Laravel a month ago. Trying to make a page with one form on it and I keep getting a "Controller method not found." error. There is only one form on the page and that method is being called fine and making the query that I want. It does redirect to the same page with that form, /dashboard/edit/module.
It would be awesome if I could see what method is not being found or where it is in my code. Any ideas how I can do this? Someone mentioned App::error or messing with Log::error in global.php but I can't get any more information shown.
Edit:
I found that the form action is only being found if I upload a video to the form. Other then that it gives me the same error. Here is the controller method of this form. The page with this form is /dashboard/edit/module and I would like to reload that page after this runs.
public function postSection(){
$path = public_path() . "/videos/";
$filename = uniqid() . '.mp4';
$file_path = $path . $filename;
$moduleID = Input::get('moduleID');
if(!Input::hasFile('video')){
return Redirect::back()->with('error', 'Must enter a valid video file.');
}else{
try {
Input::file('video')->move($path, $filename);
$section = New Section;
$section->module_id = $moduleID;
$section->video = $file_path;
$section->save();
//I was trying to use this instead of View::make to stop form resubmission
//return Redirect::to('/dashboard/edit/module')->with('moduleID', $moduleID);
return View::make('forms.editMod')->with('moduleID', $moduleID);
}catch ( Exception $e){
return Redirect::back()->with('error', 'Unable to save the video file.');
}
}
}
Edit: And my routes.php
//Route for the home page
Route::get('/', function(){ return View::make('home'); });
//Controllers
Route::controller('dashboard/edit', "ContentController");
Route::controller('user', "UserController");
Route::group(array('before'=> 'auth|dash'), function(){
//dashboard home
Route::get('/dashboard', function(){ return View::make('dashboard');});
//dashboard subs
Route::get('dashboard/modules', function(){ return View::make('forms.module');});
Route::get('dashboard/users', function(){ return View::make('users');});
Route::get('dashboard/reporting', function(){ return View::make('reporting');});
//user pages
Route::get('dashboard/register', function(){ return View::make('forms.register');});
Route::post('dashboard/edit/user', array('before'=>'csrfajax', function(){
$id = Input::get('userID');
$user = User::find($id);
return View::make('forms.editUser')->with('user', $user);
}));
});
And the form...
{{ Form::open(array('files' => true, 'action' => 'ContentController#postSection', 'id' => 'sectionform')) }}
<fieldset>
{{ Form::label('Video (mp4)') }}
{{ Form::hidden('moduleID', $module->id)}}
{{ Form::file('video', array('id' => 'video', 'class' => 'form-control')) }}<br>
{{ Form::submit('Save') }}
</fieldset>
{{ Form::close() }}
In routes.php, to reach this method you're using Route::controller, which results in RESTful routing. If the browser's HTTP request used the POST action, you'd correctly be routed to public function postSection(){}. But if the HTTP request used GET, which is the default for web browsing, especially when no data is being submitted by the browser, Laravel would be looking for a method called public function getSection(){}. This would explain why when you're uploading something (i.e. using POST), you reach the page, but otherwise you don't.
See the official documentation for the full low-down on implicit routing: http://laravel.com/docs/controllers#implicit-controllers