I am trying to create a temporarily PDF file from raw PDF string.
This is my input, which is sent through an API (JSON):
{
"name": "pdffilename.pdf",
"content": "%PDF-1.2 [.......]%%EOF"
}
The "content" string is the actual PDF raw data string.
Now this is my controller, that handles the API request:
/**
* Function to convert a PDF file to text
*/
public function PDFtoText(Request $request)
{
$name = $request->name;
$content = $request->content;
//Save PDF file on the server (temp files).
$pdf = Storage::disk('local')->put('/temp_files/' . $name, $content);
return response()->json([
'result' => "Success"
], 200);
}
An actual file is created in the temp_files folder, with the name pdffilename.pdf. However I cannot open the file, as it says the file is "corrupt".
What am I doing wrong here?
the best way to save the content of the document or file is using the base64_encode function, this transform de content in base64 encode. Then when you need this content the unique process you need to do is to call the base64_decode function. I tried and works fine for me. Any questions only write me.
Related
I am trying to convert an html file that contains the Arabic language to pdf and I used tcp pdf
public function generatePdf(){
$users = User::all();
$reportHtml = view('pdf.users', ['users' => $users])->render();
return PDF::HTML($reportHtml);
}
give me this error
"message": "Symfony\\Component\\HttpFoundation\\Response::setContent(): Argument #1 ($content) must be of type ?string, Barryvdh\\Snappy\\PdfWrapper given, called in C:\\Users\\amrel\\Desktop\\topArt\\vendor\\laravel\\framework\\src\\Illuminate\\Http\\Response.php on line 72",
You can't return pdf file directly. Try either
Option #1. Return response in application/pdf type:
return Response::make(PDF::HTML($reportHtml), 200, [
'content-type'=>'application/pdf',
]);
Option #2. From Laravel 5.2 you can return file in storage/ by just:
return response()->file($pathToFile);
So you can save it to your storage and then return.
Option #3. You can send your pdf as downloadable file.
$pdf = PDF::HTML($reportHtml);
return $pdf->download('name.pdf');
Option #4. You can save pdf file to public storage and send url link to it and let the frontend decide.
I'm using the Microsoft Graph API to get the contents of a file, but something is off about the encoding with the content bytes being returned. When I view the file in Notepad++, the contents look something like this:
UÏMÌ؈€aX!D"AŠMtPïq¡ª†f24O]J¦¢’k¿ÇFcX+|¿¯÷q”z{CîËC~ãZVŸâÆù ´*ëáµå:ã/•þ57Yü*—kØ&Ž=NDüßÒLó>#÷.MÊ
×núšÙÄlsb´Ò·SFAÙá~˜ wpÌ&—wY¯ÇpÊúé(¯uïû°×Œ†ˆ÷.”ÒB1ŒKŽ|G;m««¼Õ‘h’IRLp°,µ‰<ÿ¥*‡ë>Ž´ÌÇRtA‰öjJäÂY<5&u„óNæÓÓ¿Md¡U§ÎkäÐÁJÛO{9’^¬C]Ó<ô;Ë:N“šK8KÏH1
I call the Graph endpoint to get the contents of the file like this:
public function getRawAttachmentContents($emailAddress, $messageId)
{
return $this->graph->createRequest("GET", "/users/$emailAddress/messages/$messageId/attachments/{attachmentId}")
->setReturnType(get_class(new \Microsoft\Graph\Model\FileAttachment()))
->execute();
}
This is what gets returned when I make the call. The contents look very different. It's like they're in a different format. How can I get them to be in the same format as the original? When I call the Graph API to get the raw contents (using the $value at the end) nothing gets returned.
Edit: So I figured out how to get the contents of the attachment as they appear when I open the file in Notepad++. I do this:
public function getRawAttachmentContents($emailAddress, $messageId, $attachmentId)
{
$attachment = $this->graph->createRequest("GET", "/users/$emailAddress/messages/$messageId/attachments/$attachmentId/\$value")
->execute();
$attachment->getRawBody()->rewind();
$file_contents = $attachment->getRawBody()->getContents();
return $file_contents;
}
However, when I try uploading the contents returned from that function, an attachment doesn't even get created in the draft message (before, when I uploaded the plain text, it was at least creating an attachment to the draft message, and I was getting a 201 created response on the final upload of the bytes, but the attachment was corrupt).
How I can store decoded image to laravel public image path and hash image name ?
I tried like this, but didnt work and doesn't get any error message;
if (!empty($request->image)) {
$file = base64_decode($request->image)->hashName();
base64_decode($request->image)->store('user-uploads/avatar');
asset('user-uploads/avatar/' . $file);
}
This code works fine but I use API and via curl sending image then needed base64 decoding:
if ($request->hasFile('image')) {
$file = $request->file('image')->hashName();
$request->image->store('user-uploads/avatar');
asset('user-uploads/avatar/' . $file);
}
What you suggest save image and send image url to api and downloads image too path or send base64 image encode and in api decode, like I'm trying at the moment?
You can't call functions on the output of base64_decode, as it returns as string.
I would suggest you post the name of the file along with the base 64 encoded content, which can then be saved using laravel's storage helpers:
Storage::disk('local')->put('image.png', base64_decode($request->image))
I am using the below code. but still it's downloading the files instead of viewing.
public function viewFiles(StoreBusinessDevelopment $request, $file, $id)
{
$businessDevelopment = BusinessDevelopment::select('created_by', 'rfp_id')
->where('id', '=', $id)
->get();
$mimeType = File::mimeType(public_path('/uploads/'.$businessDevelopment[0]['created_by'].'/'.$businessDevelopment[0]['rfp_id'].'/'.$file));
return response()->file(public_path('/uploads/'.$businessDevelopment[0]['created_by'].'/'.$businessDevelopment[0]['rfp_id'].'/'.$file),[
'Content-Type' => $mimeType
]);
}
You can just convert files to PDF format and then return it to browser.
Browser unable to read .doc|xls|xlsx files. But you can view / rander it by using some tricks.
Example 1
First upload the file like i say .doc|xls|xlsx and make it as array of data. By using php -> laravel that have a module/repo for excel file read and parse it as array.
After make it as array and print this array as html table and browser must rander it.
For more info :
Laravel Excel
I am developing a REST API using Laravel 5.1 that has use case as following: receive a base 64 decoded PDF, and return a workspace ID of a Document Management System (DMS) from the uploaded file. The DMS service that I use in this case is Alfresco.
Current Condition
The application succeed to receive base 64 string and decode it to a file. I store the decoded file into system temporary directory, and try to upload it to the Alfresco. I have previously built function that receive a file from a form request to be stored in the Alfresco, and it works. Here is the declaration and parameters stated in the function:
public static function uploadDocument(
$doc, // <-- Okay by form request, not okay by the API decoded file
$user, // credential
$password, // credential
$params = array() // array that contains ACE
)
{
However, when I tried to use the same function with different document source, it failed. By different document source, I mean the source comes from the decoded base 64, and can be seen as follow:
// Decrypt base64
$fileData = base64_decode($request->input('file'));
// Save the decoded file to a temp directory
$tmpDir = sys_get_temp_dir();
$fileName = $request->input("fileName");
$pdfFile = fopen("$tmpDir/$fileName", 'w');
fwrite ($pdfFile, $fileData);
// Upload the decrypted file to the Alfresco
$alfUsername = Config::get('alfresco.CMIS_BROWSER_USER');
$alfPassword = Config::get('alfresco.CMIS_BROWSER_PASSWORD');
$assignees = ['assignees' => []];
$alfObjId = Alfresco::uploadDocument(
$pdfFile,
$alfUsername,
$alfPassword,
$assignees
);
fclose ($pdfFile);
The Error
Call to a member function getClientOriginalName() on resource
That refers to this line:
$uniqueFileName = $alfresco
->getUniqueFileName([
'path' => $path,
'filename' => $doc->getClientOriginalName(), // <-- This line
'session' => $session
]);
Error screenshot
The Question
Can one uploads a decoded base 64 file to another service without using temporary file?
How can I convert the decoded file into a multipart form request or similar, in order that my upload function could consume?
Thank you.
Well, sure you can call other service without saving a temporary file. If the file is already in memory as a string you could use curl to send a new request sending the string as data. Using curl to create a request you could set the content type header to multipart form data