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);
}
}
}
}
Related
I am using PDFsharp to create PDF files. My problem is when I lay down the lines of text to the PDF I get a single line only. So naturally, all of the text that fits on a the first line is visible since the other text has overflowed out of bounds.
Please see my code below:
private void createPdf2()
{
var title = DateTime.Now.ToString("MM-dd-yyyy-hh-m-ss") + "-" + txtPlazaNumber.Text + "-" + txtLaneNumber.Text;
var now = DateTime.Now;
var sb = new StringBuilder();
sb.AppendLine("Date: " + DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss")).AppendLine(Environment.NewLine);
sb.AppendLine("Plaza Number: " + txtPlazaNumber.Text).AppendLine(Environment.NewLine);
sb.AppendLine("Lane Number: " + txtLaneNumber.Text).AppendLine(Environment.NewLine);
sb.AppendLine("RFID IP Address: " + txtRfidIpAddress.Text).AppendLine(Environment.NewLine);
sb.AppendLine("RFID Port: " + nRfidPort.Text).AppendLine(Environment.NewLine);
sb.AppendLine("TFI IP Address: " + txtTfiIpAddress.Text).AppendLine(Environment.NewLine);
sb.AppendLine("QR Port: " + nQrPort.Text).AppendLine(Environment.NewLine);
sb.AppendLine("Passed Tests").AppendLine();
foreach(var p in passedList)
{
sb.AppendLine("\t").Append(p.Trim()).AppendLine();
}
sb.AppendLine("Failed Tests").AppendLine();
foreach(var f in failedList)
{
sb.AppendLine("\f").Append(f.Trim()).AppendLine();
}
PdfDocument pdf = new PdfDocument();
pdf.Info.Title = title;
PdfPage pdfPage = pdf.AddPage();
XGraphics graph = XGraphics.FromPdfPage(pdfPage);
XFont font = new XFont("Verdana", 12, XFontStyle.Regular);
graph.DrawString(sb.ToString(), font, XBrushes.Black, new XRect(0, 0, pdfPage.Width.Point, pdfPage.Height.Point), XStringFormats.TopLeft);
string pdfFilename = title + ".pdf";
pdf.Save(pdfFilename);
}
This is a little bit trickier to work around. You need an XTextFormatter, a XRect for the region which is available for the layouter and then call DrawString(…) on the formatter instead of the XGraphics object:
var formatter = new XTextFormatter(pageGraphics);
var layoutRectangle = new XRect(10, 10, page.Width, page.Height);
formatter.DrawString("Hello\r\nWorld", arial, XBrushes.Black, layoutRectangle);
http://development.wellisolutions.de/generating-pdf-with-pdfsharp/
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();
i have a tree view in which there are certain set of document list and another grid having patient details. what i need to do is when we select docs from treeview (select multiple..checkbox enabled) and patients from grid and click on a button should create all the documents using ITEXTSHARP.that is multiple documents are created. I tried it like this,
on button click
foreach( TreeNode node in TreeView1.Nodes)
{
if (node.ChildNodes.Count>0)
{
for(int i=0 ;i<(node.ChildNodes.Count);i++)
{
if (node.ChildNodes[i].Checked==true)
{
string nodevalue = node.ChildNodes[i].Value.ToString();
if (nodevalue=="3")
{
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox chk = row.FindControl("CheckBox1") as CheckBox;
if (chk.Checked)
{
Label lbl_name = row.FindControl("Label1") as Label;
Label lbl_dob = row.FindControl("Label3") as Label;
pdf_abcd(lbl_name.Text.Trim(), lbl_dob.Text.Trim());
}
}
}
}
}
}
}
}
}
}
and the pdf_abcd function is
public void pdf_abcd(string name, string dob)
{
Phrase hospt_name = new Phrase();
Phrase slogan = new Phrase();
Phrase address = new Phrase();
Phrase pat_name = new Phrase();
Phrase phr_Consent_For_Treatment = new Phrase();
Phrase phr_Professional_Care = new Phrase();
Phrase phr_Consent_For_Treatment_head = new Phrase();
Phrase phr_Professional_Care_head = new Phrase();
Phrase phr_Nursing_Care = new Phrase();
Phrase phr_Nursing_Care_head = new Phrase();
Phrase phr_signtur_line = new Phrase();
Phrase phr_signtur_bigfont = new Phrase();
Phrase phr_signtur_smallfont_line = new Phrase();
Phrase phr_signtur_date_line = new Phrase();
Phrase phr_relationship = new Phrase();
Phrase phr_witness = new Phrase();
Phrase phr_paitient_name = new Phrase();
Phrase phr_paitient_dob = new Phrase();
Paragraph para = new Paragraph();
Paragraph pat_det = new Paragraph();
Paragraph Consent_For_Treatment = new Paragraph();
Paragraph Professional_Care = new Paragraph();
Paragraph Nursing_Care = new Paragraph();
Paragraph Consent_For_Treatment_head = new Paragraph();
Paragraph Professional_Care_head = new Paragraph();
Paragraph Nursing_Care_head = new Paragraph();
Paragraph signatur = new Paragraph();
Paragraph relationship = new Paragraph();
Paragraph witness = new Paragraph();
Paragraph paitient_name_dob = new Paragraph();
Font fntNormalText = FontFactory.GetFont(FontFactory.TIMES, 12, iTextSharp.text.Font.NORMAL);
Font fntBoldText = FontFactory.GetFont(FontFactory.TIMES, 12, Font.BOLD);
Font fntsmallText = FontFactory.GetFont(FontFactory.TIMES, 8, Font.NORMAL);
Font fntverysmallText = FontFactory.GetFont(FontFactory.TIMES, 6, Font.NORMAL);
Font fntBoldheadingText = FontFactory.GetFont(FontFactory.TIMES, 10, Font.BOLD);
Font fntparaText = FontFactory.GetFont(FontFactory.TIMES, 10, Font.NORMAL);
hospt_name = new Phrase("abcd", fntBoldText);
slogan = new Phrase(System.Environment.NewLine + "Quality health care here at home", fntNormalText);
address = new Phrase(System.Environment.NewLine + "P.O. Box 677", fntsmallText);
para.Add(hospt_name);
para.Add(slogan);
para.Add(address);
phr_paitient_name = new Phrase(System.Environment.NewLine + System.Environment.NewLine + System.Environment.NewLine + System.Environment.NewLine + name + " " + dob, fntNormalText);
pat_name = new Phrase(System.Environment.NewLine + "__________________________________________________________ _______________________________" + System.Environment.NewLine + "Patient's Name D.O.B.", fntsmallText);
pat_det.Add(phr_paitient_name);
pat_det.Add(pat_name);
phr_Consent_For_Treatment_head = new Phrase(System.Environment.NewLine + "Consent For Treatment", fntBoldheadingText);
Consent_For_Treatment_head.Add(phr_Consent_For_Treatment_head);
phr_Consent_For_Treatment = new Phrase("The undersigned consents to procedures and treatments which may be performed during this hospitalization or on an outpatient or emergency basis, including but not limited to anesthesia, laboratory procedures, medical or surgical treatments, x-ray examination, or other services rendered under the general and specific instructions of the physician, physician's assistant, nurse practitioner or Designee. In order to manage accidental exposure of a health care worker to blood or other bodily fluids, the undersigned further consents to such testing; including but not limited to AIDS, TB, Syphilis, and Hepatitis testing, as may be necessary for protection of the heath care worker.", fntparaText);
Consent_For_Treatment.Add(phr_Consent_For_Treatment);
phr_Professional_Care_head = new Phrase(System.Environment.NewLine + "Professional Care", fntBoldheadingText);
Professional_Care_head.Add(phr_Professional_Care_head);
phr_Professional_Care = new Phrase("The attending physician, usually selected by the patient except under unusual or emergency circumstances, is the professional who arranges for the patient's care and treatment Doctors of medicine, including anesthesia provider, pathologists, radiologists, emergency room physicians, osteopathy, podiatry, etc., are independent contractors and are not employees of Val Verde Regional Medical Center. You will receive a separate bill from the physician/anesthesia provider.", fntparaText);
Professional_Care.Add(phr_Professional_Care);
phr_Nursing_Care_head = new Phrase(System.Environment.NewLine + "Nursing Care", fntBoldheadingText);
Nursing_Care_head.Add(phr_Nursing_Care_head);
phr_Nursing_Care = new Phrase("The hospital provides general nursing care. Private duty nursing must be arranged by the patient's representative. The hospital is not responsible for and is released from all liabilities for failure to provide such care.", fntparaText);
Nursing_Care.Add(phr_Nursing_Care);
phr_signtur_line = new Phrase(System.Environment.NewLine + System.Environment.NewLine + "__________________________________________________________________________________________ ________________", fntsmallText);
phr_signtur_bigfont = new Phrase(System.Environment.NewLine + "Signature of Patient/Responsible Party/Patient Representative", fntNormalText);
phr_signtur_smallfont_line = new Phrase("(If patient unable to sign)", fntverysmallText);
phr_signtur_date_line = new Phrase(" Date ", fntNormalText);
signatur.Add(phr_signtur_line);
signatur.Add(phr_signtur_bigfont);
signatur.Add(phr_signtur_smallfont_line);
signatur.Add(phr_signtur_date_line);
phr_relationship = new Phrase(System.Environment.NewLine + "______________________________________________________________" + System.Environment.NewLine + "Relationship to patient", fntNormalText);
relationship.Add(phr_relationship);
phr_witness = new Phrase(System.Environment.NewLine + "___________________________________ __________" + System.Environment.NewLine + "Signature of Witness Date", fntNormalText);
witness.Add(phr_witness);
Document Doc = new Document(PageSize.A4, 0, 0, 25, 50);
PdfWriter.GetInstance(Doc, new FileStream(Server.MapPath("~/abcd/abcd.pdf"), FileMode.Create));
Doc.Open();
PdfPTable table = new PdfPTable(1);
table.TotalWidth = 500f;
table.LockedWidth = true;
iTextSharp.text.Image logo = iTextSharp.text.Image.GetInstance("~/img/abcd.png");
logo.ScaleAbsolute(30, 30);
PdfPCell image_header = new PdfPCell(logo);
image_header.HorizontalAlignment = Element.ALIGN_CENTER;
image_header.BorderWidth = 0;
table.AddCell(image_header);
PdfPCell header = new PdfPCell(para);
header.HorizontalAlignment = Element.ALIGN_CENTER;
header.Colspan = 4;
header.BorderWidth = 0;
table.AddCell(header);
PdfPCell patient = new PdfPCell(pat_det);
patient.BorderWidth = 0;
table.AddCell(patient);
//PdfPCell patientname = new PdfPCell(new Phrase(System.Environment.NewLine + System.Environment.NewLine + "Patient's Name D.O.B."));
//patientname.BorderWidth = 0;
//table.AddCell(patientname);
PdfPCell head_treatment = new PdfPCell(new Phrase(Consent_For_Treatment_head));
head_treatment.BorderWidth = 0;
table.AddCell(head_treatment);
PdfPCell treatment_content = new PdfPCell(Consent_For_Treatment);
treatment_content.BorderWidth = 0;
table.AddCell(treatment_content);
PdfPCell head_profcare = new PdfPCell(Professional_Care_head);
head_profcare.BorderWidth = 0;
table.AddCell(head_profcare);
PdfPCell profcare_content = new PdfPCell(Professional_Care);
profcare_content.BorderWidth = 0;
table.AddCell(profcare_content);
PdfPCell head_nursing = new PdfPCell(Nursing_Care_head);
head_nursing.BorderWidth = 0;
table.AddCell(head_nursing);
PdfPCell nursing_content = new PdfPCell(Nursing_Care);
nursing_content.BorderWidth = 0;
table.AddCell(nursing_content);
PdfPCell sig = new PdfPCell(signatur);
sig.BorderWidth = 0;
table.AddCell(sig);
PdfPCell raltntopatient = new PdfPCell(relationship);
raltntopatient.BorderWidth = 0;
table.AddCell(raltntopatient);
PdfPCell witnesslines = new PdfPCell(witness);
witnesslines.BorderWidth = 0;
table.AddCell(witnesslines);
Doc.Add(table);
Doc.Close();
string path = Server.MapPath("~/abcd/Dabcd.pdf");
ShowPdf(path);
//Response.Redirect(Server.MapPath("~/abcd/abcd.pdf"));
}
and
private void ShowPdf(string strS)
{
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment; filename=" + strS);
Response.TransmitFile(strS);
Response.End();
Response.Flush();
Response.Clear();
}
but the system only down loads one doc..can anyone helpme
If you step back and ignore PDFs for a bit and concentrate on just HTTP requests and responses you should have your answer. When a browser makes an HTTP request (your button click) the server is allowed to send one and only one response. You're code is trying (unsuccessfully) to send multiple responses to the browser. The first time that Response.End is called the pipeline gets terminated actually and the rest of your code doesn't run.
The solution is to just make one giant PDF in one pass, make individual PDFs and merge them or create a zip file containing all of the PDFs.
I guess you should create a zip file that combines your PDF files
If you want to Open the file in new tab you have different Methods:
Method 1:
Response.Clear();
Response.ContentType = "application/pdf";
Response.AppendHeader("Content-Disposition", "attachment; filename=foo.pdf");
Response.TransmitFile(filePath);
Response.End();
Method 2:
Process process = new Process();
process.StartInfo.UseShellExecute = true;
process.StartInfo.FileName = outputPdfFile;
process.Start();
Hope this helps you!
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.