How to set orientation = landscape using KnpSnappyBundle? - symfony

I'm using Snappy Bundle along with Symfony 2.1.
I have some question I did not find in the documentation of this bundle :
How to set the orientation ?
Is there a way to display page numbers ?
Here is my config.yml for the bundle :
knp_snappy:
pdf:
enabled: true
binary: /home/wkhtmltopdf-i386
options: []
Here is one of my Controller to generate a pdf :
public function exampleAction() {
$html = $this->renderView('MyBundle:Example:test.pdf.twig', $this->param);
return new Response($this->get('knp_snappy.pdf')->getOutputFromHtml($html),200, array(
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="Test.pdf"'));
}
Thanks a lot for your help!

$pdf = $this->get('knp_snappy.pdf')->getOutputFromHtml($html,
array('orientation'=>'Landscape',
'default-header'=>true));

Related

Open pdf from server path in Symfony3

I would like to open the pdf file in the window browser but I have "The file "\\servername\20\2016080.pdf" does not exist"
If I copy this path in a browser, it's work.
Edit: I have found in the logs
CRITICAL - Uncaught PHP Exception Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException: "The file "\\servername\20\2016080.pdf" does not exist" at C:\wamp64\www\his\vendor\symfony\symfony\src\Symfony\Component\HttpFoundation\File\File.php line 37
Thank you.
$response = new BinaryFileResponse($result = $ServerModel->getDocument($request-> get('id'));
$response->headers->set('Content-Type', 'application/pdf');
return $response;
If you're using symfony 3.2 or later (which you should be), you can use the new file helper to serve binary files.
from the symfony docs
$pdfPath = $this->getParameter('dir.downloads').'/sample.pdf';
return $this->file($pdfPath);
how you go about getting the path of the file may differ depending on your implementation. But if its a straight SplFileInfo:: object php docs then you can just use:
$file->getPathname();
The file helper will automagically do much of heavy lifting for you.
Make sure the file is accessible, either by a route or by an un-firewalled path.
/**
* #Route("/show-pdf", name="show-pdf")
*/
public function showPdf(Request $request) {
ini_set('display_errors', 'On');
$pdf = file_get_contents('path/to/file.pdf');
return new Response($pdf, 200, [
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'inline; filename="file.pdf"'
]);
}

FMElfinderBundle 5 - how to set temp folder for upload

I am using FMElfinderBundle v.5 (for some reasons I cannot use latest version) with Symfony 2.8.12. I followed documentation and it worked fine, until there was request to allow upload large files (up to 20MB). I changed upload_max_size parameter to 20M and it was ok, but during upload files are split to 2MB chunks and elfinder tries to store them in temp directory. Problem is, that it has no access there. It does not read settings from virtual host definition, it always uses system temp folder.
Reading documentation I have found that there can be used two parameters for configuring elfinder temp dir - upload_temp_path and common_temp_path. But i didn't have luck with setting them. Every time I run in PHPStorm console command s cache: clear --no-warmup I get InvalidConfigurationException.
I tried to put parameters somewhere else in config structure under fm_elfinder key, but still the same exception.
This is my configuration in config.yml:
fm_elfinder:
instances:
default:
locale: %locale%
editor: ckeditor
fullscreen: true
theme: smoothness
include_assets: true
relative_path: false
connector:
roots:
uploads:
driver: LocalFileSystem
path: uploads
upload_max_size: 20M
Anyone please can help me, how to set temp dir?
Ok, some detailed info:
I took ElFinderConfigurationReader from ElFinder bundle and saved it into my project under name ElFinderConfigurationCustomReader. Then this class i defined as a service:
service.custom_fm_elfinder.configurator:
class: CSBN\SVJBundle\Component\ElFinder\ElFinderConfigurationCustomReader
arguments: ['%fm_elfinder%', '#request_stack', '#service_container', '%elfinder_temporary_path%']
variable elfinder_temporary_path is set in parameters.yml.
in config.yml i set my own configuration reader:
fm_elfinder:
configuration_provider: service.custom_fm_elfinder.configurator
And in my newly created file ElFinderConfigurationCustomReader i just in method getConfiguration added one row:
$options['uploadTempPath'] = $this->temporaryPath;
which is taken from service parameters in constructor.
Hope this helps you.
Edit: full function copy:
/**
* #param $instance
*
* #return array
*/
public function getConfiguration($instance)
{
$request = $this->requestStack->getCurrentRequest();
$efParameters = $this->parameters;
$parameters = $efParameters['instances'][$instance];
$options = array();
$options['corsSupport'] = $parameters['cors_support'];
$options['debug'] = $parameters['connector']['debug'];
$options['bind'] = $parameters['connector']['binds'];
$options['plugins'] = $parameters['connector']['plugins'];
$options['uploadTempPath'] = $this->temporaryPath;
$options['roots'] = array();
foreach ($parameters['connector']['roots'] as $parameter) {
$path = $parameter['path'];
$homeFolder = $request->attributes->get('homeFolder');
if ($homeFolder !== '') {
$homeFolder = '/'.$homeFolder.'/';
}
$driver = $this->container->has($parameter['driver']) ? $this->container->get($parameter['driver']) : null;
$driverOptions = array(
'driver' => $parameter['driver'],
'service' => $driver,
'glideURL' => $parameter['glide_url'],
'glideKey' => $parameter['glide_key'],
'plugin' => $parameter['plugins'],
'path' => $path.$homeFolder, //removed slash for Flysystem compatibility
'startPath' => $parameter['start_path'],
'URL' => $this->getURL($parameter, $request, $homeFolder, $path),
'alias' => $parameter['alias'],
'mimeDetect' => $parameter['mime_detect'],
'mimefile' => $parameter['mimefile'],
'imgLib' => $parameter['img_lib'],
'tmbPath' => $parameter['tmb_path'],
'tmbPathMode' => $parameter['tmb_path_mode'],
'tmbUrl' => $parameter['tmb_url'],
'tmbSize' => $parameter['tmb_size'],
'tmbCrop' => $parameter['tmb_crop'],
'tmbBgColor' => $parameter['tmb_bg_color'],
'copyOverwrite' => $parameter['copy_overwrite'],
'copyJoin' => $parameter['copy_join'],
'copyFrom' => $parameter['copy_from'],
'copyTo' => $parameter['copy_to'],
'uploadOverwrite' => $parameter['upload_overwrite'],
'uploadAllow' => $parameter['upload_allow'],
'uploadDeny' => $parameter['upload_deny'],
'uploadMaxSize' => $parameter['upload_max_size'],
'defaults' => $parameter['defaults'],
'attributes' => $parameter['attributes'],
'acceptedName' => $parameter['accepted_name'],
'disabled' => $parameter['disabled_commands'],
'treeDeep' => $parameter['tree_deep'],
'checkSubfolders' => $parameter['check_subfolders'],
'separator' => $parameter['separator'],
'timeFormat' => $parameter['time_format'],
'archiveMimes' => $parameter['archive_mimes'],
'archivers' => $parameter['archivers'],
);
if ($parameter['volume_id'] > 0) {
$driverOptions['id'] = $parameter['volume_id'];
}
if (!$parameter['show_hidden']) {
$driverOptions['accessControl'] = array($this, 'access');
};
$options['roots'][] = array_merge($driverOptions, $this->configureDriver($parameter));
}
return $options;
}
Ok, i have found solution. It is necessary to make yoour own custom configuration reader and replace the original one. Configuration class must implement ElFinderConfigurationProviderInterface. See [https://github.com/helios-ag/FMElfinderBundle/blob/master/Resources/doc/advanced-configuration.md#custom-configuration-provider][1] for more details.

Symfony 3.0 load config from php file

I try to set up a symfony project with the microcontroller trait. But instead of use a config.yml I want to use a config.php file.
return [
'framework' => [
'secret' => 'secret_'
]
];
What is the best practice to achieve this?
when using microkernel trait, you can use the configureContainer method in your front controller (app.php) to load configuration directly from an array, like this:
protected function configureContainer(ContainerBuilder $c, LoaderInterface $loader)
{
// PHP equivalent of config.yml
$c->loadFromExtension('framework', array(
'secret' => 'S0ME_SECRET'
));
}
docs here
You should use the container to set the parameters like
$container->setParameter('framework.secret', 'secret_');
as explained in the Symfony Docs

wkhtmltopdf works in command mode but not in Symfony2 bundle (knp_snappy)

I am generating PDF reports about the bundle knp_snappy, as it says in the title, so wkhtmltopdf command works perfectly in command mode but it does in the bundle, I get the following error:
The exit status code '127' says something went wrong:
stderr, "PROT_EXEC | PROT_WRITE failed.
I understand it is something related to permissions but do not know what I have to change to make it work.
my config.yml
knp_snappy:
pdf:
enabled: true
binary: "/usr/bin/wkhtmltopdf"
options: []
My controller:
$html = $this->renderView('PanelBundle:Default:hotel-booking-summary.pdf.html.twig', array(
'summary' => $summary,
'agency' => $agency
));
return new Response(
$this->get('knp_snappy.pdf')->getOutputFromHtml($html),
200,
array(
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="file.pdf"'
)
);
I hope you can help me, greetings and thank you very much.
pls show
ls -la /usr/bin/wkhtmltopdf
Actually you can try set permissions something like
sudo chown %your_ssh_user%:%your_www_group% /usr/bin/wkhtmltopdf

Testing File uploads in Symfony2

In the Symfony2 documentation it gives the simple example of:
$client->request('POST', '/submit', array('name' => 'Fabien'), array('photo' => '/path/to/photo'));
To simulate a file upload.
However in all my tests I am getting nothing in the $request object in the app and nothing in the $_FILES array.
Here is a simple WebTestCase which is failing. It is self contained and tests the request that the $client constructs based on the parameters you pass in. It's not testing the app.
class UploadTest extends WebTestCase {
public function testNewPhotos() {
$client = $this->createClient();
$client->request(
'POST',
'/submit',
array('name' => 'Fabien'),
array('photo' => __FILE__)
);
$this->assertEquals(1, count($client->getRequest()->files->all()));
}
}
Just to be clear. This is not a question about how to do file uploads, that I can do. It is about how to test them in Symfony2.
Edit
I'm convinced I'm doing it right. So I've created a test for the Framework and made a pull request.
https://github.com/symfony/symfony/pull/1891
This was an error in the documentation.
Fixed here:
use Symfony\Component\HttpFoundation\File\UploadedFile;
$photo = new UploadedFile('/path/to/photo.jpg', 'photo.jpg', 'image/jpeg', 123);
// or
$photo = array('tmp_name' => '/path/to/photo.jpg', 'name' => 'photo.jpg', 'type' => 'image/jpeg', 'size' => 123, 'error' => UPLOAD_ERR_OK);
$client = static::createClient();
$client->request('POST', '/submit', array('name' => 'Fabien'), array('photo' => $photo));
Documentation here
Here is a code which works with Symfony 2.3 (I didn't tried with another version):
I created an photo.jpg image file and put it in Acme\Bundle\Tests\uploads.
Here is an excerpt from Acme\Bundle\Tests\Controller\AcmeTest.php:
function testUpload()
{
// Open the page
...
// Select the file from the filesystem
$image = new UploadedFile(
// Path to the file to send
dirname(__FILE__).'/../uploads/photo.jpg',
// Name of the sent file
'filename.jpg',
// MIME type
'image/jpeg',
// Size of the file
9988
);
// Select the form (adapt it for your needs)
$form = $crawler->filter('input[type=submit]...')->form();
// Put the file in the upload field
$form['... name of your field ....']->upload($image);
// Send it
$crawler = $this->client->submit($form);
// Check that the file has been successfully sent
// (in my case the filename is displayed in a <a> link so I check
// that it appears on the page)
$this->assertEquals(
1,
$crawler->filter('a:contains("filename.jpg")')->count()
);
}
Even if the question is related to Symfony2, it appears in the top results when searching for Symfony4 in Google.
Instancing an UploadedFile works, but the shortest way I found was also actually in the official documentation:
$crawler = $client->request('GET', '/post/hello-world');
$buttonCrawlerNode = $crawler->selectButton('submit');
$form = $buttonCrawlerNode->form();
$form['photo']->upload('/path/to/lucas.jpg');
https://symfony.com/doc/current/testing.html#forms
I found this article, https://coderwall.com/p/vp52ew/symfony2-unit-testing-uploaded-file, and works perfect.
Regards
if you want to mock a UploadedFile without a client request, you can use:
$path = 'path/to/file.test';
$originalName = 'original_name.test';
$file = new UploadedFile($path, $originalName, null, UPLOAD_ERR_OK, true);
$testSubject->method($file);

Resources