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();
Related
I am developing a web application and one of its features is to generate a multiple certificate in a PDF file. There's no problem in generating a pdf but what I want to happen when generating a multiple certificate is to be in one pdf file only. I am just a beginner so I don't have much idea on doing that. Below is my code for generating a certificate. Thanks in advance!
protected void btnPdf_Click(object sender, EventArgs e)
{
string now = DateTime.Now.ToString("MM-dd-yyyy");
foreach (GridViewRow row in TraineeGrid.Rows)
{
CheckBox chk = (CheckBox)row.FindControl("chkSelect");
if (chk.Checked)
{
Label varName = (Label)row.FindControl("lbName");
string name = varName.Text;
Label varCourse = (Label)row.FindControl("lbCourse");
string course = varCourse.Text;
Label varCertNum = (Label)row.FindControl("lbCertNum");
string certNumber = varCertNum.Text;
Label varEndDate = (Label)row.FindControl("lbEndDate");
string endDate = varEndDate.Text;
DateTime date = DateTime.Parse(endDate);
string finalEDate = date.ToString("MMMM dd, yyyy");
Label varStartDate = (Label)row.FindControl("lbStartDate");
string startDate = varStartDate.Text;
DateTime date1 = DateTime.Parse(startDate);
string dateFileName = date1.ToString("MM-dd-yyyy");
string finalSDate = date1.ToString("MMMM dd, yyyy");
var checkedBoxes = TraineeGrid.Controls.OfType<CheckBox>().Count(c => chk.Checked);
try
{
Directory.CreateDirectory("D:\\Intern\\BASSWeb\\Certificates\\"+now+"\\");
string inputCertificate = "D:\\Intern\\BASSWeb\\Certificates\\CertificateLayout.pdf";
string outputCertificate = "D:\\Intern\\BASSWeb\\Certificates\\"+now+"\\"+name+"_" + course + "_"+dateFileName+".pdf";
// open the reader
PdfReader reader = new PdfReader(inputCertificate);
Rectangle size = reader.GetPageSizeWithRotation(1);
Document document = new Document();
// open the writer
FileStream fs = new FileStream(outputCertificate, FileMode.Create, FileAccess.Write);
PdfStamper stamp = new PdfStamper(reader, fs);
PdfContentByte cb = stamp.GetOverContent(1);
var pageSize = reader.GetPageSize(1);
ColumnText ct = new ColumnText(cb);
PdfCopy copy = new PdfCopy(document, fs);
document.Open();
Font font = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 45, iTextSharp.text.Color.BLACK);
ct.SetSimpleColumn(10f, 100f, 600f, 325f);
Paragraph certText = new Paragraph(new Phrase(20, name, font));
ct.AddElement(certText);
ct.Go();
Font font2 = FontFactory.GetFont(FontFactory.HELVETICA_OBLIQUE, 19, iTextSharp.text.Color.GRAY);
ct.SetSimpleColumn(10f, 100f, 600f, 390f);
certText = new Paragraph(new Phrase("This is to certify that ", font2));
ct.AddElement(certText);
ct.Go();
ct.SetSimpleColumn(10f, 100f, 500f, 297f);
certText = new Paragraph(new Phrase("has successfully completed the " + course + " at BASS Philippines RHQ", font2));
ct.AddElement(certText);
ct.Go();
ct.SetSimpleColumn(10f, 100f, 500f, 240f);
certText = new Paragraph(new Phrase("From: " + finalSDate + "", font2));
ct.AddElement(certText);
ct.Go();
ct.SetSimpleColumn(10f, 100f, 500f, 216f);
certText = new Paragraph(new Phrase("To: " + finalEDate + "", font2));
ct.AddElement(certText);
ct.Go();
Font font3 = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 10, iTextSharp.text.Color.BLACK);
ct.SetSimpleColumn(10f, 100f, 500f, 192f);
certText = new Paragraph(new Phrase("Certificate Number: " + certNumber + "", font2));
ct.AddElement(certText);
ct.Go();
stamp.Close();
reader.Close();
fs.Close();
Process.Start(outputCertificate);
chk.Checked = false;
}
catch (Exception ex)
{
string errorMessage = "alert(\"ERROR: "+ ex.Message.ToString() +" \");";
ScriptManager.RegisterStartupScript(this, GetType(), "ServerControlScript", errorMessage, true);
}
}
}
}
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);
I have a class that build the content for my table of contents and that works, fine and dandy.
Here's the code:
public void Build(string center,IDictionary<string,iTextSharp.text.Image> images)
{
iTextSharp.text.Image image = null;
XPathDocument rapportTekst = new XPathDocument(Application.StartupPath + #"..\..\..\RapportTemplates\RapportTekst.xml");
XPathNavigator nav = rapportTekst.CreateNavigator();
XPathNodeIterator iter;
iter = nav.Select("//dokument/brevhoved");
iter.MoveNext();
var logo = iTextSharp.text.Image.GetInstance(iter.Current.GetAttribute("url", ""));
iter = nav.Select("//dokument/gem_som");
iter.MoveNext();
string outputPath = iter.Current.GetAttribute("url", "")+center+".pdf";
iter = nav.Select("//dokument/titel");
iter.MoveNext();
this.titel = center;
Document document = new Document(PageSize.A4, 30, 30, 100, 30);
var outputStream = new FileStream(outputPath, FileMode.Create);
var pdfWriter = PdfWriter.GetInstance(document, outputStream);
pdfWriter.SetLinearPageMode();
var pageEventHandler = new PageEventHandler();
pageEventHandler.ImageHeader = logo;
pdfWriter.PageEvent = pageEventHandler;
DateTime timeOfReport = DateTime.Now.AddMonths(-1);
pageWidth = document.PageSize.Width - (document.LeftMargin + document.RightMargin);
pageHight = document.PageSize.Height - (document.TopMargin + document.BottomMargin);
document.Open();
var title = new Paragraph(titel, titleFont);
title.Alignment = Element.ALIGN_CENTER;
document.Add(title);
List<TableOfContentsEntry> _contentsTable = new List<TableOfContentsEntry>();
nav.MoveToRoot();
iter = nav.Select("//dokument/indhold/*");
Chapter chapter = null;
int chapterCount = 1;
while (iter.MoveNext())
{
_contentsTable.Add(new TableOfContentsEntry("Test", pdfWriter.CurrentPageNumber.ToString()));
XPathNodeIterator innerIter = iter.Current.SelectChildren(XPathNodeType.All);
chapter = new Chapter("test", chapterCount);
while(innerIter.MoveNext())
{
if (innerIter.Current.Name.ToString().ToLower().Equals("billede"))
{
image = images[innerIter.Current.GetAttribute("navn", "")];
image.Alignment = Image.ALIGN_CENTER;
image.ScaleToFit(pageWidth, pageHight);
chapter.Add(image);
}
if (innerIter.Current.Name.ToString().ToLower().Equals("sektion"))
{
string line = "";
var afsnit = new Paragraph();
line += (innerIter.Current.GetAttribute("id", "") + " ");
innerIter.Current.MoveToFirstChild();
line += innerIter.Current.Value;
afsnit.Add(line);
innerIter.Current.MoveToNext();
afsnit.Add(innerIter.Current.Value);
chapter.Add(afsnit);
}
}
chapterCount++;
document.Add(chapter);
}
document = CreateTableOfContents(document, pdfWriter, _contentsTable);
document.Close();
}
I'm then calling the method CreateTableOfContents(), and as such it is doing what it is supposed to do. Here's the code for the method:
public Document CreateTableOfContents(Document _doc, PdfWriter _pdfWriter, List<TableOfContentsEntry> _contentsTable)
{
_doc.NewPage();
_doc.Add(new Paragraph("Table of Contents", FontFactory.GetFont("Arial", 18, Font.BOLD)));
_doc.Add(new Chunk(Environment.NewLine));
PdfPTable _pdfContentsTable = new PdfPTable(2);
foreach (TableOfContentsEntry content in _contentsTable)
{
PdfPCell nameCell = new PdfPCell(_pdfContentsTable);
nameCell.Border = Rectangle.NO_BORDER;
nameCell.Padding = 6f;
nameCell.Phrase = new Phrase(content.Title);
_pdfContentsTable.AddCell(nameCell);
PdfPCell pageCell = new PdfPCell(_pdfContentsTable);
pageCell.Border = Rectangle.NO_BORDER;
pageCell.Padding = 6f;
pageCell.Phrase = new Phrase(content.Page);
_pdfContentsTable.AddCell(pageCell);
}
_doc.Add(_pdfContentsTable);
_doc.Add(new Chunk(Environment.NewLine));
/** Reorder pages so that TOC will will be the second page in the doc
* right after the title page**/
int toc = _pdfWriter.PageNumber - 1;
int total = _pdfWriter.ReorderPages(null);
int[] order = new int[total];
for (int i = 0; i < total; i++)
{
if (i == 0)
{
order[i] = 1;
}
else if (i == 1)
{
order[i] = toc;
}
else
{
order[i] = i;
}
}
_pdfWriter.ReorderPages(order);
return _doc;
}
The problem is however. I want to insert a page break before the table of contents, for the sake of reordering the pages, so that the table of contents is the first page, naturally. But the output of the pdf-file is not right.
Here's a picture of what it looks like:
It seems like the _doc.NewPage() in the CreateTableOfContents() method does not execute correctly. Meaning that the image and the table of contents is still on the same page when the method starts the reordering of pages.
EDIT: To clarify the above, the _doc.NewPage() gets executed, but the blank page is added after the picture and the table of contents.
I've read a couple of places that this could be because one is trying to insert a new page after an already blank page. But this is not the case.
I'll just link to the pdf files aswell, to better illustrate the problem.
The pdf with table of contents: with table of contents
The pdf without table of contents: without table of contents
Thank you in advance for your help :)
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;
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.