//private static IDictionary<string, string> Meta2Parameters(Texxtoor.BaseLibrary.Pdf2Epub.MetaData data) { // IDictionary<string, string> dictionary = new Dictionary<string, string>(); // dictionary.Add("##Author##", data.Author); // dictionary.Add("##Title##", data.Title); // dictionary.Add("##Date##", data.Date); // dictionary.Add("##UUID##", Guid.NewGuid().ToString()); // return dictionary; //} private static void ParseHtml(Document doc, StringReader html, StyleSheet css, List <Bitmap> images) { iTextSharp.text.Rectangle mySize = null; var htmlWorker = new HTMLWorker(doc); htmlWorker.SetStyleSheet(css); //htmlWorker.Parse(html); var objects = HTMLWorker.ParseToList(html, css); foreach (var element in objects) { doc.Add(element); } mySize = doc.PageSize; if (images.Count > 0) { for (int i = 0; i <= images.Count - 1; i++) { System.Drawing.Image mySource = (Bitmap)images[i]; iTextSharp.text.Image myImage = iTextSharp.text.Image.GetInstance(mySource, System.Drawing.Imaging.ImageFormat.Png); myImage.ScaleAbsolute(400, 300); doc.Add(myImage); } } }
public byte[] Render(string htmlText, string pageTitle) { byte[] renderedBuffer; // BaseFont baseFont = BaseFont.CreateFont(@"D:\ProfholodDevelop\ProfholodSite\ProfholodSite\fonts\arial.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); //iTextSharp.text.Font font = new iTextSharp.text.Font(baseFont, iTextSharp.text.Font.DEFAULTSIZE, iTextSharp.text.Font.NORMAL); string arialuniTff = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "arial.ttf"); //Register the font with iTextSharp iTextSharp.text.FontFactory.Register(arialuniTff); iTextSharp.text.html.simpleparser.StyleSheet ST = new iTextSharp.text.html.simpleparser.StyleSheet(); //Set the default body font to our registered font's internal name ST.LoadTagStyle(HtmlTags.BODY, HtmlTags.FACE, "Arial"); //Set the default encoding to support Unicode characters ST.LoadTagStyle(HtmlTags.BODY, HtmlTags.ENCODING, BaseFont.IDENTITY_H); Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory); using (var outputMemoryStream = new MemoryStream()) { using (var pdfDocument = new Document(PageSize.A4.Rotate(), HorizontalMargin, HorizontalMargin, VerticalMargin, VerticalMargin)) { PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDocument, outputMemoryStream); pdfWriter.CloseStream = false; pdfWriter.PageEvent = new PrintHeaderFooter { Title = pageTitle }; pdfDocument.Open(); using (var htmlViewReader = new StringReader(htmlText)) { using (var htmlWorker = new HTMLWorker(pdfDocument)) { htmlWorker.SetStyleSheet(ST); //string HJ = "Привет !!!!!!!!!!!!!!! Привет"; //Chunk c1 = new Chunk(HJ,font); // pdfDocument.Add(c1); htmlWorker.Parse(htmlViewReader); } } } renderedBuffer = new byte[outputMemoryStream.Position]; outputMemoryStream.Position = 0; outputMemoryStream.Read(renderedBuffer, 0, renderedBuffer.Length); } return(renderedBuffer); }
/// <summary> /// Hàm xuất Pdf /// </summary> /// <param name="titleExport">Tiêu đề xuất excel</param> /// <param name="nameFile">Tên file excel</param> /// <param name="infoExport">Những thông tin cần bổ sung vào file Export</param> /// <param name="columnGridViews">Cấu hình cột của gridview</param> /// <param name="rowspanTotal">Có dòng hiển thị header</param> /// <param name="list">Danh sách cần hiển thị</param> /// <param name="fromDate">Xem báo cáo từ ngày</param> /// <param name="toDate">Xem báo cáo đên ngày</param> /// <param name="exportDate">Ngày xuất báo cáo</param> /// <param name="isShowFooter">Có hiển thị Footer của GridView</param> /// <param name="tableSecond">Có table thứ 2 trong file xuất</param> public static void ExportPdf <T>(string titleExport, string nameFile, string infoExport, List <ColumnGridView> columnGridViews, int rowspanTotal, List <T> list, string fromDate, string toDate, string exportDate, bool isShowFooter = true, PdfPTable tableSecond = null) { var gridView = SettingGridView(columnGridViews, rowspanTotal, TypeExport.Pdf, list, isShowFooter); var ARIALUNI_TFF = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "ARIALUNI.TTF"); FontFactory.Register(ARIALUNI_TFF); var baseFont = BaseFont.CreateFont(ARIALUNI_TFF, BaseFont.IDENTITY_H, BaseFont.EMBEDDED); var table = SettingTablePdf(gridView, rowspanTotal, columnGridViews, baseFont, isShowFooter); HttpContext.Current.Response.ContentType = "application/pdf"; HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + nameFile + "_" + DateTime.Now.ToString("dd-MM-yyyy") + ".pdf"); HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache); var sw = new StringWriter(); var hw = new HtmlTextWriter(sw); hw.Write("<div style='font-size: 16px; font-weight: bold;'>" + "HỆ THỐNG AIRTIME MIX " + titleExport.ToUpper() + "</div>"); hw.Write("<div style='text-align:center;'>Từ ngày:" + fromDate + " đến ngày: " + toDate + "</div>"); hw.Write("<div style='text-align:center;'>Ngày xuất:" + exportDate + "</div>"); hw.Write(infoExport); hw.WriteBreak(); var pdfDoc = new Document(PageSize.A4.Rotate(), 15f, 15f, 15f, 10f); pdfDoc.SetMarginMirroring(false); var htmlparser = new HTMLWorker(pdfDoc); PdfWriter.GetInstance(pdfDoc, HttpContext.Current.Response.OutputStream); pdfDoc.Open(); var styles = new StyleSheet(); styles.LoadTagStyle("body", "encoding", BaseFont.IDENTITY_H); styles.LoadTagStyle("body", "font-family", "Arial Unicode MS"); styles.LoadTagStyle("body", "font-size", "10px"); htmlparser.SetStyleSheet(styles); htmlparser.Parse(new StringReader(sw.ToString())); if (tableSecond != null) { tableSecond.SpacingAfter = 10; pdfDoc.Add(tableSecond); } pdfDoc.Add(table); pdfDoc.Close(); HttpContext.Current.Response.Write(pdfDoc); HttpContext.Current.Response.End(); }
public static byte[] RenderPDFFromFile(string htmlPath, string fontPath, Dictionary <string, string> placeHolders /*, string pageTitle*/) { byte[] renderedBuffer; using (var outputMemoryStream = new MemoryStream()) { using (var pdfDocument = new Document(PageSize.A4, 10f, 10f, 10f, 10f)) { string htmlText = File.ReadAllText(htmlPath); foreach (var item in placeHolders) { if (htmlText.Contains(item.Key)) { htmlText = htmlText.Replace(item.Key, item.Value); } } FontFactory.Register(fontPath); PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDocument, outputMemoryStream); pdfWriter.CloseStream = false; //pdfWriter.PageEvent = new PrintHeaderFooter { Title = pageTitle }; pdfDocument.Open(); using (var htmlViewReader = new StringReader(htmlText)) { using (var htmlWorker = new HTMLWorker(pdfDocument)) { var styleSheet = new StyleSheet(); styleSheet.LoadTagStyle(HtmlTags.BODY, HtmlTags.FACE, "Roboto-Regular"); styleSheet.LoadTagStyle(HtmlTags.BODY, HtmlTags.ENCODING, BaseFont.IDENTITY_H); htmlWorker.SetStyleSheet(styleSheet); htmlWorker.Parse(htmlViewReader); } } } renderedBuffer = new byte[outputMemoryStream.Position]; outputMemoryStream.Position = 0; outputMemoryStream.Read(renderedBuffer, 0, renderedBuffer.Length); } return(renderedBuffer); }
public byte[] GetPDF(string pHTML) { byte[] bPDF = null; MemoryStream ms = new MemoryStream(); TextReader txtReader = new StringReader(pHTML); // 1: create object of a itextsharp document class Document doc = new Document(PageSize.A4, 25, 25, 25, 25); // 2: we create a itextsharp pdfwriter that listens to the document and directs a XML-stream to a file PdfWriter oPdfWriter = PdfWriter.GetInstance(doc, ms); // 3: we create a worker parse the document HTMLWorker htmlWorker = new HTMLWorker(doc); // 4: we open document and start the worker on the document doc.Open(); // step 4.1: register a unicode font and assign it an allias FontFactory.Register("C:\\Windows\\Fonts\\ARIALUNI.TTF", "arial unicode ms"); // step 4.2: create a style sheet and set the encoding to Identity-H StyleSheet ST = new StyleSheet(); ST.LoadTagStyle("body", "encoding", "Identity-H"); // step 4.3: assign the style sheet to the html parser htmlWorker.SetStyleSheet(ST); htmlWorker.StartDocument(); // 5: parse the html into the document htmlWorker.Parse(txtReader); // 6: close the document and the worker htmlWorker.EndDocument(); htmlWorker.Close(); doc.Close(); bPDF = ms.ToArray(); return(bPDF); }
public static byte[] GetPDF(string pHTML) { byte[] bPDF = null; MemoryStream ms = new MemoryStream(); TextReader txtReader = new StringReader(pHTML); // 1: create object of a itextsharp document class Document doc = new Document(PageSize.A4, 25, 25, 25, 25); // 2: we create a itextsharp pdfwriter that listens to the document and directs a XML-stream to a file PdfWriter oPdfWriter = PdfWriter.GetInstance(doc, ms); // 3: we create a worker parse the document HTMLWorker htmlWorker = new HTMLWorker(doc); StyleSheet styles = new StyleSheet(); //styles.LoadTagStyle("th", "face", "helvetica"); //styles.LoadTagStyle("span", "size", "10px"); //styles.LoadTagStyle("span", "face", "helvetica"); //styles.LoadTagStyle("td", "size", "10px"); styles.LoadTagStyle("body", HtmlTags.FONTFAMILY, "times-roman"); htmlWorker.SetStyleSheet(styles); // 4: we open document and start the worker on the document doc.Open(); htmlWorker.StartDocument(); // 5: parse the html into the document htmlWorker.Parse(txtReader); // 6: close the document and the worker htmlWorker.EndDocument(); htmlWorker.Close(); doc.Close(); bPDF = ms.ToArray(); return(bPDF); }
public byte[] RenderPDF(string htmlText /*, string pageTitle*/) { byte[] renderedBuffer; using (var outputMemoryStream = new MemoryStream()) { using (var pdfDocument = new Document(PageSize.A4, 10f, 10f, 10f, 10f)) { //string arialuniTff = Server.MapPath("~/fonts/ARIALUNI.TTF"); //FontFactory.Register(arialuniTff); string Roboto = Server.MapPath("~/fonts/Roboto-Regular.ttf"); FontFactory.Register(Roboto); PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDocument, outputMemoryStream); pdfWriter.CloseStream = false; //pdfWriter.PageEvent = new PrintHeaderFooter { Title = pageTitle }; pdfDocument.Open(); using (var htmlViewReader = new StringReader(htmlText)) { using (var htmlWorker = new HTMLWorker(pdfDocument)) { var styleSheet = new StyleSheet(); styleSheet.LoadTagStyle(HtmlTags.BODY, HtmlTags.FACE, "Roboto-Regular");//Arial Unicode MS styleSheet.LoadTagStyle(HtmlTags.BODY, HtmlTags.ENCODING, BaseFont.IDENTITY_H); htmlWorker.SetStyleSheet(styleSheet); htmlWorker.Parse(htmlViewReader); } } } renderedBuffer = new byte[outputMemoryStream.Position]; outputMemoryStream.Position = 0; outputMemoryStream.Read(renderedBuffer, 0, renderedBuffer.Length); } return(renderedBuffer); }
private void createPDF(string html) { //MemoryStream msOutput = new MemoryStream(); TextReader reader = new StringReader(html);// step 1: creation of a document-object Document document = new Document(PageSize.A4, 30, 30, 30, 30); Response.ContentType = "Application/pdf"; // step 2: // we create a writer that listens to the document // and directs a XML-stream to a file PdfWriter writer = PdfWriter.GetInstance(document, Response.OutputStream);//new FileStream("Test.pdf", FileMode.Create)); // step 3: we create a worker parse the document HTMLWorker worker = new HTMLWorker(document); // step 4: we open document and start the worker on the document document.Open(); // step 4.1: register a unicode font and assign it an allias FontFactory.Register("C:\\Windows\\Fonts\\ARIALUNI.TTF", "arial unicode ms"); // step 4.2: create a style sheet and set the encoding to Identity-H iTextSharp.text.html.simpleparser.StyleSheet ST = new iTextSharp.text.html.simpleparser.StyleSheet(); ST.LoadTagStyle("body", "encoding", "Identity-H"); // step 4.3: assign the style sheet to the html parser worker.SetStyleSheet(ST); worker.StartDocument(); // step 5: parse the html into the document worker.Parse(reader); // step 6: close the document and the worker worker.EndDocument(); worker.Close(); document.Close(); Response.End(); }
public byte[] CreateInitialPdf(HandlebarPdfEntity model) { var memoryStream = new MemoryStream(); var document = new Document(); var writer = PdfWriter.GetInstance(document, memoryStream); document.Open(); writer.PageEvent = new CreateFooterAndHeaderEvent(model.Header, DateTime.Now.ToString("d"), model.UniqueReference); var htmlWorker = new HTMLWorker(document); var sr = new StringReader(model.Html); var styles = new StyleSheet(); styles.LoadStyle("li", "list-style-type", "circle"); htmlWorker.SetStyleSheet(styles); htmlWorker.Parse(sr); document.Close(); return(memoryStream.ToArray()); }
// Versão Original em: https://social.msdn.microsoft.com/Forums/pt-BR/049133ce-2ce0-4b6e-9194-53b62e12ddbe/como-gerar-um-arquivo-pdf-a-partir-de-uma-pagina-aspx?forum=aspnetpt private void ConverteAspx2Pdf() { // Limpa qualquer coisa já previamente renderizada! Response.ClearContent(); // Para fazer download direto é só descomentar a linha abaixo, caso contrario o PDF é exibido no navegador // Response.AddHeader("content-disposition", "attachment; filename=ExportacaoAspx2Pdf.pdf"); // Altera o tipo de documento Response.ContentType = "application/pdf"; // Prepara um buffer que conterá todo o HTML que é renderizado StringWriter stw = new StringWriter(); HtmlTextWriter htextw = new HtmlTextWriter(stw); // Renderiza todo o HTML do ASPX no buffer (string) this.RenderControl(htextw); // Cria um novo documento PDF em branco Document doc = new Document(PageSize.A4, 10f, 10f, 10f, 10f); // Define o local de saida (gravação) do PDF como o dispositivo de transmissão do ASP.Net que vai para o navegador PdfWriter.GetInstance(doc, Response.OutputStream); doc.Open(); // Os estilos do boleto devem ser definidos desta forma // http://stackoverflow.com/questions/8414637/itextsharp-htmlworker-parsehtml-tablestyle-and-pdfstamper StyleSheet styles = new StyleSheet(); Dictionary <string, string> BolCell = new Dictionary <string, string>(); //styles.LoadStyle("BolCell", "size", "7px"); BolCell.Add("size", "7pt"); //BolCell.Add("face", "verdana"); styles.LoadStyle("BolCell", BolCell); Dictionary <string, string> BolField = new Dictionary <string, string>(); styles.LoadStyle("BolField", "size", "12px"); //BolField.Add("weight", "bold"); BolField.Add("size", "9pt"); //BolField.Add("face", "arial"); styles.LoadStyle("BolField", BolField); // Lê o HTML completo do buffer como uma String StringReader str = new StringReader(stw.ToString()); // Chama um conversor interno de HTML para PDF HTMLWorker htmlworker = new HTMLWorker(doc); // Transforma o HTML em PDF htmlworker.SetStyleSheet(styles); htmlworker.Parse(str); // fim do PDF doc.Close(); // Transmite o HTML para o browser Response.Write(doc); // Finaliza tudo! Response.End(); }
public IActionResult ExportToPdf(string returnUrl, int id) { var fanfic = Mapper.Map <FanficViewModel>(FanficRepository.GetById(id)); var topics = Mapper.Map <List <TopicViewModel> >(TopicRepository.GetTopicsByFanficId(id)); try { pdfDoc = new Document(PageSize.LETTER, 40f, 40f, 60f, 60f); BaseFont baseFont = BaseFont.CreateFont(@"wwwroot/font/arial.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); string path = @"wwwroot/pdf/tester1.pdf"; file = new FileStream(path, FileMode.Create); wri = PdfWriter.GetInstance(pdfDoc, file); pdfDoc.Open(); var spacer = new Paragraph("\n"); FileStream fileLogo = new FileStream(@"wwwroot/images/icons/logoPDF.png", FileMode.Open); var logo = Image.GetInstance(fileLogo); logo.SetAbsolutePosition(pdfDoc.Left, pdfDoc.Top); pdfDoc.Add(logo); fileLogo.Close(); var helvetica = new Font(baseFont, 20); var helveticaBase = helvetica.GetCalculatedBaseFont(false); wri.DirectContent.BeginText(); wri.DirectContent.SetFontAndSize(helveticaBase, 20f); wri.DirectContent.ShowTextAligned(Element.ALIGN_CENTER, fanfic.Name, 305, 705, 0); wri.DirectContent.EndText(); pdfDoc.Add(spacer); pdfDoc.Add(spacer); Paragraph info = new Paragraph("Author: " + fanfic.ApplicationUser.UserName + "\n" + "Rating: " + fanfic.AverageRating + "\n" + "Date: " + fanfic.CreateDate.ToShortDateString(), new Font(baseFont, 11, 2)); pdfDoc.Add(info); pdfDoc.Add(spacer); var avatarFanfic = fanfic.ImgUrl; avatarFanfic = avatarFanfic.Substring(0, 47) + "t_FanficPDF" + avatarFanfic.Substring(58, 22) + "jpg"; Uri uri = new Uri(avatarFanfic); Jpeg img = new Jpeg(uri); pdfDoc.Add(img); pdfDoc.Add(spacer); Paragraph descLabel = new Paragraph("Description: ", new Font(baseFont, 16)); pdfDoc.Add(descLabel); pdfDoc.Add(spacer); string arialuniTff = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "ARIALUNI.TTF"); FontFactory.Register(arialuniTff); StyleSheet ST = new StyleSheet(); ST.LoadTagStyle(HtmlTags.BODY, HtmlTags.FACE, "Arial Unicode MS"); ST.LoadTagStyle(HtmlTags.BODY, HtmlTags.ENCODING, BaseFont.IDENTITY_H); using (var htmlWorker = new HTMLWorker(pdfDoc)) { using (var sr = new StringReader(fanfic.Description)) { htmlWorker.SetStyleSheet(ST); htmlWorker.Parse(sr); } } pdfDoc.Add(spacer); Chapter content = new Chapter(new Paragraph("Content: ", new Font(baseFont, 16)), 0); pdfDoc.Add(content); foreach (var item in topics) { pdfDoc.Add(spacer); Paragraph chapter = new Paragraph("Chapter " + item.Number + ". " + item.Name, new Font(baseFont, 12)); pdfDoc.Add(chapter); } foreach (var item in topics) { Chapter chapter = new Chapter(new Paragraph(item.Name, new Font(baseFont, 18)), item.Number); pdfDoc.Add(chapter); pdfDoc.Add(spacer); Paragraph infoTopic = new Paragraph("Rating: " + item.AverageRating, new Font(baseFont, 11)); pdfDoc.Add(infoTopic); pdfDoc.Add(spacer); if (item.ImgUrl != " ") { var avatarTopic = item.ImgUrl; avatarTopic = avatarTopic.Substring(0, 47) + "t_FanficPDF" + avatarTopic.Substring(58, 22) + "jpg"; Uri uriTopic = new Uri(avatarTopic); Jpeg imgTopic = new Jpeg(uriTopic); pdfDoc.Add(imgTopic); pdfDoc.Add(spacer); } using (var htmlWorker = new HTMLWorker(pdfDoc)) { using (var sr = new StringReader(item.Text)) { htmlWorker.SetStyleSheet(ST); htmlWorker.Parse(sr); } } } pdfDoc.Close(); wri.Close(); WebClient User = new WebClient(); Byte[] FileBuffer = User.DownloadData(@"wwwroot/pdf/tester1.pdf"); if (FileBuffer != null) { Response.ContentType = "application/pdf"; Response.Headers.Add("content-length", FileBuffer.Length.ToString()); Response.Body.Write(FileBuffer, 0, FileBuffer.Length); } } catch (Exception ex) { pdfDoc.Close(); wri.Close(); } finally { System.IO.File.Delete(@"wwwroot/pdf/tester1.pdf"); } return(RedirectPermanent(returnUrl)); }
private bool CreatePDF(string HTMLContent, string OutputFilePath, out string ErrorIfAny) { bool IsSuccess = false; ErrorIfAny = string.Empty; Document document = new Document(); try { StringWriter SW = new StringWriter(); SW.Write(HTMLContent); MyPage tmpPage = new MyPage(); HtmlForm form = new HtmlForm(); form.Controls.Add(new LiteralControl("")); tmpPage.Controls.Add(form); HtmlTextWriter htmlWriter = new HtmlTextWriter(SW); form.Controls[0].RenderControl(htmlWriter); string htmlContent = SW.ToString(); PdfWriter.GetInstance(document, new FileStream(OutputFilePath, FileMode.Create)); HTMLWorker worker = new HTMLWorker(document); document.Open(); using (TextReader sReader = new StringReader(htmlContent)) { FontFactory.Register(@"[Your font file location].ttf", "OpenSans-Regular"); string fontpath = @"[Your font file location].ttf"; //"simsun.ttf" file was downloaded from web and placed in the folder BaseFont bf = BaseFont.CreateFont(fontpath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED); //create new font based on BaseFont Font fontContent = new Font(bf, 11); Font fontHeader = new Font(bf, 12); // step 4.2: create a style sheet and set the encoding to Identity-H iTextSharp.text.html.simpleparser.StyleSheet ST = new iTextSharp.text.html.simpleparser.StyleSheet(); ST.LoadTagStyle("body", "encoding", "Identity-H"); worker.SetStyleSheet(ST); worker.StartDocument(); worker.Parse(sReader); worker.EndDocument(); worker.Close(); document.Close(); } IsSuccess = true; } catch (Exception eX) { IsSuccess = false; ErrorIfAny = eX.Message; } finally { try { if (document != null && document.IsOpen()) { document.Close(); } } catch { } } return(IsSuccess); }
protected void Page_Load(object sender, EventArgs e) { //ทดสอบ ชั่วคราว ลบออกเมื่อใช้งานจริง //Session["CurrCode"] = "707012555"; //Session["YearVersion"] = "2555"; //Session["NumTQF1"] = "001"; CurrCode = Request.QueryString["CurrCode"]; YearVersion = Request.QueryString["YearVersion"]; TQF.Curriculum curriculum = new TQF.Curriculum().getCurriculum(CurrCode, YearVersion); StructurePlan structurePlan = new StructurePlan().getStructurePlan(CurrCode, YearVersion); Label1.Text = curriculum.CurrThName; //Label2.Text = curriculum.MajorName; if (curriculum.CurrStatus == "1") { //สถานะของหลักสูตร(1=ใหม่, 2=ปรับปรุง) curriculum.CurrStatus = "หลักสูตรใหม่"; } else { curriculum.CurrStatus = "หลักสูตรปรับปรุง"; } Label3.Text = "(" + curriculum.CurrStatus + " พ.ศ. " + curriculum.YearVersion + ")"; Label4.Text = "มหาวิทยาลัยเทคโนโลยีพระจอมเกล้าพระนครเหนือ"; Label5.Text = new Faculty().getFaculty(curriculum.FacultyCode).Faculty_Thai + " "; Label6.Text = new Department().getDepartment(curriculum.DepartmentCode).Department_Thai; //รหัสและชื่อหลักสูตร Label7.Text = curriculum.CurrCode; Label8.Text = curriculum.CurrThName; Label9.Text = curriculum.CurrShortThName; Label10.Text = curriculum.CurrEnName; Label11.Text = curriculum.CurrShortEnName; if (CurrCode != "999999999") { //ชื่อปริญญาและสาขาวิชา Label12.Text = new Diploma().getDiploma(curriculum.DiplomaCode).DomainThName; Label13.Text = new Diploma().getDiploma(curriculum.DiplomaCode).DomainThShortName; Label14.Text = new Diploma().getDiploma(curriculum.DiplomaCode).DomainEnName; Label15.Text = new Diploma().getDiploma(curriculum.DiplomaCode).DomainEnShortName; //วันที่อนุมัติหลักสูตร และภาคการศึกษาที่เริ่มใช้หลักสูตร Label16.Text = new utility().getThaiBirthDay(curriculum.ApprovedDate); Label17.Text = curriculum.BeginSemester + "/" + curriculum.YearVersion; //จำนวนหน่วยกิตที่เรียนตลอดหลักสูตร Label18.Text = structurePlan.TotalCredits + " หน่วยกิต"; } //รูปแบบของหลักสูตร string sqlStructurePlan = "Select * From STRUCTUREPLAN Where CURRCODE='" + CurrCode + "' And YEARVERSION='" + YearVersion + "'"; List <StructurePlan> dataStructurePlan = new StructurePlan().getStructurePlanManual(sqlStructurePlan); foreach (StructurePlan data in dataStructurePlan) { Label19.Text = new CurrFormat().getCurrFormat(data.CurrFormatCode).CurrFormatName; if (dataStructurePlan.Count > 1) { Label19.Text += "<br>"; } //Tab 2: โครงสร้างหลักสูตร htmlGenerateTab2(data.MajorCode, data.CurrFormatCode, data.TotalCredits, data.YearVersion, data.CurrTypeCode); //Tab 3: รายวิชาในหลักสูตร htmlGenerateTab3(data.MajorCode, data.CurrFormatCode, data.TotalCredits, data.YearVersion, data.CurrTypeCode); //Tab 4: แผนการศึกษา htmlGenerateTab4(data.MajorCode, data.CurrFormatCode, data.TotalCredits, data.YearVersion, data.CurrTypeCode); //Tab 5: คำอธิบายรายวิชา htmlGenerateTab5(data.MajorCode, data.CurrFormatCode, data.TotalCredits, data.YearVersion, data.CurrTypeCode); } Label20.Text = curriculum.NumYear + " ปี / " + curriculum.MaxNumYear + " ปี"; //อาจารย์ผู้รับผิดชอบหลักสูตร //ความหมาย LOADTYPECODE //1 อาจารย์ประจำหลักสูตร //4 อาจารย์ประจำแขนง string sqlLecturer = "Select * From ABOUTLECTURER Where CURRCODE='" + CurrCode + "' And YEARVERSION='" + YearVersion + "' And LOADTYPECODE='1' Order By LECTIDENTITY"; List <AboutLecturer> aboutLecturer = new AboutLecturer().getAboutLecturerManual(sqlLecturer); int i = 1; foreach (AboutLecturer data in aboutLecturer) { SysUser sysUser = new SysUser().getSysUser(data.LectIdentity); AcademicPosition position = new AcademicPosition().getAcademicPosition(sysUser.AcademicPositionCode); Label21.Text += "<span class=\"report-indent-1em\">" + i + ". " + position.AcademicPositionThName + sysUser.ThName + " " + sysUser.ThSurName + "</span><BR>"; i++; } //Export to PDF utility utname = new utility(); Response.ContentType = "application/pdf"; Response.AddHeader("content-disposition", "attachment;filename=" + CurrCode + ".pdf"); Response.Cache.SetCacheability(HttpCacheability.NoCache); StringWriter sw = new StringWriter(); HtmlTextWriter hw = new HtmlTextWriter(sw); dvHtml.RenderControl(hw); StringReader sr = new StringReader(sw.ToString()); Document pdfDoc = new Document(PageSize.A4, 50f, 50f, 50f, 50f); //Document pdfDoc = new Document(PageSize.A4.Rotate(), 50f, 50f, 10f, 10f); HTMLWorker htmlparser = new HTMLWorker(pdfDoc); PdfWriter.GetInstance(pdfDoc, Response.OutputStream); pdfDoc.Open(); StyleSheet styles = new StyleSheet(); FontFactory.Register(Server.MapPath("~/Fonts/") + "THSarabunNew.ttf"); styles.LoadTagStyle("body", HtmlTags.FACE, "THSarabunNew"); styles.LoadTagStyle("body", "size", "16pt"); styles.LoadTagStyle("body", "encoding", BaseFont.IDENTITY_H); styles.LoadTagStyle(HtmlTags.TABLE, "width", "100%"); styles.LoadTagStyle(HtmlTags.TABLE, "align", "center"); styles.LoadTagStyle(HtmlTags.TABLE, HtmlTags.BORDER, "0"); styles.LoadTagStyle(HtmlTags.TH, HtmlTags.BORDER, "0"); styles.LoadTagStyle(HtmlTags.TD, HtmlTags.BORDER, "0"); htmlparser.SetStyleSheet(styles); htmlparser.Parse(sr); pdfDoc.Close(); Response.Write(pdfDoc); Response.End(); //End Export to PDF }
private bool SendPDFEmail(DataTable dt, DataTable dta) { string companyName = "ESOGU"; StringBuilder sb = new StringBuilder(); sb.Append("<table width='100%' cellspacing='0' cellpadding='2'>"); sb.Append("<tr><td align='center' style='background-color: #18B5F0' colspan = '2'><b>Yazılım Raporu</b></td></tr>"); sb.Append("<tr><td colspan = '2'></td></tr>"); sb.Append("</td><td><b>Tarih: </b>"); sb.Append(DateTime.Now); sb.Append(" </td></tr>"); sb.Append("<tr><td colspan = '2'><b>Kurum Adı :</b> "); sb.Append(companyName); sb.Append("</td></tr>"); sb.Append("</table>"); sb.Append("<br />"); sb.Append("<table border = '1'>"); sb.Append("<tr>"); foreach (DataColumn column in dt.Columns) { sb.Append("<th style = 'background-color: #D20B0C;color:#632828'>"); sb.Append(column.ColumnName); sb.Append("</th>"); } sb.Append("</tr>"); foreach (DataRow row in dt.Rows) { sb.Append("<tr>"); foreach (DataColumn column in dt.Columns) { sb.Append("<td>"); sb.Append(row[column]); sb.Append("</td>"); } sb.Append("</tr>"); } sb.Append("</table>"); ////time sb.Append("<br />"); sb.Append("<br />"); sb.Append("<br />"); sb.Append("<table border = '1'>"); sb.Append("<tr>"); foreach (DataColumn column in dta.Columns) { sb.Append("<th style = 'background-color: #D20B0C;color:#632828'>"); sb.Append(column.ColumnName); sb.Append("</th>"); } sb.Append("</tr>"); foreach (DataRow row in dta.Rows) { sb.Append("<tr>"); foreach (DataColumn column in dta.Columns) { sb.Append("<td>"); sb.Append(row[column]); sb.Append("</td>"); } sb.Append("</tr>"); } sb.Append("</table>"); StringReader sr = new StringReader(sb.ToString()); Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f); HTMLWorker htmlparser = new HTMLWorker(pdfDoc); #region Türkçe karakter sorunu için yazılması gereken kod bloğu. FontFactory.Register(Path.Combine("C:\\Windows\\Fonts\\Arial.ttf"), "Garamond"); StyleSheet css = new StyleSheet(); css.LoadTagStyle("body", "face", "Garamond"); css.LoadTagStyle("body", "encoding", "Identity-H"); css.LoadTagStyle("body", "size", "12pt"); htmlparser.SetStyleSheet(css); #endregion using (MemoryStream memoryStream = new MemoryStream()) { PdfWriter writer = PdfWriter.GetInstance(pdfDoc, memoryStream); pdfDoc.Open(); htmlparser.Parse(sr); pdfDoc.Close(); byte[] bytes = memoryStream.ToArray(); memoryStream.Close(); MailMessage mm = new MailMessage("*****@*****.**", "*****@*****.**"); mm.Subject = "Birim Yazılım Raporu"; mm.Body = "Birim Yazılım Raporu PDF Eki"; mm.Attachments.Add(new Attachment(new MemoryStream(bytes), "RaporPDF.pdf")); mm.IsBodyHtml = true; try { SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587); smtp.EnableSsl = true; smtp.UseDefaultCredentials = false; smtp.Credentials = new NetworkCredential("*****@*****.**", "grup9proje*"); smtp.Send(mm); return(true); } catch (Exception) { ViewBag.Error = "Mesaj Gönderilken hata olıuştu"; return(false); } } }
/// <summary> /// /// </summary> /// <param name="HtmlTemp"></param> /// <param name="FileName"></param> public static void MyPaymentReport(string FileName, string UserImg, string mycontent) { // Create a Document object HttpContext context = HttpContext.Current; var document = new Document(PageSize.A4, 50, 50, 25, 25); HTMLWorker worker = new HTMLWorker(document); // Create a new PdfWriter object, specifying the output stream // var output = new FileStream(context.Server.MapPath("~/MyFirstPDF.pdf"), FileMode.Create); var output = new MemoryStream(); var writer = PdfWriter.GetInstance(document, output); try { //string arialuniTff = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "ARIALUNI.TTF"); //iTextSharp.text.FontFactory.Register(arialuniTff); string fontpath = System.Web.HttpContext.Current.Server.MapPath("~/Content/ARIALUNI.ttf"); // BaseFont bf = BaseFont.CreateFont(fontpath + "ARIALUNI.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED); iTextSharp.text.FontFactory.Register(fontpath, "CustomAriel"); // Font f = new Font(bf, 10, Font.NORMAL); }catch (Exception objEx) { } // Open the Document for writing document.Open(); //... Step 3: Add elements to the document! ... var titleFont = FontFactory.GetFont("Arial", 18, Font.BOLD); var subTitleFont = FontFactory.GetFont("Arial", 14, Font.BOLD); var boldTableFont = FontFactory.GetFont("Arial", 12, Font.BOLD); var endingMessageFont = FontFactory.GetFont("Arial", 10, Font.ITALIC); var bodyFont = FontFactory.GetFont("Arial", 12, Font.NORMAL); //document.Add(new Paragraph("IFind - Asia", titleFont)); iTextSharp.text.html.simpleparser.StyleSheet ST = new iTextSharp.text.html.simpleparser.StyleSheet(); //Set the default body font to our registered font's internal name ST.LoadTagStyle("body", "face", "Arial Unicode MS"); //Set the default encoding to support Unicode characters ST.LoadTagStyle("body", "encoding", "Identity-H"); // step 4.3: assign the style sheet to the html parser worker.SetStyleSheet(ST); //List<IElement> list = HTMLWorker.ParseToList(new StringReader(mycontent), ST); //add logo //var logo = iTextSharp.text.Image.GetInstance(context.Server.MapPath("~/Img/Users/ducnguyen.jpg")); //Image logo = iTextSharp.text.Image.GetInstance(context.Server.MapPath(UserImg)); //logo.ScaleToFit(80, 80); ////logo.SetAbsolutePosition(50, 700); //document.Add(logo); // Read in the contents of the Receipt.htm file... //string contents = File.ReadAllText(context.Server.MapPath("~/html/" + HtmlTemp + ".html")); //string contents = LoadWebtoHTML(context.Server.MapPath("~/PersonInfo/MyPdfReport")); string contents = getImage(mycontent); // Step 4: Parse the HTML string into a collection of elements... var parsedHtmlElements = HTMLWorker.ParseToList(new StringReader(contents), ST); // Enumerate the elements, adding each one to the Document... foreach (var htmlElement in parsedHtmlElements) { document.Add(htmlElement as IElement); } // Close the Document - this saves the document contents to the output stream document.Close(); context.Response.ContentType = "application/pdf"; context.Response.AddHeader("Content-Disposition", string.Format("attachment;filename=MyPayment-{0}.pdf", FileName)); context.Response.ContentEncoding = Encoding.UTF8; context.Response.HeaderEncoding = Encoding.UTF8; context.Response.BinaryWrite(output.ToArray()); context.Response.Flush(); context.Response.End(); }
public IActionResult OrderDetails(BasketOrderModel basketOrderModel) { string tempId = HttpContext.Session.GetString("id"); int userId = int.Parse(tempId); var basketProducts = _basketService.Baskets(userId); List <BasketListele> basketListele = new List <BasketListele>(); foreach (var item in basketProducts) { BasketListele basketList = new BasketListele(); var product = _productService.GetById(item.ProductId); if (product == null) { var basketToDeleted = _basketService.GetById(item.Id); _basketService.Delete(basketToDeleted); // eğer kullanıcın sepetindeki bir ürün daha sonra alınırsa bu ürün kullanıcının sepetinden de otomatik //silinmektedir. continue; } int basketId = item.Id; basketList.Products = product; basketList.BasketId = basketId; basketListele.Add(basketList); } basketOrderModel.BasketLists = basketListele; //silinebilir. basketOrderModel.OrderList.BasketIds = HttpContext.Session.GetString("BasketIds"); basketOrderModel.OrderList.OrderTime = DateTime.Now; basketOrderModel.OrderList.UserId = userId; basketOrderModel.CardDetails.UserId = userId; Order order = new Order() //aynı kullanıcıya ait birden fazla kayıt veritabanında tutulur . Bu daha sonra düzenlenebilir. { Address = basketOrderModel.OrderList.Address, BasketIds = basketOrderModel.OrderList.BasketIds, EMail = basketOrderModel.OrderList.EMail, OrderTime = basketOrderModel.OrderList.OrderTime, UserId = basketOrderModel.OrderList.UserId }; _orderService.Add(order); int orderId = order.Id; // o anki order ıd alınır . sipariş faturasına eklenmesi için string orderIdNow = orderId.ToString(); HttpContext.Session.SetString("getByOrderId", orderIdNow); Card card = new Card() { CardName = basketOrderModel.CardDetails.CardName, CardNumber = basketOrderModel.CardDetails.CardNumber, Cvv = basketOrderModel.CardDetails.Cvv, ExpirationMonth = basketOrderModel.CardDetails.ExpirationMonth, ExpirationYear = basketOrderModel.CardDetails.ExpirationYear, UserId = userId }; Card userCard = _cardService.GetByUserId(userId); if (userCard == null) // ilk kez kayıt yapan kullanıcı veritabanına eklenir. Çünkü 1 kullanıcının sistemde sadece 1 kayıtı olacaktır. { _cardService.Add(card); } // eğer kullanıcı kendi kartı dışında bir kart kullanır ise bu kart sisteme eklenmez. Daha sonra yapılacak olan //tüm alışverişlerde sistemde ilk kayıt yapılmış olan kart kullanıcıya gösterilecektir. // Daha sonra istenirse kaydedilmiş olan kartı güncelleyebilir veya silebilir. //BasketOrderModel basketOrderModelDeneme = new BasketOrderModel() //silinebilir. Veritabanınadan order bilgileri çekilebilir. //{ // CardDetails = card, // City = basketOrderModel.City, // FirstName = basketOrderModel.FirstName, // LastName = basketOrderModel.LastName, // Phone = basketOrderModel.Phone, // OrderList = order, // BasketLists = basketOrderModel.BasketLists //}; #region Mail Yollama SmtpClient client = new SmtpClient(); MailAddress from = new MailAddress("mail adresiniz", "ShoopingApp"); string eMail = basketOrderModel.OrderList.EMail; MailAddress to = new MailAddress(eMail);//bizim mail adresi MailMessage msg = new MailMessage(from, to); msg.IsBodyHtml = true; msg.Subject = "Alışveriş Faturası"; #region StringBuilder ile Mail düzenleme StringBuilder builder = new StringBuilder(); builder.Append("<head>"); builder.Append(" <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css \" " + " " + "integrity=\"sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l\" " + " " + "crossorigin=\"anonymous\" />"); builder.Append("</head>"); builder.Append("<body>"); builder.Append("<h4 style=\"text-align:center;color:red;\">Sayin " + basketOrderModel.FirstName + " " + basketOrderModel.LastName + " Siparis Faturaniz</h4><br><br>"); builder.Append("<table class=\"table table-striped\">"); builder.Append(" <tr>"); builder.Append("<th>Ürün resmi </th><th>Ürün ismi </th><th>Ürün fiyatı</th><th>Açiklama </th> "); builder.Append("</tr>"); foreach (var item in basketListele) { builder.Append(" <tr>"); string imagePath = "wwwroot\\" + "img\\" + item.Products.ImageUrl; //var imageFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, imagePath); builder.Append("<td> <img src=" + "\"" + imagePath + "\"" + " " + "width=\"100\" height=\"100\" /> </td><td>" + item.Products.ProductName + "</td><td>" + item.Products.ProductPrice + "</td><td>" + item.Products.Description + " </td> "); builder.Append("</tr>"); } builder.Append("</table>"); builder.Append("<div style=\" text-align:center;margin-top:40px; font-family: Arial, Helvetica, sans - serif; \">"); builder.Append("<pre>"); builder.Append("<br><br><h4 style=\"color:red;\">-- Kart Bilgileriniz --</h4>" + "<br>"); builder.Append(" Kart İsminiz : " + basketOrderModel.CardDetails.CardName + "<br>"); builder.Append(" Kart Numaraniz : " + basketOrderModel.CardDetails.CardNumber + "<br>"); builder.Append(" Son kullanma tarihi : " + basketOrderModel.CardDetails.ExpirationMonth + "\\" + basketOrderModel.CardDetails.ExpirationYear + "<br>"); int toplam = 0; foreach (var item in basketListele) { toplam += item.Products.ProductPrice; } builder.Append("<br><br><h4 style=\"color:red;\">-- Sipariş Bilgileriniz --</h4>" + "<br>"); builder.Append(" Siparis Tutari : " + toplam + " TL" + "<br>"); builder.Append(" Siparis Adresiniz : " + basketOrderModel.OrderList.Address + "<br>"); builder.Append(" E-Mail Adresiniz : " + basketOrderModel.OrderList.EMail + "<br>"); builder.Append(" Siparis Tarihi : " + basketOrderModel.OrderList.OrderTime + "<br>"); builder.Append(" Telefon Numaraniz : " + basketOrderModel.Phone + "<br>"); builder.Append(" Sehriniz : " + basketOrderModel.City + "<br>"); builder.Append("</pre>"); builder.Append("</div>"); builder.Append("</body>"); #region Pdf StringReader sr = new StringReader(builder.ToString()); Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f); HTMLWorker htmlparser = new HTMLWorker(pdfDoc); #region Türkçe karakter sorunu için yazılması gereken kod bloğu. // FontFactory.Register(Path.Combine("C:\\Windows\\Fonts\\Arial.ttf"), "Garamond"); /// kendi türkçe karakter desteği olan fontunuzu da girebilirsiniz. StyleSheet css = new StyleSheet(); css.LoadTagStyle("body", "face", "Garamond"); css.LoadTagStyle("body", "encoding", "Identity-H"); css.LoadTagStyle("body", "size", "12pt"); htmlparser.SetStyleSheet(css); #endregion using (MemoryStream memoryStream = new MemoryStream()) { PdfWriter writer = PdfWriter.GetInstance(pdfDoc, memoryStream); pdfDoc.Open(); htmlparser.Parse(sr); pdfDoc.Close(); byte[] bytes = memoryStream.ToArray(); memoryStream.Close(); // normal text halinde yollar ama biz pdf yolluyoruz ve buna gerek kalmaz. // msg.Body += "Bizleri tercih ettiğiniz için teşekkür ederiz" + builder; //burada başında gönderen kişinin mail adresi geliyor //msg.CC.Add(from);//herkes görür msg.Attachments.Add(new Attachment(new MemoryStream(bytes), "SiparisFaturasi.pdf")); // msg.Attachments.Add(new Attachment("images/hp.jpg")); NetworkCredential info = new NetworkCredential("mail adresiniz", "sifreniz"); client.Port = 587; client.Host = "smtp.gmail.com"; client.EnableSsl = true; client.Credentials = info; client.Send(msg); } #endregion #endregion #endregion #region Odeme //Odeme actiondan buraya taşınmıştır. Çünkü Post methotda olması daha uygun olacaktır. foreach (var item in basketProducts) { var productToDeleted = _productService.GetById(item.ProductId); // tam sepette ödeme ye tıklarken ürün satılmışsa buradaki product // null olabilir bu durumu sonra kontrol etmelisin. var product = _productService.GetById(item.ProductId); // ilgili ürün bulunur. int productPrice = product.ProductPrice; // ürünün fiyatı bulunur. int saticiId = product.UserId; User satici = _userService.GetById(saticiId); satici.Balance += productPrice; _userService.Update(satici); // saticinin bakiyesi güncellenir. if (productToDeleted.UnitsInStock == 1) { _productService.Delete(productToDeleted); // Stokta 1 tane varsa ilgili ürün silinir. _favorilerService.Delete(item.ProductId); // favorilerden de silinir. } if (productToDeleted.UnitsInStock > 1) { productToDeleted.UnitsInStock -= 1; _productService.Update(productToDeleted); } _basketService.Delete(item); // ilgili sipariş silinir. } #endregion // return View(basketOrderModelDeneme); //sipariş faturası // ödeme kısmında productlar veritabanından silinir. // ama kullanıcı siparişten vazgeçebilir. fake den silinse daha güzel olur . Araştır bunu //kullanıcı sipariş verdikten sonra iptal edemez bu yüzden fake e ihtiyeç yoktur. Bu durum Daha sonra düzenlenebilir. return(RedirectToAction("Odeme", "Basket", new { city = basketOrderModel.City, firstName = basketOrderModel.FirstName, lastName = basketOrderModel.LastName, phone = basketOrderModel.Phone, cardName = basketOrderModel.CardDetails.CardName, cardNumber = basketOrderModel.CardDetails.CardNumber, cvv = basketOrderModel.CardDetails.Cvv, expirationMonth = basketOrderModel.CardDetails.ExpirationMonth, expirationYear = basketOrderModel.CardDetails.ExpirationYear })); }
protected void CreartePdf() { string filname = Server.MapPath("../Admin/InvoicePdf/" + lblInvoiceNoMail.Text + ".pdf"); if (System.IO.File.Exists(filname)) { System.IO.File.Delete(filname); } iTextSharp.text.html.simpleparser.StyleSheet styles = new iTextSharp.text.html.simpleparser.StyleSheet(); styles.LoadStyle("wdth20", "width", "30"); styles.LoadStyle("wdth80", "width", "80"); styles.LoadStyle("wdth50", "width", "50"); styles.LoadStyle("wdth140", "width", "140"); styles.LoadStyle("wdth100", "width", "100"); styles.LoadStyle("wdth200", "width", "200"); styles.LoadStyle("wdth400", "width", "400"); styles.LoadStyle("wdth51", "width", "51"); styles.LoadStyle("wdth40", "width", "40"); styles.LoadStyle("wdth60", "width", "60"); styles.LoadStyle("wdth65", "width", "65"); styles.LoadStyle("wdth55", "width", "55"); styles.LoadStyle("hght200", "height", "200"); styles.LoadStyle("border-left", "border-left-width", "1"); styles.LoadStyle("borderright", "BorderWidthRight ", "1f"); //for header StringWriter swheader = new StringWriter(); HtmlTextWriter hwheader = new HtmlTextWriter(swheader); pnlHeader.RenderControl(hwheader); StringReader srheader = new StringReader(swheader.ToString()); PdfPCell cellLeft = new PdfPCell(); StyleSheet style = new StyleSheet(); style.LoadStyle("wdth20", "width", "30"); style.LoadStyle("wdth40", "width", "40"); style.LoadStyle("wdth60", "width", "60"); style.LoadStyle("wdth80", "width", "80"); style.LoadStyle("wdth81", "width", "81"); style.LoadStyle("wdth100", "width", "100"); style.LoadStyle("wdth50", "width", "50"); style.LoadStyle("wdth51", "width", "51"); style.LoadStyle("wdth140", "width", "140"); style.LoadStyle("wdth600", "width", "552"); style.LoadStyle("wdth200", "width", "220"); style.LoadStyle("wdth400", "width", "331"); style.LoadStyle("wdth550", "width", "551"); style.LoadStyle("wdth541", "width", "551"); style.LoadStyle("wdth65", "width", "65"); style.LoadStyle("wdth55", "width", "55"); List <IElement> objects = HTMLWorker.ParseToList(new StringReader(swheader.ToString()), style); //This transforms your HTML to a list of PDF compatible objects for (int k = 0; k < objects.Count; ++k) { cellLeft.AddElement((IElement)objects[k]); //if (k == 1) //{ // cellLeft.FixedHeight = 500f; // cellLeft.GetMaxHeight();//Add these objects to cell one by one //} } //header ends //for content StringWriter sw = new StringWriter(); HtmlTextWriter hw = new HtmlTextWriter(sw); pnlMail.RenderControl(hw); StringReader sr = new StringReader(sw.ToString()); float topmrg = cellLeft.GetMaxHeight() + 22; Document pdfDoc = new Document(PageSize.A4, 22, 22, topmrg, 40); HTMLWorker htmlparser = new HTMLWorker(pdfDoc); htmlparser.SetStyleSheet(styles); PdfWriter writer = PdfWriter.GetInstance(pdfDoc, new FileStream(filname, FileMode.Create)); pdfDoc.Open(); writer.PageEvent = new HeaderFooter1(cellLeft); htmlparser.Parse(sr); pdfDoc.Close(); pdfDoc.Dispose(); sr.Close(); sr.Dispose(); srheader.Close(); sr.Dispose(); writer.Close(); writer.Dispose(); Mail(filname); }