generating pdf using sinatra and pdf. pdf displays odd in browser - sinatra

I am using pdfkit to generate a pdf via the following code:
get "/:lang/:course/:project/protected/:project.pdf" do
PDFKit.configure do |config|
config.wkhtmltopdf = '/usr/local/bin/wkhtmltopdf'
config.default_options = {
:page_size => 'A3',
# :load_error_handling => 'skip',
# :load_media_error_handling => "ignore",
# :debug_javascript => true,
# :javascript_delay => "300",
:print_media_type => true,
:margin_top => "8mm",
:margin_bottom => "5mm",
:footer_spacing => "-8",
}
end
kit = PDFKit.new("http://localhost:4000/#{params[:lang]}/#{params[:course]}/#{params[:project]}/")
kit.to_pdf
I can see in my puma logs that it is generating the pdf, however when it loads the page I see the following:
It looks like its trying to render the pdf but for reasons unknown to me it displays it like that. Iv tested this in both Chrome & Firefox.
Can anyone point me in the right direction?

In the get request I needed to add the following code:
headers['Content-Type'] = 'application/pdf'

Related

How can I do multipart requests mith Mojo::UserAgent?

I'd like to perform a multipart file upload to Google Drive as described here using a Mojo::UserAgent. I currently do it like this:
my $url = Mojo::URL->new('https://www.googleapis.com/upload/drive/v3/files');
$url->query({ fields => 'id,parents',
ocr => 'true',
ocrLanguage => 'de',
uploadType => 'multipart' });
my $tx = $ua->post($url,
json => { parents => [ '0ByFk4UawESNUX1Bwak1Ka1lwVE0' ] },
{
'Content-Type' => 'multipart/related',
'parents' => [ '0ByFk4UawESNUX1Bwak1Ka1lwVE0' ]
},
$content );
but it doesn't work.
I've managed authorization OK (omitted here) and simple file upload works fine. I just can't seem to do the multipart.
I've tried to make sense of the docs here - but to no avail, in the sense that the file gets uploaded OK, but the JSON part gets ignored, and the file gets uploaded in the root folder.

File Upload in Userfrosting

We need to have the user upload an image as a part of sign up process.
Had tried accessing $_FILES['filename'] in the controller, which turns out to be undefined under slim.
Had seen about Slim's way of file uploading in a couple of articles, which are reported to be working, but I hit the wall.
The twig part works fine with Bootstrap File Input library
For the server part using File Upload library for Slim
Controller code (modifications to AccountController) looks like this
...
$storage = new \Upload\Storage\FileSystem('c:/xampp/htdocs/userfrosting/public/images/');
$file = new \Upload\File('imagefile', $storage);
$new_filename = 'test.jpg';
$file->setName($new_filename);
$file->addValidations(array(
// Ensure file is of type "image/jpg"
new \Upload\Validation\Mimetype('image/jpg'),
// Ensure file is no larger than 500K (use "B", "K", M", or "G")
new \Upload\Validation\Size('500K')
));
// Access data about the file that has been uploaded
$uploadfiledata = array(
'name' => $file->getNameWithExtension(),
'extension' => $file->getExtension(),
'mime' => $file->getMimetype(),
'size' => $file->getSize(),
'md5' => $file->getMd5(),
'dimensions' => $file->getDimensions()
);
error_log('$uploadfiledata' . print_r($uploadfiledata, true));
// Try to upload file
try {
// Success!
$file->upload();
} catch (\Exception $e) {
// Fail!
$errors = $file->getErrors();
}
...
This returns the following error,
Type: InvalidArgumentException
Message: Cannot find uploaded file identified by key: imagefile
File: C:\xampp\htdocs\userfrosting\userfrosting\vendor\codeguy\upload\src\Upload\File.php
Line: 139
The relevant twig chunk is
<input id="imagefile" type="file" name="imagefile" class="file" data-show-upload="false">
Has anyone been able to get file upload working as a part of any Userfrosting code?
Appreciate any help / pointers.
Thanks!
My guess is that you're using ufFormSubmit to submit your registration form, and it is not grabbing the file input. So, you will probably need to add some extra code on the client side to explicitly submit the file input along with the rest of the form. See this example using Dropzone and UF: https://gist.github.com/frostbitten/c1dce70023321158a2fd#file-upload-twig
By the way, you can use your browser to see what data is actually being sent in your POST request. For example, in Firefox you can use the Network Monitor.

zfdatagrid and jqgrid: subgrid is not loading

I am using Zend Framework that's why I decided to use "zfdatagrid deploy jqgrid" instead of using jqgrid straight away.
I want to have jqgrid with subgrid. Grid is shown ok, but when I click expand button then I get notice "Loading" but nothing happens. I have debugged that "subGridUrl" is called correctly, because debugger hit function where I should select data from MySQL for subgrid, and I tried to pass pure json response (instead of selecting from MySQL) but still subgrid is not shown. Maybe I don't understand what response must be? My response:
<...>
$responce = new stdClass();
$responce->rows[0]['id']='0';
$responce->rows[0]['cell']=array('0','test1','123','1');
$responce->rows[1]['id']='1';
$responce->rows[1]['cell']=array('1','test2','321','2');
$j = json_encode($responce);
echo $j;
<...>
Sorry, my bad. But instead of deleting my question, I will explain my mistake incase somebody else will do the same...
I made a mistake declaring "subGridModel". Instead using array:
$jqGrid->setJqgParams(array(
'caption' => 'test report',
<..>
'subGrid' => true,
'subGridUrl' => $this->view->url(array('controller'=>'report','action'=>'indexstoragebalancesubgrid'),'default', true),
'subgridtype' => 'json',
'loadonce' => false,
// next line where problem fixed
'subGridModel' => array(array("name" => array("ID", "Title", "Code", "Quantity"), "width" => array(10,55,200,80)))
<..>
));
I wrote string:
'subGridModel'=>'[{name : ["ID", "Title", "Code", "Quantity"], width : [10,55,200,80]}]'
And that's why it did not work in javascript.
By the way, you can see that I wrote array in array. That is because with one array ZFDataGrid generates such javascript:
"subGridModel":{"name":["ID","Title","Code","Quantity"],"width":[10,55,200,80]}
instead of this:
"subGridModel":[{"name":["ID","Title","Code","Quantity"],"width":[10,55,200,80]}]
It is important for jqgrid subgrid to work!

SoundCloud API: Tweeting on upload and disable comments

The following PHP code uploads a new track to SoundCloud successfully, but the tweet is not sent.
Is there something I need to have in there as well in order to do this?
$track = $soundcloud->post('tracks',
array(
'track[asset_data]' => '#audio.mp3',
'track[title]' => "my audio",
'track[description]' => "Updated: " . date('l jS F Y h:i:s A'),
'track[sharing]' => 'public',
'track[shared_to][connections][][id]' => '123',
'track[sharing_note]' => 'Have a listen to'
));
Also I'd like to be able to disable comments on the audio I upload, but I wasn't sure what the parameter for that would be too?
Thanks!
dB
I'm unable the repro the sharing problem. Please note that sometimes sharing on other social networks doesn't happen right away. Are you still having trouble? Here's the code I used:
<?php
require_once 'Services/Soundcloud.php';
$client = new Services_Soundcloud("foo", "bar");
$client->setAccessToken('ACCESS_TOKEN');
$track = $client->post('tracks', array(
'track[title]' => 'Foooo',
'track[asset_data]' => '#/Users/paul/audio.wav',
'track[sharing]' => 'public',
'track[shared_to][connections][][id]' => 'CONNECTION_ID',
'track[sharing_note]' => 'Check it out'
));
print_r($track);
Also verify that your CONNECTION_ID is correct. Some code to get a list of connections so you can verify the id:
<?php
require_once 'Services/Soundcloud.php';
$client = new Services_Soundcloud("foo", "bar");
$client->setAccessToken('ACCESS_TOKEN');
print_r(json_decode($client->get('me/connections')));
Unfortunately there's no way currently to disable comments via the API. I'll file a bug and see about getting this fixed.
Hope that helps!

Zend_Cache_Frontend_Page does not recognize output without echo

I am trying to fiddle around with Zend_Cache, so I added following code to my action (will be moved to bootstrap later, I guess):
$frontendOptions = array(
'lifetime' => 7200,
'debug_header' => true, // für das Debuggen
'default_options' => array(
'cache' => true,
'cache_with_get_variables' => true,
'cache_with_session_variables' => true,
'cache_with_cookie_variables' => true,
'cache_with_post_variables' => true,
)
);
$backendOptions = array(
'cache_dir' => '/tmp/'
);
$cache = Zend_Cache::factory('Page', 'File',
$frontendOptions, $backendOptions
);
echo "hej";
var_dump($cache->start('someid'));
Zend generates a cache file containing hejbool(false) now, but apart from that it does not cache my page. According to a German book about zend framework, false is correct when there is no cache available. true is only returned when a cache was found.
When I debugged within Zend_Cache_Frontend_Page.php directly, it went down to the bottom of the start()-method, meaning that nothing went wrong (id given) and no cache was found, so one had to be generated. This was done (I can see it in /tmp/), but without the needed content.
So why does not not cache the output from Zend_View, but only direct output via echo?
I do not call any explicit function to render the view, but this did not seem necessary anymore (my views are always rendered automatically according to controller and action). I tried it for both a standard XHTML template (index.phtml) and an RSS template (index.rss.phtml).
Any ideas? Do you need any other code fragments?
When using the Zend_Cache_Frontend_Page you have to enable the disableOutputBuffering option. The reason is that Zend_Cache_Frontend_Page uses ob_start with a callback and it has to be the first call to ob_start otherwise it leads to that strange behaviour you've encountered.
To enable it you can either set it in your Bootstrap with
Zend_Controller_Front::getInstance()->setParam('disableOutputBuffering', true);
or using the configuration file after your frontController-setup (here in the INI-style configuration):
resources.frontController.params.disableOutputBuffering = true