Laravel - Set page title when using Response::make to view pdf file - laravel

I am trying to set the page title in Laravel to be the name of the file that is being viewed in the browser. I have looked through the documentation and questions on stack overflow and cannot seem to find the solution. The page title keeps defaulting to the primary key
public function download(SomeModel $document)
{
if(Storage::disk('s3')->exists($document->file_path)) {
return \Response::make(Storage::disk('s3')->get($document->file_path), 200, [
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'inline; filename="'. $document->custom_file_name .'"'
]);
}
return view('errors.404');
}
How can I make it to where the <title></title> of the page is using the $document->custom_file_name as opposed to being the id.

You need to set the Title metadata on your pdf document, then the browser will interpret it as the title automatically.
http://www.w3.org/TR/WCAG20-TECHS/PDF18.html

Related

How to display PDF Documents on the browser using a View in Laravel 5.8

I'm working on a web application using Laravel 5.8, I'm new to Laravel framework. I would like to display PDF documents on the browser when users click on some buttons. I will allow authenticated users to "View" and "Download" the PDF documents.
I have created a Controller and a Route to allow displaying of the documents. I'm however stuck because I have a lot of documents and I don't know how to use a Laravel VIEW to display and download each document individually.
/* PDFController*/
public function view($id)
{
$file = storage_path('app/pdfs/') . $id . '.pdf';
if (file_exists($file)) {
$headers = [
'Content-Type' => 'application/pdf'
];
return response()->download($file, 'Test File', $headers, 'inline');
} else {
abort(404, 'File not found!');
}
}
}
/The Route/
Route::get('/preview-pdf/{id}', 'PDFController#view');
Mateus' answer does a good job describing how to setup your controller function to return the PDF file. I would do something like this in your /routes/web.php file:
Route::get('/show-pdf/{id}', function($id) {
$file = YourFileModel::find($id);
return response()->file(storage_path($file->path));
})->name('show-pdf');
The other part of your question is how to embed the PDF in your *.blade.php view template. For this, I recommend using PDFObject. This is a dead simple PDF viewer JavaScript package that makes embedding PDFs easy.
If you are using npm, you can run npm install pdfobject -S to install this package. Otherwise, you can serve it from a CDN, or host the script yourself. After including the script, you set it up like this:
HTML:
<div id="pdf-viewer"></div>
JS:
<script>
PDFObject.embed("{{ route('show-pdf', ['id' => 1]) }}", "#pdf-viewer");
</script>
And that's it — super simple! And, in my opinion, it provides a nicer UX for your users than navigating to a page that shows the PDF all by itself. I hope you find this helpful!
UPDATE:
After reading your comments on the other answer, I thought you might find this example particularly useful for what you are trying to do.
According to laravel docs:
The file method may be used to display a file, such as an image or PDF, directly in the user's browser instead of initiating a download.
All you need to do is pass the file path to the method:
return response()->file($pathToFile);
If you need custom headers:
return response()->file($pathToFile, $headers);
Route::get('/show-pdf/{id}', function($id) {
$file = YourFileModel::find($id);
return response()->file(storage_path($file->path));
})->name('show-pdf');
Or if file is in public folder
Route::get('/show-pdf', function($id='') {
return response()->file(public_path().'pathtofile.pdf');
})->name('show-pdf');
then show in page using
<embed src="{{ route('show-pdf') }}" type="text/pdf" >

How to send blade as attachment in pdf format in laravel?

I want to send blade file as attachment in mail with laravel. I am
writing below code for this but its not working.
Below is my controller where i am getting data from form and then send
this data to another controller where my attachment function is
called.
$data = array('shareholders'=>$request->com_shareholder_count,'contract_send'=>$request->contract_send);
$to = $mail_log->to_email_id = $request->email_id;
$mail = Mail::to($to)->send(new SendMailable($data));
This is my SendMailable controller :
$director_info_pdf = view('directors_info',compact('data'))->render();
On return this variable it shows me error :
message: "Invalid view.", exception: "InvalidArgumentException",…}
exception: "InvalidArgumentException"
file: "C:\xampp\htdocs\caps_admin\vendor\laravel\framework\src\Illuminate\Mail\Mailer.php"
line: 285
message: "Invalid view."
After this line i am writing code to attach my files. where i am sending some files other 3 files are directly send from folder. And last one is attached from blade file.
->attachdata($director_info_pdf, 'dynamic_data.pdf')
->attach( $public_path.'/'.'contract.pdf', [
'as' => 'contract.pdf',
'mime' => 'application/pdf',
])
->attach($public_path.'/'.'HMRC.pdf',[
'as' => 'HMRC.pdf',
'mime' => 'application/pdf',
])
->attach($public_path.'/'.'clientR3.pdf',[
'as' => 'contract1.pdf',
'mime' => 'application/pdf',
]);
I am able to send mail with all 4 files as attachment. But when i am trying to open my files in mail rest 3 files are working as pdf. but ->attachdata($director_info_pdf, 'dynamic_data.pdf') this file get corrupted.
I dont know how to first change this file into pdf and then send as attachment.
I am using snappy for pdf.
I think you want to send pdf as an attachment in your email without saving it in your system .
your can refer the following code to do this .
public function sendmail()
{
$data["email"]='useremail#gmail.com';
$data["client_name"]='user_name';
$data["subject"]='sending pdf as attachment';
//Generating PDF with all the post details
$pdf = PDF::loadView('userdata'); // this view file will be converted to PDF
//Sending Mail to the corresponding user
Mail::send([], $data, function($message)use($data,$pdf) {
$message->to($data["email"], $data["client_name"])
->subject($data["subject"])
->attachData($pdf->output(), 'Your_Post_Detail.pdf', [
'mime' => 'application/pdf',
])
->setBody('Hi, welcome user! this is the body of the mail');
});
}
hope it helped you .
for better understanding you can follow this article
how to send pdf as an attachment in email in laravel
I dont know how to first change this file into pdf and then send as attachment. I am using snappy for pdf.
So that's the problem right there. You are attaching an HTML file, and simply naming it as if it's a PDF. That won't work. You do indeed need to generate this PDF from the HTML view that you render.
Here is the documentation for snappy:
https://github.com/barryvdh/laravel-snappy#usage
I suggest you to read up on it, as the examples given there are pretty straight forward and easy to understand.
This is untested, but if you've set up Snappy correctly, based on your code, something like this should work:
$snappy = App::make('snappy.pdf');
$director_info_pdf = $snappy->getOutputFromHtml(view('directors_info',compact('data'))->render());

Displaying pdf in laravel

I'm creating a site where an author uploads a pdf file. The way I've created my site is there is a page where story titles is shown, if a person clicks on the title it uses the story slug to go to the story, but I want a pdf to be displayed when the the title is clicke d. I'm not sure where to start. I have tried barryvdh/laravel-dompdf, but it doesn't have a "partial" section to display a pdf. It only allows for the pdf to be viewed as a whole page. I hope I made sense.
Something similar to this Google Books
Try this way :
$filename = 'test.pdf';
$path = storage_path($filename);
return Response::make(file_get_contents($path), 200, [
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'inline; filename="'.$filename.'"'
]);
Try this html object tag :
<div>
<object data="test.pdf" type="application/pdf" width="300" height="200">
alt : test.pdf
</object>
</div>

How can I return actual JSON using Drupal?

I'd like to implement a simple AJAX function locally that allows me to autocomplete node titles of already existing nodes as the user types. To that end, I need the ability to have an API that I can search on node titles. The problem is that when I output raw JSON, it comes surrounded by tags. So, no matter what I do, I keep getting...
<html>
<head>
</head>
<body>
<pre style="word-wrap: break-word; white-space: pre-wrap;"> {json here}</pre>
</body>
</html>
I've tried implementing a custom page template that only outputs content already, that produced the same results. Here is how I am currently doing this, in my module file...
<?php
/**
* Implementation of hook_menu()
*/
function content_relation_menu() {
$items = array();
$items['api'] = array(
'title' => 'Search',
'page callback' => 'content_relation_get',
'access callback' => TRUE,
'type' => MENU_CALLBACK,
);
return $items;
}
function content_relation_get($term = '') {
drupal_add_http_header('Content-Type', 'application/javascript; utf-8');
$var = json_encode(
db_query("SELECT nid,title FROM {node} WHERE title LIKE :title LIMIT 5", array(":title" => $term.'%'))->fetchAll()
);
echo $var;
exit(0);
}
How can I return JUST raw JSON?
The 'Drupal' way is using drupal_json_output() and drupal_exit().
$data = db_query("SELECT nid,title FROM {node} WHERE title LIKE :title LIMIT 5", array(":title" => $term.'%'))->fetchAll();
drupal_json_output($data);
drupal_exit();
UPDATE
I've just put your code, as is, into a module and all I get when requesting http://site.com/api is the expected JSON, there are no tags. The problem won't be anything to do with Drupal, more likely to do with server/browser configuration.
This link may help:
What do browsers want for the Content-Type header on json ajax responses?
This actually DID output raw JSON - Chrome was adding the html wrapping. Viewing the output in command line cURL showed that this did output raw JSON.
Take out the exit(0); and it should work. If your page callback doesn't return anything then the normal theme handlers don't get called so you get raw output.
That said, due to the rather poor performance of Drupal, for decent response times you're better off making a small standalone script that talks to the drupal DB, so you don't pay the rather heavy startup costs of a drupal request when you don't need of that functionality.

The url from an image via custom field (wordpress)

Am not even sure if this can be done but...
Ive added a feed from my forums to wordpress it works great but I need it to auto add the url of the image in a custom field from the images in the post (feed) first image would be fine as its only ahve a slider
Is there any way to do this?
Details
Ok I think I did not explain this very well so made a few screen shots
This is my slider at the minute with my
This is an imported post one other feed I was using
On this image you can see the custom field (which I have to fill in after every import)
Adding the image url into the custom field
and finaly a view of the slider working
This is what am trying to do (auto) so my feed from my booru / forums / 2 other of my sites and (2 other peoples) sites make my home page on a new site
Hope this explain it alot more
This uses the external Simple Pie library built into WordPress to fetch the feed, get the image url and create a new post for each item and save the image url as a custom field.
To activate the process we have to hook into wp_cron. The code below does it daily but it would probably be better to do it weekly to prevent overlap. Some overlap will probably occur so this still needs a way to check if we have already imported the image
First we need a function to save the custom field after the post has been created. This section comes from another answer I found on WordPress Answers.
Edit:
This needs to be wrapped in a plugin to schedule the cron event and the cron event was missing the action to make it fire.
Edit:
Final version below tested and it works but the feed the OP is getting is using relative url's so the domain name needs to be added somewhere in the output code.
<?php
/*
Plugin Name: Fetch The Feed Image
Version: 0.1
Plugin URI: http://c3mdigital.com
Description: Sample plugin code to fetch feed image from rss and save it in a post
Author: Chris Olbekson
Author URI: http://c3mdigital.com
License: Unlicense For more information, please refer to <http://unlicense.org/>
*/
//Register the cron event on plugin activation and remove it on deactivation
register_activation_hook(__FILE__, 'c3m_activation_hook');
register_deactivation_hook(__FILE__, 'c3m_deactivation_hook');
add_action( 'c3m_scheduled_event', 'create_rss_feed_image_post');
function c3m_activation_hook() {
wp_schedule_event(time(), 'weekly', 'c3m_scheduled_event');
}
function c3m_deactivation_hook() {
wp_clear_scheduled_hook('c3m_scheduled_event');
}
function create_rss_feed_image_post() {
if(function_exists('fetch_feed')) {
include_once(ABSPATH . WPINC . '/feed.php'); // include the required file
$feed = fetch_feed('http://animelon.com/booru/rss/images'); // specify the source feed
}
foreach ($feed->get_items() as $item) :
// global $user_ID;
$new_post = array(
'post_title' => $item->get_title(),
'post_status' => 'published',
'post_date' => date('Y-m-d H:i:s'),
//'post_author' => $user_ID,
'post_type' => 'post',
'post_category' => array(0)
);
$post_id = wp_insert_post($new_post);
if ($enclosure = $item->get_enclosure() )
update_post_meta( $post_id, 'feed_image_url', $enclosure->get_link() );
endforeach;
}

Resources