Removing a "Print" button Before Rendering PDF from View - MVC3 - c#

I have a view that I pass to Rotativa (wkhtmltopdf) to get a PDF version of the view for users to print, once they click the "print button":
Here is the rendered view that will be converted to PDF if the user clicks the "print" button
Here is the button code from the view
<div id="print-pdf" align="center">
<a id="print-me" class = "print-btn"
href='#Url.Action("PrintMyView", "Report",
new { id = Model.MonthlyReportID,
clubKeyNo = Model.ClubKeyNumber,
month = Model.ReportMonth,
year = Model.ReportYear }, null)'>Print Report</a>
</div>
Common sense tells me that I need to remove the button before the PDF is generated from the view, so users don't get a PDF with a button on it:
I tried hiding the button (.hide()) and also removing it (.remove())
but the PDF is still rendering with the button:
<script type="text/javascript">
$(document).ready(function () {
$('#print-me').show();
$('#print-pdf').click(function () {
$('#print-me').hide();
});
});
</script>
Anything else that I could try here?
Thanks!

You can do a version for PDF so you can handled what and what no should be printed
what are running in javascript does not work because then executed when the doom is ready, but the Rotativa will not execute any javascript
so, you render just what you need
#if (Model.mustPrint){
<div id="print-pdf" align="center">
<a id="print-me" class = "print-btn" href='#Url.Action("PrintMyView", "Report",
new
{
id = Model.MonthlyReportID,
clubKeyNo = Model.ClubKeyNumber,
month = Model.ReportMonth,
year = Model.ReportYear
}, null)'>Print Report</a>
</div>
}

Try this css:
#media print
{
#print-me
{
display:none;
}
}
ref

Rotativa does not render as print media, but as a browser, you must force rendering as print.
Send the "--print-media-type" argument
Doing this you can use css to hide if the media for print
#media print {
.noprint {
display: none! important
}}
Ex:
return new ViewAsPdf("Details", obj)
{
CustomSwitches = "--print-media-type"
}
Complete example:
return new ViewAsPdf("Details", obj)
{
CustomSwitches = "--print-media-type",
FileName = your_name_report.pdf",
PageOrientation = Orientation.Portrait,
PageSize = Size.A4,
PageMargins = new Margins(0, 0, 0, 0),
PageWidth = 210,
PageHeight = 297
};

Related

Issue in opening pop-up window by clicking button multiple times in MVC4?

Hi i got issue in opening pop-up window multiple times while clicking button. I will explain my issue clearly.
Hi, this is my parent view Customer Form.I have one add button near to Area if i enter the CustomerName AddressType, Street, Location,Place and then select the area.Suppose if area is not in the list means i have to add that. so i click that add button it will open AreaPartial view as popup window.
After i enter the details and click the create button it will save the data in db and it shows the same popup window when it was close means when i click x mark[which is in the pop up window right top corner ) . Now all are working fine.
Now my issue is i open the pop-up window by clicking the button and add the area and close the pop-up window before clicking the main save button in parent view i have to add another one area so i click the add button again but it wont opening the pop-up window . This is my issue.
My Controller code to save the data which is entered in the partial view pop-up window
public ActionResult AreaPartialView()
{
ViewBag.CityID = new SelectList(db.Cities, "CityID", "DisplayName");
return View("AreaPartialView");
}
[HttpPost]
public ActionResult AddAreaInfo(CustomerViewModel objareaVM)
{
var objAreaID = Guid.NewGuid();
ViewBag.CityID = new SelectList(db.Cities, "CityID", "DisplayName", objareaVM.CityID);
var ObjArea = new Area()
{
AreaID =objAreaID,
DisplayName = objareaVM.Area,
PrintName = objareaVM.Area,
CityID = objareaVM.CityID,
IsActive = true,
IsDeleted = false,
CreatedDate = DateTime.Now,
EditedDate = DateTime.Now,
LastActiveOn = DateTime.Now,
RowID = Guid.NewGuid(),
CreatedSessionID = Guid.NewGuid(),
EditedSessionID = Guid.NewGuid(),
OfflineMode = false,
OfflineID = Guid.NewGuid()
};
db.Areas.Add(ObjArea);
db.SaveChanges();
ModelState.Clear();
return Json(objAreaID);
}
My j-query code to display the area partial view as popup window once the add button is clicked in Parent View
<script src="~/Scripts/jquery-1.10.2-ui.js"></script>
<link rel="stylesheet"href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" />
<script type="text/javascript">
$("#AddArea").click(function () {
$('#AddAreaNew').dialog("open");
});
$(function () {
$('#AddAreaNew').dialog({
autoOpen: false,
width: 400,
height: 500,
resizable: false,
title: 'Add Area',
modal: true,
open: function (event, ui) {
$(this).load("#Url.Action("AreaPartialView", "Customer")");
},
buttons: {
"Close": function () {
$(this).dialog("close");
}
}
});
});
My Partial View code
#Html.Label("Area" , new { #class = "control-label" })
#Html.TextBoxFor(model => model.Area, new { #class = "form-control", type = "text" ,id ="AreaName"})
#Html.ValidationMessageFor(model => model.Area)
#Html.Label("City")
#Html.DropDownList("CityID", null, "Select", new { #class = "form-control " })
<script src="~/Scripts/jquery-1.10.4-ui.min.js"></script>
<link href="~/Content/jquery-ui-1.10.4.custom.min.css" rel="stylesheet" />
<script src="~/Scripts/jquery-ui-1.8.24.min.js"></script>
<script type="text/javascript">
function SaveArea() {
debugger;
var Area = $("#AreaName").val();
var CityID = $("#CityID").val();
alert(Area);
var AreaAdd = { "Area": '' +Area + '', "CityID": CityID };
$.post("/Customer/AddAreaInfo", AreaAdd, function(data) {
var option = new Option(Area, data);
$('#AreaID').append($(option));
alert("sucess");
window.close();
});
}
This is my issue i cant able to open my pop-up window multiple times.i tried my level best to explain my issue. please any one help me to solve this issue.
Advance thanks..
Perhaps something like this would help you, as a brief example.
<style>
.floatingbox
{
z-index:99999;
position:absolute;
/* and more of your styling here, the main point is to make to appear above any other element on the page */
}
</style>
<div class="floatingbox" id="inputbox">
</div>
EDIT: <input type="button" value="Add Field" onclick="WhenIGetClicked(this)"/>
function WhenIGetClicked(e)
{
RefershContent();
document.getElementbyId('input').style.left = e.style.left;
document.getElementbyId('input').style.top = e.style.top; // show div at position of button but you can change it to where-ever
}
function RefreshContent()
{
// put your html in here for the different fields you'll need in the div
document.getElementbyId('inputbox').innerHTML = '';
// add the rest of your html mark up but make it as a function so it can be 'refreshed' and look like a new blank form each time, i found this easier than making a partial view and having to deal with loading it into the div/messing with javascript inside the partial view but may be personal preference :)
}
function OnSaveClick()
{
var SomeValueYouWantToPass = document.getElementbyId('inputboxinsidethediv').value; // or innerHTML works sometimes too if it's not getting the value correctly
$.ajax({
type:post,
url: '/MyController/ActionName',
dataType: 'json',
data: { MyVariableOnTheControllerSide: SomeValueYouWantToPass },
success: function()
{
alert('hey it worked!'); // or refresh the page to load the new field, etc
}
)}
}
</script>
On the controller side now:
public JsonResult UpdateField(string MyVariableOnTheControllerSide)
{
//do something with the data.
return Json('Hey it worked!', JsonRequestBehavior.AllowGet);
}
If you'd like to pass it as a class since that's how you have it set up on your controller, you'll have to create the class as a Json object on the HTML markup side of it when grabbing the values (heck you could even do a for loop of the controls in the div and dynamically grab the values instead of reaching out to each element to get it's value). Very basic run down of how I usually do pop ups. Let me know if you need clarification or if I missed your point :)

MvcReportViewer export to PDF only first page

I have MvcReportViewer component, which I use for reports.
In new version of MvcReportViewer js printReport is like this:
function printReport() {
$find('ReportViewer').exportReport('PDF');
}
Is there a possibility to export PDF only first page ?
I created seperate report (which has subreport of the first page) made changes in MvcReportViewer.js:
function printReport() {
if ($('.printOtherUrl').length > 0) {
window.open($('.printOtherUrl').val(), '_blank');
} else {
$find('ReportViewer').exportReport('PDF');
}
}
In a View that i show my #Html.MvcReportViewer:
When iframe is loaded (i have 500ms setTimeout for height and width too, then i add this input):
$("<input type='hidden' class='printOtherUrl'>").val('#Url.Action(Mvc.Reports.GetDailyReportFirstPage())').appendTo($this.contents().find('body'));
And made ie print button hidden per ShowPrintButton = false of ControlSettings
And my controller action is :
public virtual ActionResult GetDailyReportFirstPage()
{
return this.Report(
ReportFormat.Excel,
SiteReports.DailySummaryMainReport,
new { genDate = Clock.Now() });
}

Is there a way to make an Iframe expandable as needed?

Is there a way to make an Iframe expandable as needed? I have a web page with an Iframe to a second web page on a same server. The second web page has an expandable table. What I would like is when someone views the second page throught the Iframe and clicks on the table to expand, the Iframe will also expand to fit the size.
<script type="text/javascript">
//<![CDATA[
window.onload = function() {
var f = document.getElementById("mainframe");
function resize() {
var h = "";
var w = "";
if (f.contentDocument) {
h = f.contentDocument.documentElement.offsetHeight + 20 + "px";
(f.contentDocument.documentElement,"").getProperty Value
("width");
} else if (f.contentWindow) {
h = f.contentWindow.document.body.scrollHeight + 5 + "px";
} else {
return;
}
f.setAttribute("height",h);
f.parentNode.setAttribute("height",h);
}
if (window.addEventListener) {
f.onload = resize;
} else if (f.attachEvent) {
f.attachEvent("onload", resize);
} else {
return;
}
resize();
}
//]]>
</script>
<iframe name="frm" id="mainframe" src="URL HERE" frameborder="0" allowtransparency="no" scrolling="no" target="_self" height="150"></iframe>
And here's the HTML code:
Name Of Page
If the page is in same domain in that case following solution should work.
Make iframe automatically adjust height according to the contents without using scrollbar?

Need to make selected text as bold/italic/underline using javascript, and also save & retrieve the same using c#

I need to make selected text of textbox bold/italic/underline using javascript. For that i am using the following code.
<img src="~/images/Bold" alt="Bold" onclick="changeFont('TextBox1','b');" />
<img src="~/images/Italic" alt="Italic" onclick="changeFont('TextBox1','i');" />
<img src="~/images/Underline" alt="Underline" onclick="changeFont('TextBox1','u');" />
<script type="text/javascript" language="javascript">
function changeFont(txt, change) {
if (change == 'b') {
if (document.getElementById(txt).style.fontWeight == 'bold')
document.getElementById(txt).style.fontWeight = 'normal';
else
document.getElementById(txt).style.fontWeight = 'bold';
}
else if (change == 'i') {
if (document.getElementById(txt).style.fontStyle == 'italic')
document.getElementById(txt).style.fontStyle = 'normal';
else
document.getElementById(txt).style.fontStyle = 'italic';
}
else {
if (document.getElementById(txt).style.textDecoration == 'underline')
document.getElementById(txt).style.textDecoration = 'none';
else
document.getElementById(txt).style.textDecoration = 'underline';
}
}
</script>
But the issue here is, when i click on bold image its making the whole text into bold but not the selected text. It´s not working for the other two images either.
While saving the text of textbox I am unable to get the text including html tags even after trying with
document.getElementById('TextBox1').innerHTML;
I am able to get only the value of textbox.
Is there any way to save and retrieve the same using javascript or C#
Thanks in advance
SC
Here is a question that answers your problem about getting the highlighting text
How to get selected text in textarea?
About making the selected text bold you would need to use html tags or something like bbcode and parse it to html when you print it on to a page.
EDIT: Here is a page that shows the jquery plugin "fieldselection" in action.
EDIT 2: Here is an example of how I would've done this: jsfiddle link
The HTML:
<input id="bold" type="button" value="B" />
<br />
<textarea id="editor"></textarea>
<div id="resultAsHtml"></div>
<br />
<div id="resultAsText"></div>
The javascript (jquery) code:
$(document).ready(function() {
$("#editor").keyup(Update);
function Update(){
var text = $(this).val();
var result = ParseToHtml(text);
$("#resultAsHtml").html(result);
$("#resultAsText").text(result);
}
$("#bold").click(function(){
var range = $("#editor").getSelection();
var textToReplaceWith = "[b]"+ range.text + "[/b]";
$("#editor").replaceSelection(textToReplaceWith , true);
var text = $("#editor").val();
var result = ParseToHtml(text);
$("#resultAsHtml").html(result);
$("#resultAsText").text(result);
});
function ParseToHtml(text) {
text = text.replace("[b]", "<b>");
text = text.replace("[/b]", "</b>");
text = text.replace(" "," ");
text = text.replace("\n","</br>");
return text;
}
$("#bold").replaceSelection("[b]" + $("#editor").getSelection() + "[/b]", true);
});
document.execCommand("bold", false, null);
this is Simplest techinique which worked for me
in all browsers ...

ASP C# | MessageBox Keeps Displaying

I have a JavaScript MessageBox that keeps displaying when I click events in a Repeater or refresh the current page.
Here is the function:
public myFunctions()
{
}
/** Display Successs/Error Message **/
public void DisplayUserMessage(string messageType, string messageString, Label ErrorMessageLabel)
{
ErrorMessageLabel.Visible = true;
ErrorMessageLabel.Text = "<b>" + messageType.Substring(0, 1).ToUpper() + messageType.Substring(1).ToLower() + ":</b> " + messageString;
ErrorMessageLabel.CssClass = messageType.ToLower() + "_message";
}
public void HideUserMessage(Label ErrorMessageLabel)
{
ErrorMessageLabel.Visible = false;
ErrorMessageLabel.Text = "";
ErrorMessageLabel.CssClass = "";
}
Here is the jquery to make it fade out:
$(document).ready(function () {
/** Success/Error Messages **/
$('.success_message').animate({ opacity: 1.0 }, 2000).fadeOut('slow');
$('.error_message').animate({ opacity: 1.0 }, 2000).fadeOut('slow');
});
Here it is on the MasterPage:
<!-- Message Box -->
<div id="msgBox" runat="server">
<asp:Label ID="ErrorMessageLabel" CssClass="" runat="server" Visible="false"></asp:Label>
</div>
Here is the script in the code-behind when a success occurs:
Label ErrorMessageLabel = (Label)Master.FindControl("ErrorMessageLabel");
new myFunctions().DisplayUserMessage("success", "Administrator Updated!", ErrorMessageLabel);
Anyone know how I can stop it from continually showing up after I click another button or refresh the page?
Use a hidden input and set the value when success function is called. All the other times reset the value. In your document ready function check the value of the hidden element and then call the animate function.
<input id="txtHidSuccess" type="hidden" runat="server" />
In page load
txtHidSuccess.Value = "0";
In the success/error function
txtHidSuccess.Value = "1";
jQuery
$(function(){
if ($("#txtHidSuccess").val() === "1") {
/** Success/Error Messages **/
$('.success_message').animate({ opacity: 1.0 }, 2000).fadeOut('slow');
$('.error_message').animate({ opacity: 1.0 }, 2000).fadeOut('slow');
}
});
I see where you're calling DisplayUserMessage(), but not HideUserMessage(). My guess is that when you set the ErrorMessageLabel properties, they're stored in the View State persisted across postbacks.
Rather than use an ASP.NET Label control, you could try just wrapping some text with a regular div and use CSS to hide it. When the success event occurs in your app, you can use ClientScriptManager.RegisterStartupScript() to write a script to the client that shows the div. Then, your animate functions can fade out the div if it's visible.
if(IsPostBack)
new myFunctions().HideUserMessage(ErrorMessageLabel);
This worked. Thanks #Harie

Categories