Symfony 2 KnpSnappy Bundle Error - php

I m trying to implement Knp SNappy Bundle to display an html page as a pdf from my controller.
I'm stuck with this error :
The exit status code '1' says something went wrong:
stderr: "Loading pages (1/6)
[> ] 0%
[======> ] 10%
[==========> ] 18%
Warning: Failed to load file:///slick/slick.css (ignore)
Warning: Failed to load file:///slick/slick-theme.css (ignore)
Warning: Failed to load file:///clovis-app/style.css (ignore)
Warning: Failed to load file:///clovis-app/estimate.css (ignore)
Warning: Failed to load file:///clovis-app/res/clovis.png (ignore)
Warning: Failed to load file:///js/collection.js (ignore)
Warning: Failed to load file:///clovis-app/script.js (ignore)
Warning: Failed to load file:///clovis-app/estimate.js (ignore)
[============================================================] 100%
Counting pages (2/6)
[============================================================] Object 1 of 1
Resolving links (4/6)
[============================================================] Object 1 of 1
Loading headers and footers (5/6)
Printing pages (6/6)
[> ] Preparing
[===================> ] Page 1 of 3
[=======================================> ] Page 2 of 3
[============================================================] Page 3 of 3
Done
Exit with code 1 due to network error: ContentOperationNotPermittedError"
stdout: ""
command: "C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe" --lowquality "C:\Users\Razgort\AppData\Local\Temp\knp_snappy55ae6cc4ad0353.17775155.html" "C:\Users\Razgort\AppData\Local\Temp\knp_snappy55ae6cc4ad41d0.64896673.pdf".
Here is my configuration file :
knp_snappy:
pdf:
enabled: true
binary: "\"C:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltopdf.exe\""
options: []
image:
enabled: true
binary: "\"C:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltoimage.exe\""
options: []
and here is how i render the view :
$html = $this->renderView('CompanyBundle:Estimate:edit.html.twig', array(
'estimate' => $estimate,
'estimateForm' => $estimateForm->createView(),
'articleForm' => $articleForm->createView(),
'articleSelectForm' => $articleSelectForm->createView(),
'manpowerForm' => $manpowerForm->createView(),
'manpowerSelectForm' => $manpowerSelectForm->createView(),
'workSelectForm' => $workSelectForm->createView(),
'workForm' => $workForm->createView(),
'bundleForm' => $bundleForm->createView(),
'bundleSelectForm' => $bundleSelectForm->createView(),
));
return new Response(
$this->get('knp_snappy.pdf')->getOutputFromHtml($html),
200,
array(
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="file.pdf"'
)
);
I eard there is problems on MAMP, i use wamp, didn't see any issue with it.
I'll really appreciate some help on this =)
Edit :
I modified some things in order to generate a pdf first. And i did. But the pdf only contents my login page. Then i added the access to my session and it worked. But when i try to send it as a response like that :
$session = $this->get('session');
$session->save();
session_write_close();
$pageUrl = $this->generateUrl('estimate_preview', array('id' => $id), true);
return new Response(
$this->get('knp_snappy.pdf')->getOutput($pageUrl, array('cookie' => array($session->getName() => $session->getId()))),
200,
array(
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="file.pdf"'
)
);
it doesn't seem to work either... Does someone have an idea why ?

Try by using forward (getContent()) method instead render.
$html = $this->forward('CompanyBundle:Estimate:edit.html.twig', array(
'estimate' => $estimate,
'estimateForm' => $estimateForm->createView(),
'articleForm' => $articleForm->createView(),
'articleSelectForm' => $articleSelectForm->createView(),
'manpowerForm' => $manpowerForm->createView(),
'manpowerSelectForm' => $manpowerSelectForm->createView(),
'workSelectForm' => $workSelectForm->createView(),
'workForm' => $workForm->createView(),
'bundleForm' => $bundleForm->createView(),
'bundleSelectForm' => $bundleSelectForm->createView(),
))->getContent();
$pdf =$this->get('knp_snappy.pdf')->getOutputFromHtml($html);
First check by printing $pdf and then you can return it as a response.

Do this for all your CSS files in your Twig:
<link rel="stylesheet" href="{{ app.request.scheme ~'://'~ app.request.httpHost ~ asset('css/my_custom_stylesheet.css') }}" />
The CSS folder must be directly under /web

Knp SNappy Bundle is a wrapper. In your symphony side you do all right.
But in your HTML-to-render you have relative URLs, that is not absolute to HTTP-server. So when wkhtmltopdf see in your HTML url like '/dsasdaasd/sdaasd.wtf', it does not know, that it's your site.
1st option. Render PDF by URL (pass some option like "use print styles").
2nd: Use in your HTML absolute pathes to assets.
Anyway there is no absolute correct HTML, so you can meet in the future more errors like this -- even if in huge HTML there will be only one not-found-image. So try to find some options in snappy to ignore these errors as in the result pdf will be generated ok.

Related

Phpunit testing, error when including file

Very new to php unit and can't exactly work out whats wrong. My class is as follows:
<?php
include $_SERVER['DOCUMENT_ROOT'] . '/assets/php/global_php_includes.php';
use PHPUnit\Framework\TestCase;
final class PesticideTests extends TestCase {
public function addPesticideTest() {
$data = array(
"code" => randomString(16),
"created_by" => $_SESSION['userCode'],
"company_code" => "TEST_COMPANY",
"crop_code" => "TEST_CROP",
"content" => "TEST_CONTENT",
"comments" => "TEST_COMMENTS",
"function" => "TEST_FUNCTION",
"pcs_no" => 0123,
"phi" => "TEST_PHI",
"product_name" => "TEST_PRODUCT",
"substance" => "TEST_SUBSTANCE",
"date_of_reg_review" => "01-01-0001",
"use_by_date" => "01-01-0001",
"off_label_approval" => "TEST_OFF_LABEL_APPROVED",
"latest_time_of_application" => "TEST_LATEST_TIME_OF_APPLICATION",
"max_individual_dose" => "TEST_MAX_INDIVIDUAL_DOSE",
"max_total_dose" => "TEST_MAX_TOTAL_DOSE",
"max_no_applications" => "TEST_MAX_NO_APPLICATIONS",
"method_of_application" => "TEST_METHOD_OF_APPLICATION",
"status" => 'inactive'
);
$result = addPesticide($connection, $data);
$this->assertEquals(1, $result);
}
}
the command I run to test it is ./vendor/bin/phpunit tests/PesticideTests.php
and the error I get is
PHP Warning: include(/assets/php/global_php_includes.php): failed to open stream: No such file or directory in C:\xampp\htdocs\tapp\tests\PesticideTests.php on line 3
Warning: include(/assets/php/global_php_includes.php): failed to open stream: No such file or directory in C:\xampp\htdocs\tapp\tests\PesticideTests.php on line 3
PHP Warning: include(): Failed opening '/assets/php/global_php_includes.php' for inclusion (include_path='C:\xampp\php\PEAR') in C:\xampp\htdocs\tapp\tests\PesticideTests.php on line 3
Warning: include(): Failed opening '/assets/php/global_php_includes.php' for inclusion (include_path='C:\xampp\php\PEAR') in C:\xampp\htdocs\tapp\tests\PesticideTests.php on line 3
PHPUnit 9.5.2 by Sebastian Bergmann and contributors.
W 1 / 1 (100%)
Time: 00:00.014, Memory: 4.00 MB
There was 1 warning:
1) Warning
No tests found in class "PesticideTests".
WARNINGS!
Anyone have any idea what I'm doing wrong? If I also run it as just ./vendor/bin/phpunit tests then I get the error "No tests found". Pretty confused
EDIT:
I have fixed the test not being found by naming it by the wrong convention, still getting an error for the include file
When running your code withing phpunit there is no $_SERVER['DOCUMENT_ROOT'] set. This only gets set when running in the context of a webserver. Just replace this with the directory where the assets directory is.

How to get the size of the image?

I have this array wanna get the size of the image:
$main_image = $product->images()->where('main_image', 1)->first();
if($main_image){
$url = asset('uploads/products/'. $main_image['image']);
$image[] = [
"name" => $main_image->image,
"type" => FileUploader::mime_content_type($main_image->image_path),
"size" => filesize($url),
"file" => $main_image->image_path,
"local" => $main_image->image_path,
];
}
I got this error:
filesize(): stat failed for http://myapp.test/uploads/products/83QhiRFarGpV.jpeg
Even my image exists in the folder!:
I tried all the options in this one but still same error at all!
Your code is using asset() to generate the $url:
http://myapp.test/uploads/products/83QhiRFarGpV.jpeg
The filesize() function works with local files, not URLs.
filesize($main_image->image_path) should work since you are using it in the line above to get the file type.
You probably also have another issue with
"file" => $main_image->image_path,
"local" => $main_image->image_path,
Where you probably want the file to be $url instead.

Wkhtmltopdf Gives An uncaught Exception

I am trying to wkhtmltopdf for download my data to pdf getting an errors below.
Any help would be really appreciated.
An uncaught Exception was encountered
Type: Exception
Message: System error
Loading pages (1/6)
[> ] 0%
[======> ] 10%
[=======> ] 12%
Warning: SSL error ignored
[========> ] 14%
[=========> ] 16%
[==========> ] 18%
[============> ] 20%
[=============> ] 23%
[===============> ] 25%
[================> ] 27%
[=================> ] 29%
[==================> ] 31%
[===================> ] 33%
[=====================> ] 35%
[======================> ] 38%
[========================> ] 40%
[=========================> ] 43%
[===========================> ] 45%
[============================> ] 47%
[=============================> ] 49%
[=====================================> ] 63%
[==========================================> ] 70%
[=============================================> ] 76%
[=================================================> ] 83%
[============================================================] 100%
Counting pages (2/6)
[============================================================] Object 1 of 1
Resolving links (4/6)
[============================================================] Object 1 of 1
Loading headers and footers (5/6)
Printing pages (6/6)
[> ] Preparing
[==============================> ] Page 1 of 2
[============================================================] Page 2 of 2
Done
Filename: application/libraries/Wkhtmltopdf.php
Line Number: 866
Backtrace:
File: /var/www/admin/index.php
Line: 315
Function: require_once
Here's the line from my PHP codeigniter file that's sending the error in case that helps:
$html = $this->load->view('report/view_course_summary_pdf', $data, true);
$pdfFilePath = "Course_Summary_Report.pdf";
$options['path'] = $myPath;
$options['orientation'] = 'Landscape';
$options['commandOptions'] =
array(
'useExec' => true, // Can help if generation fails without a useful error message
'procEnv' => array(
// Check the output of 'locale' on your system to find supported languages
'LANG' => "'" . $this->session->userdata('lang_code') . "_US.utf-8" . "'",
)
);
$this->load->library('wkhtmltopdf', $options);
$this->wkhtmltopdf->setTitle($this->common_lang->get_lang_token('course_summary_report'));
$this->wkhtmltopdf->setOptions(['ignoreWarnings' => true]);
$this->wkhtmltopdf->setHtml($html); // $html can be a url or html content.
$this->wkhtmltopdf->output(Wkhtmltopdf::MODE_DOWNLOAD, $pdfFilePath);
A bunch of people have talked about similar issues that are related to using WKPDF with an SSL, but I don't think that's causing my problems since it says the SSL error was ignored... Any help would be really appreciated. Whenever I try doing it, there my HTML is download but it corrupted format using above Codeginter code.

php soapclient wsdl SOAP-ERROR: Parsing WSDL: Couldn't load from

I have googled and looked here in stackoverflow but I have not found a solution to my specific problem. I keep getting the error
SOAP-ERROR: Parsing WSDL: Couldnt load from "https://sampleurl.com/MerchantQueryService.asmx?WSDL" : failed to load external entity "https://sampleurl.com/MerchantQueryService.asmx?WSDL"
I am trying to use a SOAP API with a URL like
https://sampleurl.com/MerchantQueryService.asmx?WSDL
I am running MAMP on my localhost and using godaddy shared hosting, I have tried on both with the wsdl file can be found here
http://clemdemo.com/test.wsdl
In PHP I use the code below
error_reporting(-1);
ini_set('display_errors', 'On');
ini_set('soap.wsdl_cache_enabled', 0);
echo "<pre>";
try {
$url = "https://sampleurl.com/MerchantQueryService.asmx?WSDL ";
$headers = [
'Host: sampleurl.com',
'Connection: Keep-Alive',
'User-Agent: PHP-SOAP/5.3.29',
'Content-Type: text/xml; charset=utf-8',
'SOAPAction: "RequestTransaction"',
'Content-Length: 409'];
$rq = [
"userName" => "username_here",
"passWord" => "password_here",
"referenceId" => "3455566694",
"msisdn" => "346774313"];
try {
$cient = new SoapClient($url,
[
'soap_version' => SOAP_1_2,
'exceptions' => 1,
'cache_wsdl' => WSDL_CACHE_NONE,
'trace' => 1,
'stream_context' => stream_context_create(array('http' => array('header' => $headers)))
]);
print_r($cient);
} catch (SoapFault $e) {
echo "\nFault Code: ".$e->faultcode;
echo "\nFault String: ".$e->faultstring;
}
On my MAMP localhost i have SOAP,openssl and curl.
ALSO, I tried using (sending request) to the API with an online WSDL http://wsdlbrowser.com it WORKS but on code using PHP it fails
It often happens that providers neglect their SSL certificates and hence the sites and services end up having an invalid certificates - I suspect this is the case here.
Disabling the certificate validation as described by Kaii here or even better get your provider to fix their certificate.
Your code could/should then be something like:
$url = "https://sampleurl.com/MerchantQueryService.asmx?WSDL ";
$context = stream_context_create(array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
));
$rq = ["userName" => "username_here",
"passWord" => "password_here",
"referenceId" => "3455566694",
"msisdn" => "346774313"];
$service = new SoapClient($url, array('stream_context' => $context));
$service->RequestTransaction($rq);
The error message appears to say that your app is not able to read our WSDL. Try opening a browser from the same machine on which your app is running and see if you can access the WSDL address at https://sampleurl.com/MerchantQueryService.asmx?WSDL.
If not - you have a network/firewall/Anti Virus problem. (in case)
If you can access this address from a browser - is your app still experiencing this problem? then check any app that could be hindering your firewall.(Anti virus are most probable cause)
If you use docker there is a chance you get error because of OpenSSL default security level. Even if you disable verify and allow self-signed in SoapClient options.
Try out to lower seclevel in /etc/ssl/openssl.cnf from DEFAULT#SECLEVEL=2 to
DEFAULT#SECLEVEL=1
Or just add into Dockerfile
RUN sed -i "s|DEFAULT#SECLEVEL=2|DEFAULT#SECLEVEL=1|g" /etc/ssl/openssl.cnf
By: https://github.com/dotnet/runtime/issues/30667#issuecomment-566482876
You can verify it by run on container
curl -A 'cURL User Agent' -4 https://ewus.nfz.gov.pl/ws-broker-server-ewus/services/Auth?wsdl
Better diagnostics can be performed with: libxml_get_last_error();
Could have cached a bad response, set 'cache_wsdl' => WSDL_CACHE_NONE when initating the object
if you skip cache, and get this in your libxml error:
LibXMLError Object
(
[level] => 1
[code] => 1549
[column] => 0
[message] => failed to load external entity "URL"
[file] =>
[line] => 0
)
With no description on Ubuntu, then its not pulling the file period. You just got hit with the Ubuntu update. Wave them the bronx salute and reboot.

Symfony 2 kpn snappy generate pdf with output meets security area

I`m using Symfony2 kpn snappy bundle to generate pdfs. I want to generate PDF from an html page with css. I found a solution, but it has a problem with :
$pageUrl = $this->generateUrl('accounts_management_generate_pdf_markup',
array('invoice' => $invoiceData), true); // use absolute path!
return new \Symfony\Component\HttpFoundation\Response(
$this->get('knp_snappy.pdf')->getOutput($pageUrl), 200, array(
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="file.pdf"'
)
);
The problem is that the pageUrl accounts_management_generate_pdf_markup is behind a security area and cannot be accessed without authentication. The generated file is just the login page, to which this path accounts_management_generate_pdf_markup redirects if not logged.
My questions are:
Is there any way to pass to snappy authentication credentials?
Is there another way using snappy bundle to generate the pdf using styles(css)
You can add the session cookie as an argument to the getOutput function:
$pageUrl = $this->generateUrl('route', array('id' => $id), true);
$session = $this->get('session');
$session->save();
session_write_close();
return new Response(
$this->get('knp_snappy.pdf')->getOutput($pageUrl, array('cookie' => array($session->getName() => $session->getId()))),
200,
array(
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="file.pdf"'
)
);

Categories