Symfony3 + FPDF - return response in new window. - symfony

In Symfony3, I want to use FPDF to generate a pdf output. It's OK but my problem is that this output is on the current tab. I would like this output opens a new tab and appears in it. I tested pdf output this way :
public function testAction(request $request)
{
$pdf = new \FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->SetTextColor(0, 0, 0);
$pdf->Multicell(190, 5, "Hello World!", '', 'C', false);
return new Response($pdf->Output(), 200, array('Content-Type' => 'application/pdf'));
}
Thank you to help me solving this teasing problem !

You can't do it on the server side (by using PHP), but if you're using a form for calling this action you could set target=__blank and it'll do the job. You can also achieve this result by using js (e.g. you're using ajax).

Related

How to trigger a server side Suitelet Script from Client Script in 2.0?

I have a suitelet script (server side- working on back end) which needs to be triggered from a client script without getting navigated to that Suitelet page.
I tried using resolveScript and it makes the script work but it navigates the page to the suitelet page which is blank.
Can anyone suggest me which API to use which will trigger my Suitelet Script but remain on the same page where I m right now?
My Code:
function goToOpportunityRec() {
var rec = curr.get();
/* if i uncomment this setValue, the script stops working
curRec.setValue({
fieldId: 'custrecord_awt_status',
value: 3,
ignoreFieldChange: true
}); */
var suiteletURL = url.resolveScript({
scriptId: 'customscript_mx_awtitem_sl',
deploymentId: 'customdeploy_mx_awtitem_sl',
returnExternalUrl: false
});
suiteletURL += '&id=' + rec.id;
newWindow = window.open(suiteletURL);
}
If I remove the window.open, the Suitelet wouldn't trigger.
Please suggest a solution
In my case, I called my suiteletscript when I click button[Client script] on record.
function pageInit(context) {
}
function onButtonClick() {
document.location.href='/app/site/hosting/scriptlet.nl?script=726&deploy=1';}
exports.onButtonClick = onButtonClick;
exports.pageInit = pageInit;
return exports;});

Pdf Generation using Rotativa in ASP.Net MVC5

I am Generating PDF using Rotativa. Below is my Function to generate PDF:
public ActionResult GeneratePDF()
{
return new ViewAsPdf("pdfView")
{
FileName = "Fee_Challan.pdf",
PageOrientation = Orientation.Landscape,
PageSize = Size.A4,
PageMargins = { Left = 10, Right = 10, Top = 15, Bottom = 22 },
MinimumFontSize = 7,
PageHeight = 40
};
}
I'm Calling this function from Create method. When I call it in return RedirectToAction("GeneratePDF"); it works fine.
But when I call it before the return statement, it does not work.
GeneratePDF(); //this does not work. But I want to use this approach.
return RedirectToAction("index","Applicants");
I want to load another view after PDF is generated, that is why I don't want to call GeneratePDF() in RedirectToAction(). The debugger shows that the method is being executed fine. Tell my why it is not Working.
It is not working because in your case the GeneratePDF() method indeed returns a view as pdf. So what are you doing with it? The answer is: Nothing!
GeneratePDF(); //this returns an ActionResult which contains your pdf, but you do nothing with it here
return RedirectToAction("index","Applicants"); // this redirects the user to another action
So in this case you can only redirect the user to another action or return the pdf. You can not have two return statements in the same method.
In order to make the user not being able to generate the same pdf again (which should be harmless, so which would be the problem if the user wants the pdf again? but it's your choice how you want your application to work) you will have to disable (hide or even redirect to another page, etc.) using javascript.
Hope this covers it all. Cheers!

Mocking a GuzzleHttp response

How should I mock a Guzzle response properly. When testing a parser I'm writing, the test html is contained in files. In my PHPUnit tests I'm doing file_read_contents and passing the result into my method. Occasionally the HTML will link to a seperate file. I can mock this response like so:
public function testAlgo()
{
$mock = new MockAdapter(function() {
$mockhtml = file_get_contents($this->dir . '/HTML/authorship-test-cases/h-card_with_u-url_that_is_also_rel-me.html');
$stream = Stream\create($mockhtml);
return new Response(200, array(), $stream);
});
$html = file_get_contents($this->dir . '/HTML/authorship-test-cases/h-entry_with_rel-author_pointing_to_h-card_with_u-url_that_is_also_rel-me.html');
$parser = new Parser();
$parser->parse($html, $adaptor = $mock);
Then in my actual method, when I make the guzzle request this code works:
try {
if($adapter) {
$guzzle = new \GuzzleHttp\Client(['adapter' => $adapter]);
} else {
$guzzle = new \GuzzleHttp\Client();
}
$response = $guzzle->get($authorPage);
So obviously this isn't ideal. Does anyone know of a better way of doing this?
$html = (string) $response->getBody();
EDIT: I'm now using the __construct() methid to set up a default Guzzle Client. Then a using a second function that can be called by tests to replace the Client with a new Client that has the mock adapter. I'm not sure if this is the best way to do things.
You can use the MockPlugin API, like so:
$plugin = new MockPlugin();
$plugin->addResponse(__DIR__.'/twitter_200_response.txt');
The txt file then contains everything from your response, including headers.
There are also good approaches available here: http://www.sitepoint.com/unit-testing-guzzlephp/
Also there are articles found here: http://guzzle3.readthedocs.io/testing/unit-testing.html

Send Gravity Forms data to redirection page

I have a very simple form created with Gravity Forms;
It submits two numbers and then redirects to a different result page.
How do I retrieve those two numbers on the result page?
add_filter("gform_confirmation_4", "custom_confirmation", 3, 4 );
function custom_confirmation($confirmation, $form, $lead, $ajax)
Gives a custom confirmation. Each field value can be retrieved by using $lead[{field ID}]
I have a solution for this based on using a combination of form submission hooks and the GForms API. It's a horrible plugin so I apologise for the messiness of the logic flow. It's important to use the framework methods rather than processing the data yourself since there are a good amount of hacks and shonky things going on in there to correctly match field IDs and so forth.
I will provide a solution to pass a submission from one form to pre-populate another. Changing the destination for POST data is pretty straightforward, they have an example for it on their gform_form_tag hook documentation page. Yes, that really is the only way of doing it.
Without further ado here is the code. I've set it up to work off form configuration to make things simpler for the end user, so it works like this:
Select "allow field to be populated dynamically" in your destination form field's advanced settings and choose a parameter name for each.
Add matching CSS classes on the source fields of the other form(s) to setup the associations.
Add a CSS class to the source forms themselves so that we can quickly check if the redirection is necessary.
.
$class = 'GForms_Redirector';
add_filter('gform_pre_submission', array($class, 'checkForSubmissionRedirection'), 10, 1);
add_filter('gform_confirmation', array($class, 'performSubmissionRedirection'), 10, 4);
abstract class GForms_Redirector
{
const SOURCE_FORMS_CLASS_MATCH = 'submission-redirect';
const DEST_PAGE_SLUG = 'submit-page-slug';
const DEST_FORM_ID = 1;
protected static $submissionRedirectUrl;
// first, read sent data and generate redirection URL
function checkForSubmissionRedirection($form)
{
if (false !== preg_match('#\W' . self::SOURCE_FORMS_CLASS_MATCH . '\W#', $form['cssClass'])) {
// load page for base redirect URL
$destPage = get_page_by_path(self::DEST_PAGE_SLUG);
// load form for reading destination form config
$destForm = RGFormsModel::get_form_meta(self::DEST_FORM_ID, true);
$destForm = RGFormsModel::add_default_properties($destForm);
// generate submission data for this form (there seem to be no hooks before gform_confirmation that allow access to this. DUMB.)
$formData = GFFormsModel::create_lead($form);
// create a querystring for the new form based on mapping dynamic population parameters to CSS class names in source form
$queryVars = array();
foreach ($destForm['fields'] as $destField) {
if (empty($destField['inputName'])) {
continue;
}
foreach ($form['fields'] as $field) {
if (preg_match('#(\s|^)' . preg_quote($destField['inputName'], '#') . '(\s|$)#', $field['cssClass'])) {
$queryVars[$destField['inputName']] = $formData[$field['id']];
break;
}
}
}
// set the redirect URL to be used later
self::$submissionRedirectUrl = get_permalink($destPage) . "?" . http_build_query($queryVars);
}
}
// when we get to the confirmation step we set the redirect URL to forward on to
function performSubmissionRedirection($confirmation, $form, $entry, $is_ajax = false)
{
if (self::$submissionRedirectUrl) {
return array('redirect' => self::$submissionRedirectUrl);
}
return $confirmation;
}
}
If you wanted to pass the form values someplace else via the querystring then you'd merely need to cut out my code from the callback and build your own URL to redirect to.
This is a very old question, now you can send it using a Query String on the confirmation settings.
They have the documentation on this link:
How to send data from a form using confirmations
Just follow the first step and it will be clear to you.

Annotation in pdfclown

I am trying to put a sticky note at some x,y location. For this i am using the pdfclown annotation class in .net.
Below is what is available.
using files = org.pdfclown.files;
public override bool Run()
{
files::File file = new files::File();
Document document = file.Document;
Populate(document);
Serialize(file, false, "Annotations", "inserting annotations");
return true;
}
private void Populate(Document document)
{
Page page = new Page(document);
document.Pages.Add(page);
PrimitiveComposer composer = new PrimitiveComposer(page);
StandardType1Font font = new StandardType1Font(document, StandardType1Font.FamilyEnum.Courier, true, false);
composer.SetFont(font, 12);
annotations::Note note = new annotations::Note(page, new Point(78, 658), "this is my annotation...");
note.IconType = annotations::Note.IconTypeEnum.Help;
note.ModificationDate = new DateTime();
note.IsOpen = true;
composer.Flush();
}
Link for annotation
This is putting a sticky note at 78, 658 cordinates in a blank pdf.
The problem is that i want that sticky note in a particular pdf which has some data. How can i modify it...thanks for the help..
I'm the author of PDF Clown -- this is the right way to insert an annotation like a sticky note into an existing page:
using org.pdfclown.documents;
using annotations = org.pdfclown.documents.interaction.annotations;
using files = org.pdfclown.files;
using System.Drawing;
. . .
// Open the PDF file!
using(files::File file = new files::File(#"C:\mypath\myfile.pdf"))
{
// Get the document (high-level representation of the PDF file)!
Document document = file.Document;
// Get, e.g., the first page of the document!
Page page = document.Pages[0];
// Insert your sticky note into the page!
annotations::Note note = new annotations::Note(page, new Point(78, 658), "this is my annotation...");
note.IconType = annotations::Note.IconTypeEnum.Help;
note.ModificationDate = new DateTime();
note.IsOpen = true;
// Save the PDF file!
file.Save(files::SerializationModeEnum.Incremental);
}
Please consider that there are lots of options about the way you can save your file (to an output (in-memory) stream, to a distinct path, as a compacted file, as an appended file...).
If you look at the 50+ samples accompanying the library's distribution, along with the API documentation, you can discover how expressive and powerful it is. Its architecture strictly adheres to the official Adobe PDF Reference 1.7.
enjoy!

Resources