Convert panel HTML to PDF using C# ASP.NET - c#

I have a basic form with mostly textboxes and a few checkboxes and radio buttons. Pretty much when a user fills it out and hits submit, I need it to convert and display a PDF with the same structure and offer a print option. I have searched online and I have tried most of the options but nothing works.
I don't expect this to be too difficult, but I am fairly new to C# and can't figure out how to make an HTML panel into a PDF and print it. Any help would be appreciated, thanks in advance!
Here is the HTML for one of the labels and textboxes and the submit button:
<div>
<asp:Label ID="lblDate" runat="server" Text="Date:"></asp:Label>
<asp:TextBox ID="txtDate" runat="server"></asp:TextBox>
</div>
<asp:Button ID="SubmitButton" runat="server" Text="Button" OnClick="btnSubmit"/>
Once clicked, the .cs page will go through this:
litDate.Text = "Date: " + txtDate.Text + "<br />";
and update the panel to display the value:
<asp:Panel ID="PDFPanel" runat="server" Visible="false">
<asp:Literal ID="litDate" runat="server"></asp:Literal>
</asp:Panel>
I am not sure if the panel is needed, but this is how I was able to be sure I was getting the value back. Is there a way to go straight from submit to PDF and print?

Use something like http://code.google.com/p/wkhtmltopdf/
This roughly outlines how to do it: https://stackoverflow.com/a/18767473/181771

I made an asp.net website demo taking the contents of a panel or div and generating a pdf from the html. This is using NReco.PdfGenerator (another wkhtmltopdf wrapper):
https://github.com/jay8anks/Asp.net-HtmlToPdf_NReco.PdfGenerator
Yeah, it's a webform, but anyone sharp enough to do mvc should be able to adapt it fairly easily.
Basically, it is using javascript to get the html between a panel (div) tag and store it in a hiddenfield. Pretty straight forward, except if you want to have css or images, you can't use a relative url for them. I actually just embedded the css inline as a string, but there are other ways of doing it.
Then in the codebehind, this gets the html and generates a pdf from it:
protected void SaveHtmlToPdf()
{
string htmlOutput = Server.UrlDecode(HiddenField1.Value);
htmlOutput = string.Join(" ", System.Text.RegularExpressions.Regex.Split(htmlOutput, #"(?:\r\n|\n|\r|\t)"));
htmlOutput = htmlOutput.Replace("\"", "'");
string headerStyle = HeaderStyle();
string finalHtml = headerStyle + htmlOutput;
var strWr = new StringWriter();
var htmlWr = new HtmlTextWriter(strWr);
// base.Render(htmlWr);
var htmlToPdf = new HtmlToPdfConverter();
string filename = (orderId + ".pdf");
string filepath = "~/sales_pdfs";
string combinedFilePath = Path.Combine(Server.MapPath(filepath), filename).ToString();
for (int i = 1; i <= NumberOfRetries; ++i)
{
try
{
htmlToPdf.GeneratePdf(finalHtml, null, combinedFilePath);
break; // When done we can break loop
}
catch (IOException e)
{
// You may check error code to filter some exceptions, not every error
// can be recovered.
if (i <= NumberOfRetries)
{
Thread.Sleep(DelayOnRetry);
}
ltMsg.Text = "There was a problem creating the PDF";
}
}
}
This puts a pdf in a directory so it can be downloaded, but there are other ways that could be handled, as well. We actually wanted a copy of the PDF that someone was generating, so this was the direction we went in.

Related

Replace part of a asp label value without replacing entire content in the label

I'm passing some HTML codes as value to a asp:Label which contains div with unique ids and class names and inline JavaScript. I want to make changed or add extra div inside the label by replacing any particular character in the label string. How can I get this done?
Lets say I have the below HTML code as the value for the asp Label with ID lblcode, in the HTML code I have 3 div with content1, 2 and 3 inside a div lvl1container. I want to add a content 4 with HTML div tags by replacing the ++ADD_MORE++ with <div id=\"lvl1_4>content4</div>++ADD_MORE++.
Client side:
<asp:Label ID="lblcode" runat="server"></asp:Label>
<asp:TextBox ID="txtappend" runat="server"></asp:TextBox>
<asp:Button ID="btnappend" runat="server" Text="Append"/>
Server side:
string code = "<div id=\"lvl1container\">"+
"<div id=\"lvl1_1\">content1</div>"+
"<div id=\"lvl1_2\">content2</div>"+
"<div id=\"lvl1_3\">content3</div>"+
"++ADD_MORE++"+
"</div>";
lblcode.Text = code;
So instead of replacing the entire content of the label I want to search only for ++ADD_MORE++ and replace it with the value given inside the asp textbox txtappend. How can I get this done? thanks in advance.
In the append button click, try the below code
protected void btnappend_Click(object sender, EventArgs e)
{
System.Text.StringBuilder sb = new StringBuilder();
sb.Append(lblcode.Text);
sb.Replace("++ADD_MORE++", $"<div>{txtappend.Text}</div>");
sb.Append("++ADD_MORE++");
lblcode.Text = sb.ToString();
}

Text cut in text area in ASP.net page

i'm trying to load text from database into many text fields
every thing is Ok , but one field of them text lenght is more than the length of the text field
so not all the text appear on the screen
that is my ASP.net code
<asp:TextBox ID="descriptiont" runat="server" Rows="3" Width="300px" Height="100px" Wrap="true">
and that is the code behind of it
descriptiont.Text = s.GetValue(1).ToString();
descriptiont.Enabled = false;
and that is what i get in the web page
the orginal text is "ECASTI (Egyptian Center for the Advancement of Science, Technology, and Innovation) "
can any one help ??!!!
use this:
<asp:TextBox id="TextArea1" TextMode="multiline" Columns="50" Rows="5" runat="server" />
Then you can access the content via:
string message= TextArea1.Text;
Dont fix the height of textbox. Height should be auto.And in css add property for textbox. It will work.
word-wrap: break-word;
Try this :
string s = "Your Text Field";
if (s.Length > 20)
{
//Change Width="450px"
}
Update :
You can aslo change width in CSS when text length is more than the length of the field.
Update 2 :
You can resize the textbox in C# with the following codes :
if (s.Length>20)
{
textBox1.TextChanged += textBox1_TextChanged;
}
void textBox1_TextChanged(object sender, EventArgs e)
{
Size size = TextRenderer.MeasureText(textBox1.Text, textBox1.Font);
textBox1.Width = size.Width;
}
Without changing the length of the textbox, may be it will mess up your design, add a textbox tool tip with the same content. So when you hover on textbox it will display the full content.
descriptiont.Text = s.GetValue(1).ToString();
descriptiont.Title = s.GetValue(1).ToString();
descriptiont.Enabled = false;
there is property of textbox named "TextMode". Please add 'TextMode="multiline"'
in your view or you can add it from your code behind file also.

Cut Text to fit Textbox width and then right align

I have several Textboxes in my Form which display filepaths. Mostly the filepaths are too long to display in the textbox. Is there a possibility to cut the surplus text and append some point characters to it and then align it right?
For example:
If the path is C:\Programs\anotherfolder\blabla\thisisatest.xml
A Textbox should show: ...lder\blabla\thisisatest.xml
If I resize the textbox, the text in it shall resize/expand with it.
Is there a way to do this automatically, maybe via Resize event of a textbox.
Thank you very much.
This might help if you are looking for resizing your textbox based on the text entered. You can call this code on any event like when you move focus out of textbox or after the data is loaded in the textbox. You need to replace your textbox's actual text in below line in the code.
mySize = e.Graphics.MeasureString("This is a test", myFont);
if this is a webpage ..
include 2 hidden variables as following
<div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:HiddenField ID="HiddenField1" runat="server" />
<asp:HiddenField ID="HiddenField2" runat="server" />
</div>
include jquery and the script as following
<script type="text/javascript">
$(document).ready(function () {
$('#TextBox1').focus(function () {
$('#TextBox1').val($('#HiddenField1').val());
});
$('#TextBox1').blur(function () {
$('#TextBox1').val($('#HiddenField2').val());
});
});
</script>
set the fields in the code behind
string str = #"C:\Programs\anotherfolder\blabla\thisisatest.xml";
HiddenField1.Value = str;
if (str.Length > 10)
{
TextBox1.Text = "..." + str.Substring(str.Length - 10, 10);
HiddenField2.Value = TextBox1.Text;
}
This will show the whole string only when focused on the textbox.
Here is a demo of how it will look like.
Let me know if this was helpful or if you have any queries
Use this code to remove surplus text:
private string GetShortText(string longText)
{
int validTextSize = 27;
if (longText.Length <= validTextSize)
return longText;
return "..."+longText.Substring(longText.Length - validTextSize);
}
And use above code like this:
string longText = #"C:\Programs\anotherfolder\blabla\thisisatest.xml";
txtPath.Text=GetShortText(longText);
An for change alignment, if your form is a Windows Form you can use this code:
txtPath.TextAlign = HorizontalAlignment.Right;
Or if your form is a WPF form use this code:
txtPath.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;

Using HTML5 file (Multiple) control in asp.net

I am looking for a way to perfectly manage the <input type="file" multiple="multiple"> tag of HTML 5 in my asp.net 3.5 project.
I have done it before with a single control on page, but what if we have multiple upload controls on the same page. Please see my code:
protected void btnSave_Click(object sender, EventArgs e)
{
//---------Need to check if my upload control has files: Please suggest a perfect way
if (fupAttachment.PostedFile != null || fupAttachment.PostedFile.FileName != "" || fupAttachment.PostedFile.ContentLength>0)//here is a problem, as it does not checks for a blank file upload control
HttpFileCollection hfc = Request.Files;
string strDirectory = Server.MapPath("~/") + "Mailer/" + hidCampID.Value;
if (hfc.Count>0)
{
if (!System.IO.Directory.Exists(strDirectory))
{
System.IO.Directory.CreateDirectory(strDirectory);
}
if (System.IO.Directory.Exists(strDirectory))
{
for (int i = 0; i < hfc.Count - 1; i++)
{
hfc[i].SaveAs(strDirectory + "/" + hfc[i].FileName.Replace(" ", "_"));
}
}
}
}
}
My asp page is something like this:
//----this control is from which I want to multiple upload files
<input type="file" multiple="multiple" runat="server" id="fupAttachment" />
// Another upload control is there which takes input when page loads
<asp:FileUpload ID="fupMailingList" runat="server" />
So, exactly my problem is that when page loads "fupMailingList" has taken a file, and then when I want to use my multiple upload control "fupAttachment", I am unable to check if it has any files or not, as hfc checks for all upload controls and it gets file in one of them. So, please tell me a way to check only "fupAttachment" control and then do my work correctly.
Rather than iterating over all the files in the request, you should check on a per input basis.
var uploadedFiles = Request.Files.GetMultiple("fupAttachment");
if(uploadedFiles.Count > 0)
{
//
}
Just check the HasFile property.
if(fupMailingList.HasFile){
//Do something
}

How to set focus at the end of textbox while typing?

I have a textbox with a live search function. It is working all good except one problem. If I type any characters on it, it just loses its focus. If I set textbox.Focus(), the cursor goes at the beginning of the textbox.
I have tried most of solutions on the internet. Please check my codes below.
asp:TextBox ID="searchCompany" runat="server" Text="" CssClass="searchCompany" AutoPostBack="true" Width="190px" OnTextChanged="searchCompany_TextChanged"></asp:TextBox>
In page_Load
protected void Page_Load(object sender, EventArgs e)
{
//ScriptManager1.RegisterAsyncPostBackControl(Menu1);
menuDisplay();
searchCompany.Attributes.Add("onkeyup", "setTimeout('__doPostBack(\\'" + searchCompany.UniqueID + "\\',\\'\\')', 0);");
//searchCompany.Attributes.Add("onfocus", "javascript:setSelectionRange('" + "','')");
//searchCompany.Focus();
}
and I have tried javascript as below
<script type="text/javascript">
function setSelectionRange() {
var inputField = document.getElementById('searchCompany');
if (inputField != null && inputField.value.length > 0) {
if (inputField.createTextRange) {
var FieldRange = inputField.createTextRange();
FieldRange.moveStart('character',inputField.value.length);
FieldRange.collapse();
FieldRange.select();
}
}
}
</script>
I have tried to put codes on a method "searchCompany_TextChanged" which is calling if user type any characters on a textbox everytime however it is not working as well.
I saw other solutions with using Textbox.Select() but System.Windows.Control is not working in asp.net i guess.
Any idea??
There's a very simple trick that's worked for me. Basically, set the text value of the of input to itself to its own text value, and that will move the cursor to the end of the text. Then just focus it. This code uses jQuery to demonstrate that, but you should be able to do that in straight JS as well.
HTML
<input type="text" id="focusText"></input>
<button id="focusButton">Set Focus</button>
JavaScript
$("#focusButton").click(function() {
var text = $("#focusText").val();
$("#focusText").val(text).focus();
})
Here's a non jQuery example of the JavaScript, HTML should be the same:
document.getElementById("focusButton").onclick = function() {
var inputElement = document.getElementById("focusText");
var text = inputElement.value;
inputElement.value = text;
inputElement.focus();
}
Here's a fiddle demonstrating the non-jQuery version of the code: http://jsfiddle.net/C3gCa/

Categories

Resources