iTextSharp setting font family to chunk - c#

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?

Related

Hebrew characters are printed in reverse order in iText 7

I'm using iText 7 for printing some text in List (in Hebrew) to PDF file, but while printing the Hebrew characters are printed in a reverse way.
The input given was "קניון אם הדרך" while the data printed in PDF is "ךרדה םא ןוינק"
I have set the font encoding and the base direction for the elements but still the characters are printed in the reverse order.
Code to print list into the table in PDF:
public void PrintListData(string filename)
{
var writer = new PdfWriter(filename);
PdfDocument pdfDoc = new PdfDocument(writer);
Document doc = new Document(pdfDoc, PageSize.A4);
SetFont(doc);
Table table = new Table(UnitValue.CreatePercentArray(2)).UseAllAvailableWidth();
table.SetTextAlignment(TextAlignment.RIGHT);
//table.SetBaseDirection(BaseDirection.RIGHT_TO_LEFT);
var index = 1;
foreach (var item in _data)
{
var para = new Paragraph(item);
para.SetTextAlignment(TextAlignment.RIGHT);
//para.SetBaseDirection(BaseDirection.RIGHT_TO_LEFT);
table.AddCell(index.ToString());
table.AddCell(para);
index++;
}
doc.Add(table);
doc.Close();
Process.Start(filename);
}
Set font function
void SetFont(Document doc)
{
FontSet _defaultFontSet = new FontSet();
var fontFolders = Environment.GetFolderPath(Environment.SpecialFolder.Fonts);
_defaultFontSet.AddFont(System.IO.Path.Combine(fontFolders, "arial.ttf"), PdfEncodings.IDENTITY_H);
_defaultFontSet.AddFont(System.IO.Path.Combine(fontFolders, "arialbd.ttf"), PdfEncodings.IDENTITY_H);
doc.SetFontProvider(new FontProvider(_defaultFontSet));
doc.SetProperty(Property.FONT, new String[] { "MyFontFamilyName" });
//doc.SetProperty(Property.BASE_DIRECTION, BaseDirection.RIGHT_TO_LEFT);
}
I'm not sure to where should we set the text direction to print RTL.

OpenXML ComplexScript font not rendering

I have the following program that generates an example word document:
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
namespace OpenXmlExample
{
class Program
{
static void Main(string[] args)
{
string filePath = #"C:\Users\[Redacted]\Desktop\OpenXmlExample.docx";
using (WordprocessingDocument document = WordprocessingDocument.Create(filePath, WordprocessingDocumentType.Document))
{
// Create main part and body of document
MainDocumentPart mainPart = document.AddMainDocumentPart();
mainPart.Document = new Document();
Body body = mainPart.Document.AppendChild(new Body());
// Prototype code for generation of the document title
Paragraph paragraph = new Paragraph();
ParagraphProperties pPr = new ParagraphProperties
{
Justification = new Justification { Val = JustificationValues.Center }
};
RunProperties rPr = new RunProperties
{
RunFonts = new RunFonts { ComplexScript = new StringValue("Arial") },
Bold = new Bold { Val = true },
Caps = new Caps { Val = true },
FontSize = new FontSize { Val = "32" },
FontSizeComplexScript = new FontSizeComplexScript { Val = "36" }
};
Text t = new Text("Example Document");
Run r = new Run();
r.Append((OpenXmlElement) rPr.Clone());
r.Append(t);
pPr.Append((OpenXmlElement) rPr.Clone());
paragraph.Append(pPr);
paragraph.Append(r);
body.Append(paragraph);
}
}
}
}
It seems to be working just fine. "EXAMPLE DOCUMENT" is rendered properly, bold and uppercase, with 16pt font. However, the ComplexScript = new StringValue("Arial") part doesn't seem to be working. The text is just rendered in the default font. Can anyone help me to understand if I'm doing something incorrectly? It seems to work if I set the Ascii property to Arial, but I would like it to be generated as a <w:rFonts w:cs="Arial"/> tag.
For a single run, 4 different fonts can be configured.
The use of each of these fonts shall be determined by the Unicode character values of the run content.
ASCII for characters in the Unicode range (U+0000-U+007F).
Complex Script for characters in a complex script Unicode range, eg. Arabic text.
East Asian for characters in an East Asian Unicode range, eg. Japanese.
High ANSI for characters in a Unicode range which does not fall into one of the other categories.
The characters in 'EXAMPLE DOCUMENT' all fall within the ASCII group and will therefore have font of the corresponding group applied.
More details at MSDN and Office Open XML.

Draw checked box with itextsharp

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)));

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;
}
}
}

convert font to string and back again

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>);

Categories

Resources