RTF to HTML, change font-family - c#

I have some RTF text from my C# application which I convert to HTML and then send to my PHP file.
Problem is; all my text in PHP is in Arial, The output of my RTF is Tahoma. Any ideas how I can change the font-family?
This is my code so far:
string memoValue = inboundSet.Fields["MEMO"].Value.ToString();
if (RtfTags.IsRtfContent(memoValue))
{
using (RichEditDocumentServer richServer = new RichEditDocumentServer())
{
string htmlText = string.Empty;
richServer.RtfText = memoValue;
htmlText = richServer.HtmlText;
callDetail.Memo = htmlText;
}
}
else
{
callDetail.Memo = memoValue;
}
In my PHP file I get the value in this way:
echo "<td>Memo:</td><td>".$value->Memo."</td>";
I also tried it in this way:
echo "<td>Memo:</td><td class='fonttest'>".$value->Memo."</td>";
And in my CSS:
.fonttest
{
font-size:12px;
font-family:Arial;
}
My text keeps looking like this:
This is what my RTF text looks like:

I solved my issue by this way:
string memoValue = inboundSet.Fields["MEMO"].Value.ToString();
if (RtfTags.IsRtfContent(memoValue))
{
using (RichEditDocumentServer richServer = new RichEditDocumentServer())
{
string htmlText = string.Empty;
richServer.RtfText = memoValue;
CharacterProperties cp = richServer.Document.BeginUpdateCharacters(richServer.Document.Range);
cp.FontName = "Arial";
cp.FontSize = 12;
richServer.Document.EndUpdateCharacters(cp);
htmlText = richServer.HtmlText;
callDetail.Memo = htmlText;
}
}

You have to set font-family for your generated HTML. You can do so by applying CSS style to the header of geneted page.
Embed this style to the header:
"<style>body {font-family:Arial;}</style>"

Related

Change my Find and Replace CODE to change everything between xml marker

I have code to find and replace based on text area to multiple files (loop).
I woudl like to change find to find everything between <variables></variables>.
Theres a lot xml files and they have random text after <variables>.
App work fine to search exactly what i paste in to the field and change it in all files.
Now I have winform System.Windows.Forms.TextBox to find text. I can change it to text, label or whatever to make it const or maybe it is a possibility to make something like if between <variables> and </variables> is * then find everything. I know it is more difficult.
For now this app is only to work with a marker: <variables>.
I have this code to find:
private bool FindAndReplace(string file)
{
string content = string.Empty;
using (StreamReader sr = new StreamReader(file))
{
content = sr.ReadToEnd();
}
string searchText = GetSearchText(findWhatString);
if (Regex.IsMatch(content, searchText))
{
string newText = Regex.Replace(content, searchText, replaceWithText);
using (StreamWriter sw = new StreamWriter(file))
{
sw.Write(newText);
}
return true;
}
return false;
}
all code:
NetFiddle
edit: it works but I need to write "variable" in winform to make it start searching
private bool FindAndReplace(string file)
{
string content = string.Empty;
using (StreamReader sr = new StreamReader(file))
{
//Read the file into the string variable.
content = sr.ReadToEnd();
}
string searchText = GetSearchText(findWhatString);
if (Regex.IsMatch(content, searchText))
{
string newText = Regex.Replace(content, "(?<=<variables>).+?(?=</variables>)", replaceWithText);
using (StreamWriter sw = new StreamWriter(file))
{
sw.Write(newText);
}
return true;
}
return false;
}
you can use regex for matching between <variables></variables>
(?<=<variables>).+?(?=</variables>)
I don't think that you need to deal with Regex Options. Only if you need multiline Regex.
Check This Fiddle

Adding an optional attachment to a asp.net c# form

I have a problem with some code developed by a supplier. Unfortunately the supplier is no longer available, so I'm trying to fix my problem myself!
This is my code:
public ActionResult ReportaProblem(string title, string description, string url)
{
tblReportProblem feature = new tblReportProblem();
var path = "";
feature.Title = title;
feature.Description = description;
feature.DateTime = DateTime.UtcNow;
feature.UserId = AppConfig.LoginId;
HttpPostedFileBase fu = Request.Files["fuScreenCapture"];
if (fu.FileName != "")
{
string newName = "";
var filename = "";
filename = Path.GetFileName(fu.FileName).ToLower();
newName = DateTime.Now.ToString("MMddyyHHmmss") + filename;
path = Path.Combine(Server.MapPath(Constants.Paths.ProblemImagePath + newName));
fu.SaveAs(path);
feature.FileName = newName;
}
if (_IProject.AddReportProblem(feature))
{
TempData["success"] = Constants.ReportProblemSuccess;
}
Attachment attachment = new Attachment(path);
ReportProblemEmailToAdmin(title, description, url, attachment);
return RedirectToAction("ReportaProblem");
}
Basically it allows a user to report a problem in the application. It includes the ability to add an attachment (i.e. a screen image). The problem is that if the user doesn't attach a file, I get:
Server Error in '/' Application.
The parameter 'fileName' cannot be an empty string.
Parameter name: fileName
How do I allow the user to submit the problem report without an attachment?
Thanks, David.
You have to use the fileuploadcontrol API in your C# code, and this control must be there in your aspx page. For example, you should have markup like below in your aspx page ( the id can be anything you want).
Since you have not provided any markup, so I have assumed that the id of file upload control is fileUploadControl1, and all code is based on this assumption.
Markup for file upload control
<asp:FileUpload id="fileUploadConrol1" runat="server" />
Then, your C# code should be like below.
Note that you need to first check if any file has been posted by
checking the boolean flag fileUploadConrol1.HasFile and if true
then you do your attachment logic else you skip the attachment
logic.
Also, make sure that when attachment parameter is null in method
ReportProblemEmailToAdmin then its appropriately handled.
C# code using API of above file upload control
public ActionResult ReportaProblem(string title, string description, string url)
{
tblReportProblem feature = new tblReportProblem();
var path = "";
feature.Title = title;
feature.Description = description;
feature.DateTime = DateTime.UtcNow;
feature.UserId = AppConfig.LoginId;
//fileUploadConrol1 is id of file upload control in your aspx markup
if(fileUploadConrol1.HasFile)
{
//this line below is not needed
//HttpPostedFileBase fu = Request.Files["fuScreenCapture"];
//if (fu.FileName != "")
//{
string newName = "";
var filename = "";
filename = Path.GetFileName(fileUploadControl1.FileName).ToLower();
newName = DateTime.Now.ToString("MMddyyHHmmss") + filename;
path = Path.Combine(Server.MapPath(Constants.Paths.ProblemImagePath + newName));
fileUploadControl1.SaveAs(path);
feature.FileName = newName;
//}
}
if (_IProject.AddReportProblem(feature))
{
TempData["success"] = Constants.ReportProblemSuccess;
}
Attachment attachment = null;
if(path!= string.Empty)
{
attachment = new Attachment(path);
}
ReportProblemEmailToAdmin(title, description, url, attachment);
return RedirectToAction("ReportaProblem");
}
Alternate solution if you are using html file control and not asp fileupload control
Use the C# code below, if you are using html file control rather than asp fileupload control. (NOTE: The above solution would work only if you have asp file upload file control. Use this alternate solution in your case).
public ActionResult ReportaProblem(string title, string description, string url)
{
tblReportProblem feature = new tblReportProblem();
var path = "";
feature.Title = title;
feature.Description = description;
feature.DateTime = DateTime.UtcNow;
feature.UserId = AppConfig.LoginId;
HttpPostedFile fu = null;
if (Request.Files.Count > 0 )
{
//get the posted file
fu = Request.Files[0];
//apply logic to posted file
if(fu!=null) {
string newName = "";
var filename = "";
filename = Path.GetFileName(fu.FileName).ToLower();
newName = DateTime.Now.ToString("MMddyyHHmmss") + filename;
path = Path.Combine(Server.MapPath(Constants.Paths.ProblemImagePath + newName));
fu.SaveAs(path);
feature.FileName = newName;
}
}
if (_IProject.AddReportProblem(feature))
{
TempData["success"] = Constants.ReportProblemSuccess;
}
Attachment attachment = null;
if(path!= string.Empty)
{
attachment = new Attachment(path);
}
ReportProblemEmailToAdmin(title, description, url, attachment);
return RedirectToAction("ReportaProblem");
}

C#: Create Resource file with values having French characters

In my C# console application, using google translate service I am programmatically trying to translate MyResources.resx file into MyResources.fr-CA.resx
Here is the code:
public static string TranslateText(string input, string languagePair)
{
string url = String.Format("http://www.google.com/translate_t?hl=en&ie=UTF8&text={0}&langpair={1}", input, languagePair);
WebClient webClient = new WebClient();
webClient.Encoding = System.Text.Encoding.UTF8;
string result = webClient.DownloadString(url);
result = result.Substring(result.IndexOf("<span title=\"") + "<span title=\"".Length);
result = result.Substring(result.IndexOf(">") + 1);
result = result.Substring(0, result.IndexOf("</span>"));
return result.Trim();
}
static void Main(string[] args)
{
var resWriter = new ResourceWriter("Translations.resources");
ResourceSet resourceSet = MyResources.ResourceManager.GetResourceSet(CultureInfo.CurrentUICulture, true, true);
foreach (DictionaryEntry entry in resourceSet)
{
string resKey = entry.Key.ToString();
string resValue = entry.Value.ToString();
var result = TranslateText(resValue, "en|fr-CA");
if (result != null)
{
resWriter.AddResource(resKey, System.Web.HttpUtility.HtmlDecode(result));
}
}
resWriter.Close();
}
Problem is that some french characters show up as "?" character in resulting Resources.fr-CA.resx file and that also, only if I use System.Web.HttpUtility.HtmlDecode, otherwise it shows characters for example like "d&#39"
So how can I programmatically insert French based values in a resource file correctly?
You have to change your webClient encoding type to decode French characters properly.
So this line:
webClient.Encoding = System.Text.Encoding.UTF8;
Have to be like this:
webClient.Encoding = System.Text.Encoding.GetEncoding("ISO-8859-1");
and your "result" variable (after calling TranslateText method) should be readable in French correctly.
Please try this way and inform me, it worked for me.
Regards.

ITextSharp build phrase from Html with list tags

I have a report that I'm trying to generate using iTextSharp that includes html text entered by the user using tinymce on my web page. I then have a report and I want to insert a phrase that uses their markup.
While basic markup such as bold and underline work, lists, indents, alignment do not. Any suggestions short of writing my own little html to pdf parser?
My code:
internal static Phrase GetPhraseFromHtml(string html, string fontName, int fontSize)
{
var returnPhrase = new Phrase();
html.Replace(Environment.NewLine, String.Empty);
//the string has to be well formated html in order to work and has to specify the font since
//specifying the font in the phrase overrides the formatting of the html tags.
string pTag = string.Format("<p style='font-size: {0}; font-family:{1}'>", fontSize, fontName);
if (html.StartsWith("<p>"))
{
html = html.Replace("<p>", pTag);
}
else
{
html = pTag + html + "</p>";
}
html
= "<html><body>"
+ html
+ "</body></html>";
using (StringWriter sw = new StringWriter())
{
using (System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(sw))
{
var xmlWorkerHandler = new XmlWorkerHandler();
//Bind a reader to our text
using (TextReader textReader = new StringReader(html))
{
//Parse
XMLWorkerHelper.GetInstance().ParseXHtml(xmlWorkerHandler, textReader);
}
var addPhrase = new Phrase();
var elementText = new StringBuilder();
bool firstElement = true;
//Loop through each element
foreach (var element in xmlWorkerHandler.elements)
{
if (firstElement)
{
firstElement = false;
}
else
{
addPhrase.Add(new Chunk("\n"));
}
//Loop through each chunk in each element
foreach (var chunk in element.Chunks)
{
addPhrase.Add(chunk);
}
returnPhrase.Add(addPhrase);
addPhrase = new Phrase();
}
return returnPhrase;
}
}
}

CSS is not applying on creating pdf from ABC pdf

Problem:
I am passing HTML and creating pdf through ABC pdf.
But the CSS are not applied on the content and pdf created is not as expected.
Here is my code can u please suggest what is the problem or how we can apply CSS...
public static String CreateHtmlFile(String strHtmlCode)
{
String Modifiedhtml = #"<!DOCTYPE html PUBLIC ""-//W3C//DTD XHTML 1.0 Transitional//EN"" ""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd""><html class="" _Telerik_IE9"" xmlns=""http://www.w3.org/1999/xhtml"">" + strHtmlCode;
Modifiedhtml = Modifiedhtml.Remove(Modifiedhtml.IndexOf(#"//<![CDATA["), (Modifiedhtml.IndexOf("//]]>") - Modifiedhtml.IndexOf(#"//<![CDATA[")));
string[] stringSeparators = new string[] { "PdfCreator" };
var baseUrl = HttpContext.Current.Request.Url.AbsoluteUri.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries).First();
Modifiedhtml = Modifiedhtml.Replace(#"href=""../", (#"href=""" + baseUrl));
Modifiedhtml = Modifiedhtml.Replace(#"href=""/", (#"href=""" + baseUrl));
Doc theDoc = new Doc();
theDoc.HtmlOptions.UseScript = false;
//theDoc.Width = 1125;
String s = string.Empty;
//s = File.ReadAllText(#"D:\test.html");
theDoc.Page = theDoc.AddPage();
int theID;
theID = theDoc.AddHtml(strHtmlCode);
//theID = theDoc.AddHtml(s);
while (true)
{
theDoc.FrameRect(); // add a black border
if (!theDoc.Chainable(theID))
break;
theDoc.Page = theDoc.AddPage();
theID = theDoc.AddImageToChain(theID);
}
for (int i = 1; i <= theDoc.PageCount; i++)
{
theDoc.PageNumber = i;
theDoc.Flatten();
}
theDoc.Save(#"D:\two\pagedhtml4.pdf");
theDoc.Clear();
return String.Empty;
}
strHtmlCode is the HTML of the page which we have to convert in PDF.
Thanks in advance
From the WebSupergoo doc page on the AddHtml Function:
Adds a block of HTML styled text to the current page.
HTML styled text does not support CSS. For full featured, standard CSS, you want AddImageHtml.
You are passing strHtmlCode into the AddHtml function. It looks like you really want to pass in Modifiedhtml instead.

Categories

Resources