I am making an RSS Reader in C#. It gets the feed and adds it to a rich text box. Is there a way to have the title in a feed be a separate font than the summary in the rich text box? If so, how? Here is my code:
if (feedsList.SelectedItem != null)
{
feedTxt.Text = "";
string url = feedsList.GetItemText(feedsList.SelectedItem);
Uri myUri = new Uri(url, UriKind.Absolute);
XmlReader reader = XmlReader.Create(url);
SyndicationFeed feed = SyndicationFeed.Load(reader);
foreach (SyndicationItem item in feed.Items)
{
feedTxt.Text = feedTxt.Text + item.Title.Text;
feedTxt.Text = feedTxt.Text + "\n\n" + item.Summary.Text + "\n\n";
}
}
Thanks in advance!
You can use Selection property of on RichTextBox control. Something Like this:
if (feedsList.SelectedItem != null)
{
feedTxt.Text = "";
string url = feedsList.GetItemText(feedsList.SelectedItem);
Uri myUri = new Uri(url, UriKind.Absolute);
XmlReader reader = XmlReader.Create(url);
SyndicationFeed feed = SyndicationFeed.Load(reader);
foreach (SyndicationItem item in feed.Items)
{
// Store current content length of RichTextBox
int currentLength = feedTxt.Length;
// Append new content
feedTxt.Text += item.Title.Text + "\n\n";
feedTxt.Text += item.Summary.Text + "\n\n";
// Set the font for Title using selection
feedTxt.SelectionStart = currentLength.Length;
feedTxt.SelectionLength = item.Title.Text.Length;
feedTxt.SelectionFont = new System.Drawing.Font("Tahoma", 24);
// Set the font for Summary using selection
feedTxt.SelectionStart = currentLength + item.Title.Text.Length;
feedTxt.SelectionLength = item.Summary.Text;
feedTxt.SelectionFont = new System.Drawing.Font("Arial", 16);
// Reset Selection
txtTest.SelectionStart = 0;
txtTest.SelectionLength = 0;
}
}
Update
Looks like you can't append new content and style at the same time (possible limitation of Winforms?). My simple solution is to append all the content in one sweep and calculate all the selections you want to style and push them to a List.
Then you do a second pass looping through all your selections and do the styling.
You need this struct first:
struct ArticleSelection
{
public int TitleStart { get; set; }
public int TitleEnd { get; set; }
public int SummaryStart { get; set; }
public int SummaryEnd { get; set; }
};
Updated Code
if (feedsList.SelectedItem != null)
{
feedTxt.Text = "";
string url = feedsList.GetItemText(feedsList.SelectedItem);
Uri myUri = new Uri(url, UriKind.Absolute);
XmlReader reader = XmlReader.Create(url);
SyndicationFeed feed = SyndicationFeed.Load(reader);
// Create List to store our selections
List<ArticleSelection> articleSelections = new List<ArticleSelection>();
// Loop all incoming content
foreach (SyndicationItem item in feed.Items)
{
// Store current content length of RichTextBox
int currentLength = feedTxt.Length;
// Append new content
feedTxt.Text += item.Title.Text + "\n\n";
feedTxt.Text += item.Summary.Text + "\n\n";
// Calculate selection
articleSelections.Add(new ArticleSelection()
{
TitleStart = currentLength,
TitleEnd = feed.Item1.Length,
SummaryStart = currentLength + feed.Item1.Length,
SummaryEnd = feedTxt.Text - currentLength // This accounts for new lines above
}); ;
}
// Loop through the content and style it
foreach (ArticleSelection selection in articleSelections)
{
// Set the selection for Title
txtTest.SelectionStart = selection.TitleStart;
txtTest.SelectionLength = selection.TitleEnd;
txtTest.SelectionFont = new Font("Tahoma", 24);
// Set the selection for Summary
txtTest.SelectionStart = selection.SummaryStart;
txtTest.SelectionLength = selection.SummaryEnd;
txtTest.SelectionFont = new Font("Arial", 14);
}
// Remove Selection
txtTest.DeselectAll();
}
You should get something like this:
Related
I am working on a WinForms application. I use the pdf file to reset the password and the values on pdf are stored as key-value pairs(email: xxxx#mail.com, pass: 11111).
What I want to do:
Read the PDF file line by line and fill the appropriate textboxes.
What I Have done:
public bool CreatePDF(string location, string email, string key)
{
if(location != "" && email != "" && key != "")
{
PdfWriter pdfwriter = new PdfWriter(location);
PdfDocument pdf = new PdfDocument(pdfwriter);
Document document = new Document(pdf);
Paragraph fields = new Paragraph("Email: "+email + "\n" + "Secret Key: "+key);
document.Add(fields);
document.Close();
return true;
}
else
{
return false;
}
}
public string ReadPDF(string location)
{
var pdfDocument = new PdfDocument(new PdfReader(location));
StringBuilder processed = new StringBuilder();
var strategy = new LocationTextExtractionStrategy();
string text = "";
for (int i = 1; i <= pdfDocument.GetNumberOfPages(); ++i)
{
var page = pdfDocument.GetPage(i);
text += PdfTextExtractor.GetTextFromPage(page, strategy);
processed.Append(text);
}
return text;
}
}
Thank you in advance Guys!. Any suggestions on CreatePDF are also welcome.
This is what I came up with,
var pdfDocument = new PdfDocument(new PdfReader("G:\\Encryption_File.pdf"));
StringBuilder processed = new StringBuilder();
var strategy = new LocationTextExtractionStrategy();
string text = "";
for (int i = 1; i <= pdfDocument.GetNumberOfPages(); ++i)
{
var page = pdfDocument.GetPage(i);
text += PdfTextExtractor.GetTextFromPage(page, strategy);
processed.Append(text);
}
text.Split('\n');
string line = "";
line = text + "&";
string[] newLines = line.Split('&');
textBox1.Text = newLines[0].Split(':')[1].ToString();
textBox2.Text = newLines[0].Split(':')[2].ToString();
I work in WPF C#, i want to replace text into RichtextBox
i load my rtf File who contain picture it's work fine.
If i use this :
ReposLettresFusion m_ReposLettresFusion = new ReposLettresFusion();
TextRange range = new TextRange(rtb.Document.ContentStart, rtb.Document.ContentEnd);
FileStream fStream = new FileStream(#pPath, FileMode.Create);
range.Text = m_ReposLettresFusion.Fusion(pPkGuidLettre, range.Text);
range.Save(fStream, DataFormats.Rtf);
fStream.Close();
rtb.LoadRtf(pPath);
m_ReposLettresFusion = null;
range = null;
It's change my text but i loose my picture and fonts all my formatting.
How i can replace text and keep all formatting of the Rtf
Thank you
Try this :
public void Fusion(ref Xceed.Wpf.Toolkit.RichTextBox pRichTextControl)
{
foreach (KeyValuePair<string, string> entry in LettreFusion)
{
string keyword = entry.Key;
string newString = entry.Value;
TextRange text = new TextRange(pRichTextControl.Document.ContentStart, pRichTextControl.Document.ContentEnd);
TextPointer current = text.Start.GetInsertionPosition(LogicalDirection.Forward);
while (current != null)
{
string textInRun = current.GetTextInRun(LogicalDirection.Forward);
if (!string.IsNullOrWhiteSpace(textInRun))
{
int index = textInRun.IndexOf(keyword);
if (index != -1)
{
TextPointer selectionStart = current.GetPositionAtOffset(index, LogicalDirection.Forward);
TextPointer selectionEnd = selectionStart.GetPositionAtOffset(keyword.Length, LogicalDirection.Forward);
TextRange selection = new TextRange(selectionStart, selectionEnd);
selection.Text = newString;
pRichTextControl.Selection.Select(selection.Start, selection.End);
pRichTextControl.Focus();
}
}
current = current.GetNextContextPosition(LogicalDirection.Forward);
}
}
}
I have a problem with printing a pdf.
So my Document is being created by writing some values in a pdf document and saving it
public void CreateDocument(string name)
{
string oldreport = #"..\Resources\FehlerReport.pdf";
string newreportpath = #"..\Resources\" + name;
using (var newFileStream = new FileStream(newreportpath, FileMode.Create))
{
var pdfReader = new PdfReader(oldreport);
var stamper = new PdfStamper(pdfReader, newFileStream);
var form = stamper.AcroFields;
var fieldKeys = form.Fields.Keys;
form.SetField("Auftragsnummer", Kundeninformation.Auftragsnummer.ToString());
form.SetField("Kundensachnummer", Kundeninformation.Kundensachnummer.ToString());
form.SetField("Kundenname", Kundeninformation.Kundenname.ToString());
form.SetField("Kundenbestellnummer", Kundeninformation.Kundenbestellnummer.ToString());
form.SetField("Kundenrezepturnummer", Kundeninformation.Kundenrezepturnummer.ToString());
form.SetField("Spulennummer", Kundeninformation.Spulennummer.ToString());
form.SetField("Fertigungsdatum1", System.DateTime.Today.ToString("dd.MM.yy"));
int i = 1;
foreach (var item in _MeasurementReport.MeasurementReportItems)
{
form.SetField(("UhrzeitRow" + i).ToString(), item.Uhrzeit.ToString("HH:mm:ss"));
form.SetField(("FehlerindexRow" + i).ToString(), i.ToString());
form.SetField(("Position mmRow" + i).ToString(), (item.Laufmeter * pixelSize).ToString("0.00", System.Globalization.CultureInfo.InvariantCulture));
form.SetField(("HoeheRow" + i).ToString(), (item.DefectCountours.H * pixelSize).ToString("0.00", System.Globalization.CultureInfo.InvariantCulture));
form.SetField(("Breite mmRow" + i).ToString(), (item.DefectCountours.W * pixelSize).ToString("0.00", System.Globalization.CultureInfo.InvariantCulture));
form.SetField(("Flaeche Row" + i).ToString(), (item.DefectCountours.W * pixelSize * pixelSize).ToString("0.00", System.Globalization.CultureInfo.InvariantCulture));
i++;
}
form.SetField("Datum", System.DateTime.Today.ToString("dd.MM.yy"));
form.SetField("Uhrzeit", System.DateTime.Now.ToString("HH:mm"));
stamper.FormFlattening = true;
stamper.Close();
pdfReader.Close();
}
}
So now i want to print the document with this function, which also calls the CreateDocument function. It prints, but the paper is white. I checked if the created pdf is being created, and it is being created but apparently not printed.
public void Print()
{
string name = Kundeninformation.Auftragsnummer + "_" + Kundeninformation.Spulennummer+".pdf";
CreateDocument(name);
List<string> PrinterFound = new List<string>();
PrinterSettings printer = new PrinterSettings();
foreach (var item in PrinterSettings.InstalledPrinters)
{
PrinterFound.Add(item.ToString());
}
printer.PrinterName = PrinterFound[7];
printer.PrintFileName = name;
PrintDocument PrintDoc = new PrintDocument();
PrintDoc.DocumentName = #"..\Resources\"+name;
PrintDoc.PrinterSettings.PrinterName = PrinterFound[7];
PrintDoc.Print();
}
make sure your file is created completely.. otherwise you will this issue. to test quickly put some delay between file creation and printing
My program extracts Windows Updates, detects the version numbers and logs them to columns (KB, Version) in a list view, but I'm trying to change this to an ObjectListView so I can sort the columns. I can't for the life of me work out how to write the results to an ObjectListView and nothing I try seems to work. Here's my current code:
foreach (string file in msu)
{
string KB = GetKBNumber(file);
Expand.MSU(file, TempDirectory + "\\" + KB);
List<string> versions = GetVersionNumbers(TempDirectory + "\\" + KB);
foreach (string version in versions)
{
ListViewItem itm = new ListViewItem(new[] { KB, version });
olvOutput.Items.Add(itm);
}
PerformStep();
}
But it just writes blank data to the control. What am I doing wrong? Thanks in advance.
Edit: Here's the olvOutput designer code:
//
// olvOutput
//
this.olvOutput.AllColumns.Add(this.olvKBNumber);
this.olvOutput.AllColumns.Add(this.olvVersion);
this.olvOutput.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.olvOutput.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.olvKBNumber,
this.olvVersion});
this.olvOutput.Location = new System.Drawing.Point(18, 12);
this.olvOutput.Name = "olvOutput";
this.olvOutput.ShowGroups = false;
this.olvOutput.Size = new System.Drawing.Size(571, 193);
this.olvOutput.TabIndex = 8;
this.olvOutput.UseAlternatingBackColors = true;
this.olvOutput.UseCompatibleStateImageBehavior = false;
this.olvOutput.View = System.Windows.Forms.View.Details;
//
// olvKBNumber
//
this.olvKBNumber.AspectName = "";
this.olvKBNumber.CellPadding = null;
this.olvKBNumber.MaximumWidth = 100;
this.olvKBNumber.MinimumWidth = 100;
this.olvKBNumber.Text = "KB Number";
this.olvKBNumber.Width = 100;
//
// olvVersion
//
this.olvVersion.AspectName = "";
this.olvVersion.CellPadding = null;
this.olvVersion.Text = "Version";
this.olvVersion.Width = 113;
Modify the first of your snippets as:
foreach (string file in msu)
{
string KB = GetKBNumber(file);
Expand.MSU(file, TempDirectory + "\\" + KB);
List<string> versions = GetVersionNumbers(TempDirectory + "\\" + KB);
foreach (string version in versions)
{
olvOutput.AddObject(new { kbAspectName = KB, versionAspectName = version });
}
PerformStep();
}
... and modify the second code snippet as:
//
// olvKBNumber
//
this.olvKBNumber.AspectName = "kbAspectName";
// ...
//
// olvVersion
//
this.olvVersion.AspectName = "versionAspectName";
Disclaimer:
never worked with ObjectListView before so I am not saying this is the best way to achieve what you want.
I want to go to multiple pages using ASP.NET 4.0, copy all HTML and then finally paste it in a text box. From there I would like to run my parsing function, what is the best way to handle this?
protected void goButton_Click(object sender, EventArgs e)
{
if (datacenterCombo.Text == "BL2")
{
fwURL = "http://website1.com/index.html";
l2URL = "http://website2.com/index.html";
lbURL = "http://website3.com/index.html";
l3URL = "http://website4.com/index.html";
coreURL = "http://website5.com/index.html";
WebRequest objRequest = HttpWebRequest.Create(fwURL);
WebRequest layer2 = HttpWebRequest.Create(l2URL);
objRequest.Credentials = CredentialCache.DefaultCredentials;
using (StreamReader layer2 = new StreamReader(layer2.GetResponse().GetResponseStream()))
using (StreamReader objReader = new StreamReader(objRequest.GetResponse().GetResponseStream()))
{
originalBox.Text = objReader.ReadToEnd();
}
objRequest = HttpWebRequest.Create(l2URL);
//Read all lines of file
String[] crString = { "<BR> " };
String[] aLines = originalBox.Text.Split(crString, StringSplitOptions.RemoveEmptyEntries);
String noHtml = String.Empty;
for (int x = 0; x < aLines.Length; x++)
{
if (aLines[x].Contains(ipaddressBox.Text))
{
noHtml += (RemoveHTML(aLines[x]) + "\r\n");
}
}
//Print results to textbox
resultsBox.Text = String.Join(Environment.NewLine, noHtml);
}
}
public static string RemoveHTML(string text)
{
text = text.Replace(" ", " ").Replace("<br>", "\n");
var oRegEx = new System.Text.RegularExpressions.Regex("<[^>]+>");
return oRegEx.Replace(text, string.Empty);
}
Instead of doing all this manually you should probably use HtmlAgilityPack instead then you could do something like this:
HtmlWeb web = new HtmlWeb();
HtmlDocument doc = web.Load("http://google.com");
var targetNodes = doc.DocumentNode
.Descendants()
.Where(x=> x.ChildNodes.Count == 0
&& x.InnerText.Contains(someIpAddress));
foreach (var node in targetNodes)
{
//do something
}
If HtmlAgilityPack is not an option for you, simplify at least the download portion of your code and use a WebClient:
using (WebClient wc = new WebClient())
{
string html = wc.DownloadString("http://google.com");
}