i have an application where my user changes font and font color for different labels etc and they save it to a file but i need to be able to convert the font of the specified label to a string to be written to file, and then when they open that file my program will convert that string back into a font object. How can this be done? I haven't found anywhere that shows how it can be done.
thank you
bael
It is easy to go back and forth from a font to a string and back with the System.Drawing.FontConverter class. For example:
var cvt = new FontConverter();
string s = cvt.ConvertToString(this.Font);
Font f = cvt.ConvertFromString(s) as Font;
You can serialize the font class to a file.
See this MSDN article for details of how to do so.
To serialize:
private void SerializeFont(Font fn, string FileName)
{
using(Stream TestFileStream = File.Create(FileName))
{
BinaryFormatter serializer = new BinaryFormatter();
serializer.Serialize(TestFileStream, fn);
TestFileStream.Close();
}
}
And to deserialize:
private Font DeSerializeFont(string FileName)
{
if (File.Exists(FileName))
{
using(Stream TestFileStream = File.OpenRead(FileName))
{
BinaryFormatter deserializer = new BinaryFormatter();
Font fn = (Font)deserializer.Deserialize(TestFileStream);
TestFileStream.Close();
}
return fn;
}
return null;
}
Quite simple really if you want to make it readable in the file:
class Program
{
static void Main(string[] args)
{
Label someLabel = new Label();
someLabel.Font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Strikeout | FontStyle.Italic);
var fontString = FontToString(someLabel.Font);
Console.WriteLine(fontString);
File.WriteAllText(#"D:\test.txt", fontString);
var loadedFontString = File.ReadAllText(#"D:\test.txt");
var font = StringToFont(loadedFontString);
Console.WriteLine(font.ToString());
Console.ReadKey();
}
public static string FontToString(Font font)
{
return font.FontFamily.Name + ":" + font.Size + ":" + (int)font.Style;
}
public static Font StringToFont(string font)
{
string[] parts = font.Split(':');
if (parts.Length != 3)
throw new ArgumentException("Not a valid font string", "font");
Font loadedFont = new Font(parts[0], float.Parse(parts[1]), (FontStyle)int.Parse(parts[2]));
return loadedFont;
}
}
Otherwise serialization is the way to go.
First, you can use following article to enumerate system fonts.
public void FillFontComboBox(ComboBox comboBoxFonts)
{
// Enumerate the current set of system fonts,
// and fill the combo box with the names of the fonts.
foreach (FontFamily fontFamily in Fonts.SystemFontFamilies)
{
// FontFamily.Source contains the font family name.
comboBoxFonts.Items.Add(fontFamily.Source);
}
comboBoxFonts.SelectedIndex = 0;
}
To create a font:
Font font = new Font( STRING, 6F, FontStyle.Bold );
Use it to setup font style etc....
Label label = new Label();
. . .
label.Font = new Font( label.Font, FontStyle.Bold );
Use this code to create a font based on the name and color information:
Font myFont = new System.Drawing.Font(<yourfontname>, 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
Color myColor = System.Drawing.Color.FromArgb(<yourcolor>);
Related
how can I draw checked box (with X) with iTextSharp.
I don't want it to be image. More like symbol
I tried this, but it didn't work:
RadioCheckField fCell = new RadioCheckField(writer, new Rectangle(20,20), "NoDeletion", "Yes");
fCell.CheckType = RadioCheckField.TYPE_CROSS;
PdfFormField footerCheck = null;
footerCheck = fCell.CheckField;
writer.AddAnnotation(footerCheck);
Thanks,
I assume that you don't need an interactive check box. You just want to use a check box character. The first thing you need, is a font that has such a character. When I work on Windows, I have access to a file named WINGDING.TTF. This is a font program that contains all kinds of symbols, among others some check boxes:
I created the PDF shown in the screen shot like this:
public static final String DEST = "results/fonts/checkbox_character.pdf";
public static final String FONT = "c:/windows/fonts/WINGDING.TTF";
public static final String TEXT = "o x \u00fd \u00fe";
public void createPdf(String dest) throws IOException, DocumentException {
Document document = new Document();
PdfWriter.GetInstance(document, new FileOutputStream(dest));
document.Open();
BaseFont bf = BaseFont.CreateFont(FONT, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
Font f = new Font(bf, 12);
Paragraph p = new Paragraph(TEXT, f);
document.Add(p);
document.Close();
}
As you can see, the empty check box corresponds with the letter o, there are three variations of a checked check box.
Thank you, but I found a solution. Here it is:
var checkBox = new Phrase();
checkBox.Add(new Chunk(" ☒ ", new Font(BaseFont.CreateFont(PrintCommonConstants.UnicodeFontNormal, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED), 18)));
I am trying to print the contents of a rich-text box. I do that in the following way:
Obtain a TextRange from the FlowDocument.
Create a new FlowDocument with a smaller font using the TextRange.
Send this new FlowDocument to the printer.
My problem, is that the font doesn't seem to change. I would like it to go down to size 8. Instead, it remains at a fixed size. Here is my code:
private void button_Print_Click(object sender, RoutedEventArgs e)
{
IDocumentPaginatorSource ps = null;
FlowDocument fd = new FlowDocument();
PrintDialog pd = new PrintDialog();
Paragraph pg = new Paragraph();
Style style = new Style(typeof(Paragraph));
Run r = null;
string text = string.Empty;
// get the text
text = new TextRange(
this.richTextBox_Info.Document.ContentStart,
this.richTextBox_Info.Document.ContentEnd).Text;
// configure the style of the flow document
style.Setters.Add(new Setter(Block.MarginProperty, new Thickness(0)));
fd.Resources.Add(typeof(Paragraph), style);
// style the paragraph
pg.LineHeight = 0;
pg.LineStackingStrategy = LineStackingStrategy.BlockLineHeight;
pg.FontFamily = new FontFamily("Courier New");
pg.TextAlignment = TextAlignment.Left;
pg.FontSize = 8;
// create the paragraph
r = new Run(text);
r.FontFamily = new FontFamily("Courier New");
r.FontSize = 8;
pg.Inlines.Add(r);
// add the paragraph to the document
fd.Blocks.Add(pg);
ps = fd;
// format the page
fd.PagePadding = new Thickness(50);
fd.ColumnGap = 0;
fd.ColumnWidth = pd.PrintableAreaWidth;
// print the document
if (pd.ShowDialog().Value == true)
{
pd.PrintDocument(ps.DocumentPaginator, "Information Box");
}
}
I would like to add that, changing the font works just fine for the flow-document when it is inside of the rich-text box. However, when I am doing it programmatically (as shown above) I run into problems.
I try your code and found when I remove this line and then change the r.FontSize to 50, it seems work.
pg.LineHeight = 0;
Because I use dynamic text, italic or bold text could be any where, cutting everything into chunks is not an option, so I have to use html parser.
Input string is
ąčęėįšųū90-žthis <i>is <b>bold ąčęėįšųū90-ž</i></b> text
String is formatted with iTextSharp html parser:
private Paragraph CreateSimpleHtmlParagraph(String text)
{
//Our return object
List<Chunk> c = new List<Chunk>();
Paragraph p = new Paragraph();
var styles = new StyleSheet();
using (StringReader sr = new StringReader(text))
{
//Parse and get a collection of elements
List<IElement> elements = iTextSharp.text.html.simpleparser.HTMLWorker.ParseToList(sr, styles);
foreach (IElement e in elements)
{
var chunks = e.Chunks;
foreach (var chunk in chunks) //list of chunks
{
chunk.Font.SetFamily(""); //how to set font family here
}
p.Add(e);
}
}
return p; //getting all the special chars (ąčęėįšųū90-ž...)
}
Code in the main form:
Paragraph pr1 = CreateSimpleHtmlParagraph("ąčęėįšųū90-žthis <i>is <b>bold ąčęėįšųū90-ž</i></b> text");
doc.Add(pr1);
But in PDF I see only
š90-žthis is bold š90-ž text
and no other chars (ąčęėį). I know it has something to do with Fonts, but can't find the problem where. The font should be the same for whole document, times new roman, arial, ect., anything, that could show me my special chars (cp1257, Baltic encoding).
Usually, when I have to format text I use Chunks and my own fonts:
Font arial10n = PdfFontManager.GetFont("c:\\windows\\fonts\\arial.ttf", 10);
colClientTxt.AddText(new Chunk(row["name"].ToString() + "\n", arial10n));
and in PdfFontManager class:
public static Font GetFont(string name, int size)
{
BaseFont baseFont = BaseFont.CreateFont(name, BaseFont.CP1257, BaseFont.EMBEDDED);
Font font = new Font(baseFont, size);
return font;
}
So, how to set font family, or maybe there is another way to dinamicaly format my text?
I have a line of text to display and what I want to do is underline only the heading portion of the text in the display. How do I accomplish this please?
Message: This is a message for Name of Client.
Where "Message:" is underlined.
Use RichTextBox instead !
this.myRichTextBox.SelectionStart = 0;
this.myRichTextBox.SelectionLength = this.contactsTextBox.Text.Length-1;
myRichTextBox.SelectionFont = new Font(myRichTextBox.SelectionFont, FontStyle.Underline);
this.myRichTextBox.SelectionLength = 0;
You can do that underline using the RichTextBox control
int start = rtbTextBox.Text.IndexOf("Message:", StringComparison.CurrentCultureIgnoreCase);
if(start > 0)
{
rtbTextBox.SelectionStart = start;
rtbTextBox.SelectionLength = "Message:".Length-1;
rtbTextBox.SelectionFont = new Font(rtbTextBox.SelectionFont, FontStyle.Underline);
rtbTextBox.SelectionLength = 0;
}
This example use directly the text you provided in your question. It will be better if you encapsulate this code in a private method and pass in the heading text.
For example:
private void UnderlineHeading(string heading)
{
int start = rtbTextBox.Text.IndexOf(heading, StringComparison.CurrentCultureIgnoreCase);
if(start > 0)
{
rtbTextBox.SelectionStart = start;
rtbTextBox.SelectionLength = heading.Length-1;
rtbTextBox.SelectionFont = new Font(rtbTextBox.SelectionFont, FontStyle.Underline);
rtbTextBox.SelectionLength = 0;
}
}
and call from your form whith: UnderlineHeading("Message:");
If you want to show the text using a rich text box, you could do something like this:
richTextBox1.SelectionFont = new Font("Times New Roman", 10, FontStyle.Underline);
richTextBox1.SelectedText = "Message:";
richTextBox1.SelectionFont = new Font("Times New Roman", 10, FontStyle.Regular);
richTextBox1.SelectedText = " This is a message for Name of Client.";
Or, if the message is dynamic and the header and text are always separated by a colon, you could do something like this:
string message = "Message: This is a message for Name of Client";
string[] parts = message.Split(':');
richTextBox1.SelectionFont = new Font("Times New Roman", 10, FontStyle.Underline);
richTextBox1.SelectedText = parts[0] + ":";
richTextBox1.SelectionFont = new Font("Times New Roman", 10, FontStyle.Regular);
richTextBox1.SelectedText = parts[1];
Or, if you want to show the text dynamically in labels, you could do something like this:
string message = "Message: This is a message for Name of Client";
string[] parts = message.Split(':');
Label heading = new Label();
heading.Text = parts[0] + ":";
heading.Font= new Font("Times New Roman", 10, FontStyle.Underline);
heading.AutoSize = true;
flowLayoutPanel1.Controls.Add(heading);
Label message = new Label();
message.Text = parts[1];
message.Font = new Font("Times New Roman", 10, FontStyle.Regular);
message.AutoSize = true;
flowLayoutPanel1.Controls.Add(message);
Just a thought, You can use masked text box or create a custom control with richtextbox having underline and use it in client application. I heard there is a chance of creating textbox with underline using GDI+ api but not sure.
Thanks
Mahesh kotekar
I am trying to display the "✔" character in a PDF using iTextSharp. However the character won't show up on the created PDF. Please help me on this.
Phrase phrase = new Phrase("A check mark: ");
Font zapfdingbats = new Font(Font.FontFamily.ZAPFDINGBATS);
phrase.Add(new Chunk("\u0033", zapfdingbats));
phrase.Add(" and more text");
document.Add(phrase);
Font Wingdings prints this character instead of "o".
You need to connect this font to your application, then apply this font to letter and embedd the font into pdf for compatibility.
This is my function (not cleaned) that I have used in one of my projects a while back.
please clean it up, but it has some essential features that you need. (I had my custom fonts (font1.ttf and font2.ttf) copied in the project directory)
I am hoping it will help you.
public void StartConvert(String originalFile, String newFile)
{
Document myDocument = new Document(PageSize.LETTER);
PdfWriter.GetInstance(myDocument, new FileStream(newFile, FileMode.Create));
myDocument.Open();
int totalfonts = FontFactory.RegisterDirectory("C:\\WINDOWS\\Fonts");
iTextSharp.text.Font content = FontFactory.GetFont("Pea Heather's Handwriting", 13);//13
iTextSharp.text.Font header = FontFactory.GetFont("assign", 16); //16
BaseFont customfont = BaseFont.CreateFont(#"font1.ttf", BaseFont.CP1252, BaseFont.EMBEDDED);
Font font = new Font(customfont, 13);
string s = " ";
myDocument.Add(new Paragraph(s, font));
BaseFont customfont2 = BaseFont.CreateFont(#"font2.ttf", BaseFont.CP1252, BaseFont.EMBEDDED);
Font font2 = new Font(customfont2, 16);
string s2 = " ";
myDocument.Add(new Paragraph(s2, font2));
try
{
try
{
using (StreamReader sr = new StreamReader(originalFile))
{
// Read and display lines from the file until the end of
// the file is reached.
String line;
while ((line = sr.ReadLine()) != null)
{
String newTempLine = "";
String[] textArray;
textArray = line.Split(' ');
newTempLine = returnSpaces(RandomNumber(0, 6)) + newTempLine;
int counterMax = RandomNumber(8, 12);
int counter = 0;
foreach (String S in textArray)
{
if (counter == counterMax)
{
Paragraph P = new Paragraph(newTempLine + Environment.NewLine, font);
P.Alignment = Element.ALIGN_LEFT;
myDocument.Add(P);
newTempLine = "";
newTempLine = returnSpaces(RandomNumber(0, 6)) + newTempLine;
}
newTempLine = newTempLine + returnSpaces(RandomNumber(1, 5)) + S;
counter++;
}
Paragraph T = new Paragraph(newTempLine, font2);
T.Alignment = Element.ALIGN_LEFT;
myDocument.Add(T);
}
}
}
catch (Exception e)
{
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
}
catch (DocumentException de)
{
Console.Error.WriteLine(de.Message);
}
catch (IOException ioe)
{
Console.Error.WriteLine(ioe.Message);
}
try
{
myDocument.Close();
}
catch { }
}
Define font at master
protected static Font ZAPFDINGBATS(float size, bool bold = false, bool italic = false, bool underline = false, Color color = null)
=> new(StandardFonts.ZAPFDINGBATS, size, bold, italic, underline, color);
declare font
private readonly Font ZapFont = ZAPFDINGBATS(10, bold: false, color: ColorConstants.BLACK);
private readonly Action<Cell> _cellRight = cell => cell.RemoveBorder().SetTextAlignment(TextAlignment.RIGHT);
Use
document.AddTable(
columns: new float[1]
{
100
},
table => table.SetWidth(document.GetPageEffectiveArea(PageSize).GetWidth())
.SetMargins(0, 0, 0, 0)
.AddCell(model.IsTrue ? "4" : "o", ZapFont, _cellRight );
This worked for me:
pdfStamper.FormFlattening = true;