I'm using Rotativa (v1.6.4) for converting an MVC view into a PDF. I have used jQuery in the View to show/hide certain text content.
When I render the View, I see that jQuery is working, but when I render viewaspdf, the jquery is not working.
I have added --debug-javascript --no-stop-slow-scripts --javascript-delay 10000 but this looks to be not working. Can someone help me here?
Here is Controller detail:
public ActionResult PrintBenificiaryForm()
{
PrintBenificiary p = new PrintBenificiary();
p.TeamMemberInfo = GetSessionValues();
p.IndividualBenefitPlans = GetBenefitPlansandIndividuals();
string customSwitches = string.Format("--debug-javascript --no-stop-slow-scripts --javascript-delay 10000 --footer-left \"[page] of [toPage]\" --footer-spacing -10 --footer-font-size \"10\" --header-html \"{0}\" ", Url.Action("PrintHeader", "Home", null, this.Request.Url.Scheme));
return new ViewAsPdf("PrintBenificiaryForm", p)// { FileName = p.TeamMemberInfo.FirstName + " " + p.TeamMemberInfo.LastName + ".pdf" };
{
CustomSwitches = customSwitches
};
//return View(p);
}
I faced the same issue. I resolved this by editing 'qt.browser' in the 'App_Browsers' folder. It was created by Rotativa during the installing package from NuGet. I changed capability with name="javascriptversion" from 1.7 to my version of jquery - 3.1.1. And this resolved my issue. Hope this help someone
Related
I am using Rotativa to generate a pdf from a view I have created. Locally this works fine, the pdf is stored on my local computer and the email functiont then attaches and sends the file. But when I release it on our server, it basically breaks at this part:
var binary = pdf.BuildPdf(this.ControllerContext);
The website takes ages to load and then finally just says
Sorry, an error occurred while processing your request.
What i did to test this was to redirect to the actual view which will be generated in a pdf until this error was shown. I thought the issue was that the website does not have any write rights but could create directories in the required folder up until the above part mentioned.
What can I do to solve this?
Here is my full section of code for this part:
string Switches = string.Format("--print-media-type --header-html {0} --footer-html {1}", Url.Action("Header", "Home", new { area = "" }, "http"), Url.Action("Footer", "Home", new { area = "" }, "http"));
var fileName = ReportName+objScor.Name+"_"+objScor.Surname + DateTime.Now.ToString("dd MMM yyyy HHmmss") + ".pdf";
var filePath =(#"C:\\PDFReport\\" + fileName);
if (!System.IO.File.Exists(#"C:\\PDFReport\\"))
{
Directory.CreateDirectory(#"C:\\PDFReport\\");
}
var pdf = new Rotativa.ViewAsPdf("Report", report)
{
FileName = fileName,
CustomSwitches = Switches
};
var binary = pdf.BuildPdf(this.ControllerContext);
Thanks in advance.
0.7 and I want to Call an Applet for use a Token.
I did various tests:
1) Use of AppletIntegration 1.2.9 but when I call applet there's an Exception "ClassNotFoundException PaintTarget"
2) Download Legacy 1.2.10 by https://github.com/Haulmont/AppletIntegration/releases but when I cal the page I have the Exception ""Widgetset does not contain implementation for org.vaadin.applet.AppletIntegration. Check its #ClientWidget mapping, widgetsets GWT module description file and re-compile your widgetset. In case you have downloaded a vaadin add-on package, you might want to refer to add-on instructions. Unrendered UIDL:
org.vaadin.applet.AppletIntegration(NO CLIENT IMPLEMENTATION FOUND)"
3) I create a class AppletCustom
public class AppletCustom extends CustomComponent {
public AppletCustom(String codebase,
String archive,
String code,
String width,
String height,
Map<String, String> params) {
setCompositionRoot(new Label("<div id='appletDiv'></div>", ContentMode.HTML));
StringBuilder sb = new StringBuilder();
/* create the applet */
sb.append("var obj = document.createElement('object');");
sb.append("obj.setAttribute('type','application/x-java-applet');");
sb.append("obj.setAttribute('width','" + width + "');");
sb.append("obj.setAttribute('height','" + height + "');");
sb.append("var codeParam = document.createElement('param');");
sb.append("codeParam.setAttribute('name', 'code');");
sb.append("codeParam.setAttribute('value', '" + code + "');");
sb.append("obj.appendChild(codeParam);");
sb.append("var archiveParam = document.createElement('param');");
sb.append("archiveParam.setAttribute('name', 'archive');");
sb.append("archiveParam.setAttribute('value','" + archive + "');");
sb.append("obj.appendChild(archiveParam);");
sb.append("var param = document.createElement('param');");
sb.append("param.setAttribute('name', 'codebase');");
sb.append("param.setAttribute('value','" + codebase + "');");
sb.append("obj.appendChild(param);");
/* add params to the applet if you like */
if(params != null && !params.isEmpty()){
Iterator<Entry<String, String>> it =
params.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, String> pairs = (Map.Entry<String, String>) it.next();
sb.append("param = document.createElement('param');");
sb.append("param.setAttribute('name', '" + pairs.getKey() + "');");
sb.append("param.setAttribute('value','" + pairs.getValue() + "');");
sb.append("obj.appendChild(param);");
}
}
sb.append("document.getElementById('appletDiv').appendChild(obj);");
JavaScript.getCurrent().execute(sb.toString());
}
}
and i Call it in the page. The applet is seen correctly but i must to return a value using the method
vaadinUpdateVariable("docName", docName + SIGNED_FILE_SUFFIX, true);
How can i resolve my problem?
you might have have run into one of two Maven GWT plugin bugs: [MGWT-147][1] or [MGWT-148][2] just like [Henri Sara][3] said .
i recommended this blog for you : Vaadin addons and maven and eclipse.
please read this also : Using Vaadin with Maven 2
to help you getting your add-on work . if still n't fixed i refer using [Embedded][6] ui component and avoid the hard coding html tag's.
i wish if i helped you if n't i'm sorry that all i know about Vaadin+applets.
1# jira.codehaus(.)org/browse/MGWT-147
2#jira.codehaus(.)org/browse/MGWT-148
3#vaadin(.)com/c/my_sites/view?groupId=13199&privateLayout=0
4# vaadin(.)com/download/prerelease/7.0/7.0.0/7.0.0.rc2/docs/api/com/vaadin/ui/Embedded.html
I am using jasper plugin to generate my report. All is fine but except my pdf is opening on the current tab, when I want to open it in a new tab.
I have no idea how to do it. Can anybody please help me on this please?
I am using "i-report" to design my pdf. Here is my code below :
def index = {
println(params)
def testModel = this.getProperties().containsKey('chainModel') ?
chainModel : null
JasperReportDef report = null
if (params.containsKey('auto_print_dialog')){
report = docuJasperService.buildReportDefinition(params,
request.getLocale(), testModel)
}
else{
report = jasperService.buildReportDefinition(params,
request.getLocale(), testModel)
}
generateResponse(report)
}
def generateResponse = {reportDef ->
if (!reportDef.fileFormat.inline && !reportDef.parameters._inline) {
//response.characterEncoding = "UTF-8"
//response.setHeader("Content-disposition",
//"inline; filename=${params._name}");
response.setHeader("Content-disposition", "inline;
filename="+(reportDef.parameters._name ?: reportDef.name) +
"."+reportDef.fileFormat.extension);
response.contentType = "application/pdf"
response.outputStream << reportDef.contentStream.toByteArray()
} else {
render(text: reportDef.contentStream, contentType:
reportDef.fileFormat.mimeTyp,
encoding: reportDef.parameters.encoding ?
reportDef.parameters.encoding : 'UTF-8');
}
}
This is going to be handled by the link you use to generate the report. Typically adding a target of _blank will do the trick. For example:
<g:link controller="myReports" action="whateverReport" target="_blank">Click for your report</g:link>
This will open the link in a new tab.
If you are using a form adding target to the form will submit the form to a new tab. For example:
<form name="myForm" action="whateverReport" method="POST" target="_blank">
or
<g:form name="myForm" controller="myReports" action="whateverReport" target="_blank">
You could even do so with javascript window.open if you needed, but I will leave that example out of this answer as it's well documented elsewhere.
I'm having a problem similar to jQuery $.ajax Not Working in IE8 but it works on FireFox & Chrome, but with a different use case.
I'm using the jQuery Form plug-in to handle a file upload to an ASP.NET MVC controller, which sends the file off for parsing and processing. If an Exception is thrown, it should alert the user to the issue.
//client side code
//make an ajax call, sending the contents of the file
$("#ajaxUploadForm").ajaxSubmit({
dataType: 'json',
url: '/plan/Something/ExcelImport',
iframe: true,
beforeSend: function () {
$(".ui-dialog-buttonpane").find("#my_progress").fadeIn();
},
success: function (data, textStatus) {
output = "<center><span class='flash'>" + data.message + "</span></center>";
$("#flash_message").html(output).fadeIn('slow');
setTimeout(function () { $("#flash_message").fadeOut() }, 5000);
cleanup();
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("XMLHttpRequest is " + XMLHttpRequest);
var contents = "";
for (prop in XMLHttpRequest) {
contents += "\na property is " + prop + " it's value is " + XMLHttpRequest[prop];
}
alert("the contents are " + contents);
alert("textStatus is " + textStatus);
alert("errorThrown is " + errorThrown);
//comes back in an HTML envelope. This should be parsed with regex, but I can't get it to work. Dirty hack
response = XMLHttpRequest.responseText.substring(XMLHttpRequest.responseText.indexOf("<body>"));
response = response.replace("<body>", "");
response = response.replace("</body>", "");
alert("There was a problem with the upload.\r\n" + response);
},
complete: function (XMLHttpRequest, textStatus) {
$(".ui-dialog-buttonpane").find("#my_progress").remove();
something_import.dialog('close');
something_import.dialog('destroy');
}
});
//server side code
public FileUploadJsonResult ExcelImport()
{
FileUploadJsonResult result = new FileUploadJsonResult();
HttpPostedFileBase hpf = Request.Files[0] as HttpPostedFileBase;
if (hpf.ContentLength == 0)
return new FileUploadJsonResult { Data = new { message = "File contained no data" } };
String fileName = Path.GetFileName(hpf.FileName);
String timeStampedFile = fileName.Insert(fileName.IndexOf('.'),"_"+DateTime.Now.ToFileTimeUtc());
string savedFileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "tempo", timeStampedFile);
hpf.SaveAs(savedFileName);
try
{
result = ProcessFile(savedFileName, Request["Id"]) as FileUploadJsonResult;
}
catch (ArgumentException e)
{
this.Response.StatusCode = 500;
this.Response.StatusDescription = System.Net.HttpStatusCode.BadRequest.ToString();
Response.Write(e.Message);
result = Json(new { message = e.Message, stackTrace = e.StackTrace }) as FileUploadJsonResult;
}
return result;
}
This works perfectly in Chrome and Firefox. In IE, the XMLHttpRequest object coming back is different:
FF:
IE:
I've been Googling around for differences between the browser implementations of XMLHttpRequest, but haven't found anything that deals specifically with this case. Stymied.
The reason this is happening is because of the iframe fallback strategy that ajaxSubmit employs. I think since the response gets posted into the iframe IE tries to figure out how to dipslay it and decides that it wants to ask you to download the response instead of just putting it in the iframe.
I came across this same situation a while ago and found an article (that I can't find now) that offered a workaround.
If you surround your json response in a textarea nobody is going to complain(IE,FF,Chrome,probably Safari) and you'll get your response parsed correctly.
E.g. if you are returning
{Id: 1, Name: 'Me'}
just return:
<textarea>{Id: 1, Name: 'Me'}</textarea>
You see now IE thinks it's html so it inserts it into the hidden iframe. Your ajaxSubmit function still gets called and parses the json correctly and then everybody's happy. :)
If you're using ASP.NET MVC you could shamelessly copy this extension method :)
public static class ControllerExtensions
{
public static ActionResult JsonSafe(this IController controller, object obj)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
return new WriteResult(string.Format("<textarea>{0}</textarea>", serializer.Serialize(obj)));
}
}
The wikipedia article on XMLHttpRequest seems to give a good overview of the history behind the XMLHttpRequest. It seems Microsoft and Mozilla developed/adopted their own versions of the object and hence why you are probably seeing different properties.
Here is a link to Microsoft's implementation of the XMLHttpRequest interface members, which seem to match the properties in your alert.
Here is the a link to Mozilla's implementation of XMLHttpRequest.
So while we wait for the W3C to standardize the XMLHttpRequest you will continue to have different implementations across the browsers like you are seeing in this case.
For some added fun here is Apple's and Opera's specifications on XMLHttpRequest.
I have a site that need to get some data from a different sit that is using asp.net MVC/
The data to get loaded is from these pages:
http://charity.hondaclassic.com/home/totaldonations
http://charity.hondaclassic.com/Home/CharityList
This should be a no brainer but for some reason I get an empty response, here is my JS:
<script>
jQuery.noConflict();
jQuery(document).ready(function($){
$('.totalDonations').load('http://charity.hondaclassic.com/home/totaldonations');
$('#charityList').load('http://charity.hondaclassic.com/home/CharityList');
});
</script>
in firebug I see the request is made and come back with a response of 200 OK but the response is empty, if you browse to these pages they work fine! What the heck?
Here are the controller actions from the MVC site:
public ActionResult TotalDonations() {
var total = "$" + repo.All<Customer>().Sum(x => x.AmountPaid).ToString();
return Content(total);
}
public ActionResult CharityList() {
var charities = repo.All<Company>();
return View(charities);
}
Someone please out what stupid little thing I am missing - this should have taken me 5 minutes and it's been hours!
The same origin policy prevents loading HTML from another web site via AJAX. The right way to do this would be to have the methods detect if the request is coming from AJAX and return JSONP instead.
public ActionResult TotalDonations( string callback )
{
var total = "$" + repo.All<Customer>().Sum(x => x.AmountPaid).ToString();
if (!string.IsNullOrEmpty(callback))
{
return Content( callback + "( { total: " + total + " } );" );
}
else
{
return Content(total);
}
}
...
$.getJSON('http://charity.hondaclassic.com/home/totaldonations?callback=?',
function(data) {
$('.totalDonations').html( data.total );
});
your totaldonations link is missing the o in total
> $('.totalDonations').load('http://charity.hondaclassic.com/home/ttaldonations');
should be
$('.totalDonations').load('http://charity.hondaclassic.com/home/totaldonations');
I ended up just doing it server side to avoid the same origin policy mentioned above:
Dim totalDonations As String
Dim charities As String
Using Client As New System.Net.WebClient()
totalDonations = Client.DownloadString("http://charity.hondaclassic.com/home/totaldonations")
charities = Client.DownloadString("http://charity.hondaclassic.com/home/CharityList")
End Using
worked like a charm.