How to display ✔ in PDF using iTextSharp? - c#

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;

Related

C#: Unable to assign Image to PictureBox image source path from text file in winforms

I'm trying to display image in a PictureBox dynamically. Image source is stored in a text file. When reading the image path from the file it keep showing image error symbol. When I include the path in the code it works.
Text file line sample
F01,Nasi Lemak,RM 2,#"Food\NasiLemak.jpg"
public void readData()
{
try
{
int i = 0;
foreach (string line in File.ReadAllLines("food.txt"))
{
string[] parts = line.Split(',');
foreach (string part in parts)
{
Console.WriteLine("{0}:{1}", i, part);
{
Label LblFId = new Label();
{
//LblFId.AutoSize = true;
LblFId.Size = new System.Drawing.Size(70, 20);
}
Label LblFName = new Label();
{
LblFName.Size = new System.Drawing.Size(70, 20);
}
Label LblFPrice = new Label();
{
LblFPrice.Size = new System.Drawing.Size(70, 20);
}
PictureBox foodPicBox = new PictureBox();
{
foodPicBox.Size = new System.Drawing.Size(200, 200);
foodPicBox.SizeMode = PictureBoxSizeMode.StretchImage;
foodPicBox.BorderStyle = BorderStyle.Fixed3D;
}
Panel fPanel = new Panel();
LblFId.Text = parts[0];
LblFName.Text = parts[1];
LblFPrice.Text = parts[2];
foodPicBox.ImageLocation = parts[3];
fPanel.Controls.Add(LblFId);
fPanel.Controls.Add(LblFName);
fPanel.Controls.Add(LblFPrice);
fPanel.Controls.Add(foodPicBox);
foodFlow.Controls.Add(fPanel);
}
}
i++;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
The problem is in the path from the text file
#"Food\NasiLemak.jpg"
This should be saved like without the # and the "
Food\NasiLemak.jpg
Or you should write more code to remove those symbols like this
foodPicBox.ImageLocation = parts[3].Replace("#", "").Replace("\"", "");
This will remove the samples and your problem would be solved.
You need also to close foreach statment at this point
foreach (string part in parts)
{Console.WriteLine("{0}:{1}", i, part);}

How to display "Times New Roman font" in PDF?

I want to change the font of the content to TIMES NEW roman
iTextSharp.text.html.simpleparser.HTMLWorker hw = new iTextSharp.text.html.simpleparser.HTMLWorker(textSharpDocument);
#pragma warning restore 612, 618
String[] content = letterContent.Split(new string[] { AppUtil.GetAppSettings(AppConfigKey.ReceiptLetterPDFSeparator) }, StringSplitOptions.None);
//Add Content to File
if (content.Length > AppConstants.DEFAULT_PARAMETER_ZERO)
{
string imageFolderPath = AppUtil.GetAppSettings(AppConfigKey.UploadedImageFolderPath);
for (int counter = 0; counter < content.Length - 1; counter++)
{
textSharpDocument.Add(new Paragraph());
if (!String.IsNullOrEmpty(imageUrlList[counter]))
{
string imageURL = imageFolderPath + imageUrlList[counter];
textSharpDocument.Add(new Paragraph());
string imagePath = AppUtil.GetAppSettings(AppConfigKey.ParticipantCommunicationFilePhysicalPath) + imageUrlList[counter];
imagePath = imagePath.Replace(#"\", "/");
if (File.Exists(imagePath))
{
iTextSharp.text.Image png = iTextSharp.text.Image.GetInstance(imageURL);
imageLocationIDs[counter] = imageLocationIDs[counter] != null ? AppUtil.ConvertToInt(imageLocationIDs[counter], AppConstants.DEFAULT_PARAMETER_ONE) : AppUtil.ConvertEnumToInt(AppImageLocation.Left);
if (imageLocationIDs[counter] == AppUtil.ConvertEnumToInt(AppImageLocation.Left))
png.Alignment = iTextSharp.text.Image.ALIGN_LEFT;
if (imageLocationIDs[counter] == AppUtil.ConvertEnumToInt(AppImageLocation.Right))
png.Alignment = iTextSharp.text.Image.ALIGN_RIGHT;
if (imageLocationIDs[counter] == AppUtil.ConvertEnumToInt(AppImageLocation.Center))
png.Alignment = iTextSharp.text.Image.ALIGN_CENTER;
textSharpDocument.Add(png);
}
}
hw.Parse(new StringReader(content[counter]));
hw.EndElement("</html>");
hw.Parse(new StringReader(AppUtil.GetAppSettings(AppConfigKey.ReceiptLetterPDFSeparator)));
}
}
You could set at basefont something like this
BaseFont bfTimes = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false);
Font times = new Font(bfTimes, 12, Font.ITALIC, Color.BLACK);
Document doc = new Document();
PdfWriter.GetInstance(doc, new FileStream("c:\\Font.pdf", FileMode.Create));
doc.Open();
doc.Add(new Paragraph("This is a test using Times Roman", times));
doc.Close();

Adding a Table into the Footer of a PDF

After creating a PDF from HTML, I need to add a Footer to each page. The Footer is going to be a single-row, three-column table, with the left cell being an external reference ID, the center being a "Page X of Y", and the right being a date stamp. I have no experience with iTextSharp, but after reading various posts I created the following PageEventHandler
UPDATED CODE
public class FooterEvent : PdfPageEventHelper
{
PdfContentByte cb;
#region Properties
private string _FooterLeft;
public string FooterLeft
{
get { return _FooterLeft; }
set { _FooterLeft = value; }
}
private string _FooterCenter;
public string FooterCenter
{
get { return _FooterCenter; }
set { _FooterCenter = value; }
}
private string _FooterRight;
public string FooterRight
{
get { return _FooterRight; }
set { _FooterRight = value; }
}
private Font _FooterFont;
public Font FooterFont
{
get { return _FooterFont; }
set { _FooterFont = value; }
}
#endregion
public override void OnEndPage(PdfWriter writer, Document document)
{
base.OnEndPage(writer, document);
Font font = new Font(Font.FontFamily.HELVETICA, 12, Font.NORMAL, BaseColor.BLACK);
PdfPTable FooterTable = new PdfPTable(3);
FooterTable.TotalWidth = document.PageSize.Width - document.LeftMargin - document.RightMargin;
PdfPCell FooterLeftCell = new PdfPCell(new Phrase(2, FooterLeft, FooterFont));
FooterLeftCell.HorizontalAlignment = Element.ALIGN_LEFT;
FooterLeftCell.VerticalAlignment = Element.ALIGN_CENTER;
FooterLeftCell.Border = 0;
FooterTable.AddCell(FooterLeftCell);
PdfPCell FooterCenterCell = new PdfPCell(new Phrase(2, FooterCenter, FooterFont));
FooterCenterCell.HorizontalAlignment = Element.ALIGN_CENTER;
FooterCenterCell.VerticalAlignment = Element.ALIGN_CENTER;
FooterCenterCell.Border = 0;
FooterTable.AddCell(FooterCenterCell);
PdfPCell FooterRightCell = new PdfPCell(new Phrase(2, FooterRight, FooterFont));
FooterRightCell.HorizontalAlignment = Element.ALIGN_RIGHT;
FooterRightCell.VerticalAlignment = Element.ALIGN_CENTER;
FooterRightCell.Border = 0;
FooterTable.AddCell(FooterRightCell);
FooterTable.WriteSelectedRows(0, -1, document.LeftMargin, document.BottomMargin, cb);
}
}
ADDED RESPONSE
After editing my PageEvent, I'm still having issues. It's come to mind that I'm probably having issues with calling the PageEvent and adding it to the PDF (no experience with iTextSharp). Below is my attempt to add the Footer to an existing PDF that has been passed as byte[].
byte[] output = null;
string identifier = id;
string time = DateTime.Now.ToString();
string page = null;
PdfReader reader = new PdfReader(original);
int n = reader.NumberOfPages;
try
{
using (MemoryStream ms = new MemoryStream())
{
using (Document doc = new Document(PageSize.LETTER, 100, 100, 100, 100))
{
using (PdfWriter writer = PdfWriter.GetInstance(doc, ms))
{
FooterEvent footer = new FooterEvent();
writer.PageEvent = footer;
footer.FooterFont = FontFactory.GetFont(BaseFont.HELVETICA, 12, BaseColor.BLACK);
doc.Open();
for (int i = 1; i < n + 1; ++i)
{
doc.NewPage();
page = "Page " + i + " of " + n;
footer.FooterLeft = identifier;
footer.FooterCenter = page;
footer.FooterRight = time;
doc.Add(new Paragraph(reader.GetPageContent(i).ToString()));
//Probably wrong. Trying to add contents from each page in original PDF
}
doc.Close();
}
}
output = ms.ToArray();
}
}
catch (Exception ex)
{
//Some Message added later
}
return output;
Any help is appreciated. Thanks in advance.
Try this, its working for me:
FooterTable.WriteSelectedRows(0, -1, document.LeftMargin, FooterTable.TotalHeight, cb);
Check this post
Header, footer and large tables with iTextSharp
You wrote:
FooterTable.WriteSelectedRows(0, 0, document.LeftMargin, document.RightMargin, cb);
However, the method is:
FooterTable.WriteSelectedRows(rowStart, rowEnd, x, y, cb);
Which means that you're asking to write a selection of rows starting with row 0 and ending with row 0, or: you're asking to write not a single row.
Moreover, you provide an x value instead of a y value. Change that line into:
FooterTable.WriteSelectedRows(0, -1, document.LeftMargin, document.BottomMargin, cb);

How to do to display Chinese font in pdf using iTextSharp?

In the following code , chinese font( contained html text) doesnot display in pdf generated.
I also try styles and font in this method. Please help to solve this problem.
Thanks in advance to all.
public static bool GeneratedPDF(string strHTMLText, string filename, string action, string rpttype)
{
bool blnReturn = false;
string fontpath = HttpContext.Current.Server.MapPath("~/files/fonts/");
string filepath = HttpContext.Current.Server.MapPath("~/files/pdf/");
BaseFont customfont = BaseFont.CreateFont(fontpath + "simhei.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
Font font = new Font(customfont, 12);
//List<iTextSharp.text.IElement> htmlarraylist = iTextSharp.text.html.simpleparser.HTMLWorker.ParseToList(new System.IO.StringReader(strHTMLText), null);
iTextSharp.text.Document document = new iTextSharp.text.Document();
if (rpttype.Trim().ToUpper() == "REPORT")
document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A2.Rotate());
else if (rpttype.Trim().ToUpper() == "GRID")
document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4.Rotate());
else
document = new iTextSharp.text.Document(iTextSharp.text.PageSize.LETTER);
iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, new FileStream(filepath + "\\" + filename, FileMode.Create));
document.Open();
iTextSharp.text.html.simpleparser.StyleSheet styles = new iTextSharp.text.html.simpleparser.StyleSheet();
styles.LoadTagStyle("body", "font-family", "verdana");
styles.LoadStyle("body", "font-size", "5px");
List<iTextSharp.text.IElement> htmlarraylist = iTextSharp.text.html.simpleparser.HTMLWorker.ParseToList(new System.IO.StringReader(strHTMLText), styles);
for (int k = 0; k < htmlarraylist.Count; k++)
{
document.Add((IElement)htmlarraylist[k]);
}
iTextSharp.text.Paragraph p = new iTextSharp.text.Paragraph();
p.InsertRange(0, htmlarraylist);
p.Font = font; // font does not work
document.Add(p);
document.Close();
blnReturn = true;
return blnReturn;
}
You set the StyleSheet wrong. It should be something like this:
string html = #"
<html><body>
<p>使用iText做PDF文件輸出</p>
<p>使用iText做PDF文件輸出</p>
<p>使用iText做PDF文件輸出</p>
<p>使用iText做PDF文件輸出</p>
<p>使用iText做PDF文件輸出</p>
</body></html>
";
FontFactory.Register("c:/windows/fonts/ARIALUNI.TTF");
StyleSheet style = new StyleSheet();
style.LoadTagStyle("body", "face", "Arial Unicode MS");
style.LoadTagStyle("body", "encoding", BaseFont.IDENTITY_H);
using (Document document = new Document()) {
PdfWriter writer = PdfWriter.GetInstance(
document, Response.OutputStream
);
document.Open();
foreach(IElement element in HTMLWorker.ParseToList(
new StringReader(html.ToString()), style))
{
document.Add(element);
}
}
You need to change the third parameter of LoadTagStyle() above to the correct name of the specific font you're using. In other words, replace "Arial Unicode MS" above with the name/value for your font. Or you can use the font above too.

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