public static string generateOutputFile(enumOutputType outputType,string strTemplate, StyleSheet Style,int SwitchID,enumSwitchType SwitchType) { try { clsClient client = new clsClient(HttpContext.Current.Session["requestclientid"].ToString()); switch (outputType) { case enumOutputType.PDF: string Path = HttpContext.Current.Server.MapPath("~/Output/PDF/"); string PDFPath = string.Format("{0}{1}_{2}_{3}_{4:yyyy-MM-dd}.pdf", Path, SwitchType.ToString(), (new clsIFA(int.Parse(HttpContext.Current.Session["ifaid"].ToString()))).propIFA_Name, client.propForename +" "+ client.propSurname, DateTime.Now); using (clsPDF O = new clsPDF(){StyleSheet = Style}) { O.PageSetup(PageSize.LETTER, 40, 40, 30, 15); O.FromHTMLString(strTemplate); O.StartCreate(PDFPath); LogOutput(enumSwitchType.Portfolio,SwitchID,PDFPath,enumOutputType.PDF); } return PDFPath; default: return ""; } } catch (System.Net.Mail.SmtpException SE) { throw new clsOutputException(SE.Message, SE); } catch (Exception ex) { throw new clsOutputException(ex.Message, ex); } }
public override void ProcessRequest(HttpContext context) { base.ProcessRequest(context); int ShowID = Convert.ToInt32(context.Request["showid"]); Shows show = new Shows(ShowID); var writer = PdfWriter.GetInstance(doc, output); var pageEvent = new Fpp.Core.PdfDocuments.ITextEvents(); pageEvent.Header = "Refund Report"; pageEvent.SubHeader = string.Format("{0} {1}", show.ShowName, show.ShowDate.ToString("dd MMM yyyy")); writer.PageEvent = pageEvent; StyleSheet sheet = new StyleSheet(); doc.Open(); PdfPCell cell; PdfPTable ptable = new PdfPTable(colWidths); cell = new PdfPCell(new Phrase(new Chunk("Show Reference", headerFont))); cell.BorderWidth = 0; ptable.AddCell(cell); ptable = new PdfPTable(colWidths); cell = new PdfPCell(new Phrase(new Chunk("Date", headerFont))); cell.BorderWidth = 0; ptable.AddCell(cell); ptable = new PdfPTable(colWidths); cell = new PdfPCell(new Phrase(new Chunk("Name", headerFont))); cell.BorderWidth = 0; ptable.AddCell(cell); ptable = new PdfPTable(colWidths); cell = new PdfPCell(new Phrase(new Chunk("Description", headerFont))); cell.BorderWidth = 0; ptable.AddCell(cell); doc.Add(ptable); ptable = new PdfPTable(colWidths); cell = new PdfPCell(new Phrase(new Chunk("Amount", headerFont))); cell.BorderWidth = 0; ptable.AddCell(cell); doc.Add(ptable); var refunds = Transaction.GetShowRefunds(ShowID); PrintReport(ShowID, refunds, doc); doc.NewPage(); doc.Close(); context.Response.ClearContent(); context.Response.ContentType = "application/pdf"; context.Response.AddHeader("content-disposition", String.Format("inline;filename=Refund-{0:ddMMMyyyy}.pdf", show.ShowDate)); context.Response.BinaryWrite((output as MemoryStream).ToArray()); }
public void ProcessRequest(HttpContext context) { int ShowID = Convert.ToInt32(context.Request["showid"]); String cmd = context.Request["doc"].ToString(); Shows show = new Shows(ShowID); String pdfPath = context.Server.MapPath(cmd + ".pdf"); Boolean publish = false; if (!String.IsNullOrEmpty(context.Request["publish"]) && context.Request["publish"].ToString() == "1") publish = true; Document doc = new Document(PageSize.A4, -50, -50, 2, 2); Stream output; if (publish) { String path = context.Server.MapPath(@"..\schedules\"); path += DateTime.Today.ToString("yyyy"); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } path += String.Format("\\{0:yyyyMM}_{1}.pdf", show.ShowDate, show.ShowName); output = new FileStream(path, FileMode.Create); } else { output = new MemoryStream(); } var writer = PdfWriter.GetInstance(doc, output); StyleSheet sheet = new StyleSheet(); doc.Open(); var dm = new DocumentManager(); var rings = Rings.GetAllRingsForShow(ShowID); foreach (var ring in rings) { dm.PrintAllForRing(doc, ShowID, ring.ID, writer); } doc.Close(); if (publish) { } else { context.Response.ClearContent(); context.Response.ContentType = "application/pdf"; context.Response.AddHeader("content-disposition", String.Format("inline;filename=PreviewSchedule.pdf")); context.Response.BinaryWrite((output as MemoryStream).ToArray()); } }
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); }
public FileResult PdfConverter() { string htmlText = string.Empty; string filename = string.Empty; filename = "Test"; htmlText += "<div></div>"; string filePath = Request.PhysicalApplicationPath + "/Upload/Test/" + filename.Replace(" ", "") + ".pdf"; using (FileStream docFile = new FileStream(filePath, FileMode.Create)) { string url = "http://" + Request.Url.Authority + "/account/Login"; Dictionary <string, object> attr = new Dictionary <string, object>(); attr.Add("logo", new TemplateHelper().getlogo()); attr.Add("Insuredname", "Praveen Kumar"); attr.Add("EmailId", "*****@*****.**"); attr.Add("InsuredDoB", "11-05-2016"); attr.Add("InsuredAge", "40"); attr.Add("MobileNo", "9866078078"); attr.Add("SpouseDoB", "11-05-2016"); attr.Add("SpouseAge", "15"); attr.Add("DoughterDoB", "11-05-2016"); attr.Add("DoughterAge", "10"); attr.Add("SonDoB", "11-05-2016"); attr.Add("SonAge", "8"); attr.Add("NoofAdults", "2"); attr.Add("NoofChildren", "2"); attr.Add("Smoker", "Yes"); attr.Add("Preexistingdiseases", "No"); attr.Add("MaternityCover", "Yes"); attr.Add("RestorationBenefits", "Yes"); htmlText = new TemplateHelper().GetTemplateBody(attr, "~/App_Data/test.html"); iTextSharp.text.Document document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 30, 30, 10, 30); iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, docFile); document.Open(); iTextSharp.text.html.simpleparser.StyleSheet styles = new iTextSharp.text.html.simpleparser.StyleSheet(); iTextSharp.text.html.simpleparser.HTMLWorker hw = new iTextSharp.text.html.simpleparser.HTMLWorker(document); hw.Parse(new StringReader(htmlText)); document.Close(); writer.Close(); } return(File(filePath, "application/pdf", filename.Replace(" ", "") + ".pdf")); }
public static void HtmlToPdf(string html, string filePath) { Document document = new Document(); PdfWriter.GetInstance(document, new FileStream(filePath, FileMode.Create)); document.Open(); //Image pdfImage = Image.GetInstance(Server.MapPath("logo.png")); //pdfImage.ScaleToFit(100, 50); //pdfImage.Alignment = iTextSharp.text.Image.UNDERLYING; pdfImage.SetAbsolutePosition(180, 760); //document.Add(pdfImage); iTextSharp.text.html.simpleparser.StyleSheet styles = new iTextSharp.text.html.simpleparser.StyleSheet(); iTextSharp.text.html.simpleparser.HTMLWorker hw = new iTextSharp.text.html.simpleparser.HTMLWorker(document); hw.Parse(new StringReader(html)); document.Close(); }
public void ProcessRequest(HttpContext context) { int ShowID = Convert.ToInt32(context.Request["showid"]); String userIDs = context.Request["ids"].ToString(); String[] IDsList = userIDs.Split(','); Shows show = new Shows(ShowID); Document doc = new Document(PageSize.A4.Rotate(), 10, 10, -5, -5); Stream output = new MemoryStream(); var writer = PdfWriter.GetInstance(doc, output); StyleSheet sheet = new StyleSheet(); doc.Open(); int pageCount = 0; foreach (String id in IDsList) { List<int> defaultUsers = new List<int>(); int UserID = Convert.ToInt32(id); UserShows userShow = new UserShows(UserID, ShowID); printRingForUser(userShow, UserID, doc, ref defaultUsers, ref pageCount); List<int> tmp = null; foreach (int defid in defaultUsers) { if (pageCount % 2 != 0) { doc.NewPage(); } pageCount = 0; printRingForUser(userShow, defid, doc, ref tmp, ref pageCount); } if (pageCount % 2 != 0) { doc.NewPage(); } pageCount = 0; } doc.Close(); context.Response.ClearContent(); context.Response.ContentType = "application/pdf"; context.Response.AddHeader("content-disposition", String.Format("inline;filename=PreviewSchedule.pdf")); context.Response.BinaryWrite((output as MemoryStream).ToArray()); }
public static void Convert(string inputFile, string outputFile) { iTextSharp.text.Document document = new iTextSharp.text.Document(PageSize.A4, 15f, 15f, 80f, 0f); var styles = new iTextSharp.text.html.simpleparser.StyleSheet(); try { iTextSharp.text.pdf.PdfWriter.GetInstance(document, new FileStream(outputFile, FileMode.OpenOrCreate, FileAccess.ReadWrite)); document.Open(); WebClient wc = new WebClient(); string param1 = wc.DownloadString(inputFile); param1 = FormatString(param1); // param1 = FormatImages(param1); List <IElement> param2 = HTMLWorker.ParseToList(new StringReader(param1), styles); for (int k = 0; k < param2.Count; k++) { switch (param2[k].Type) { case Element.IMGRAW: case Element.IMGTEMPLATE: case Element.HEADER: case Element.TITLE: break; //case Element.Script: case (Element.PARAGRAPH): default: document.Add((IElement)param2[k]); break; } } document.Close(); } catch (Exception ex) { throw ex; } }
protected void btnGenPdf_Click(object sender, EventArgs e) { iTextSharp.text.html.simpleparser.StyleSheet styles = new iTextSharp.text.html.simpleparser.StyleSheet(); styles.LoadStyle("Invoice-Wrp", "width", "1200px"); Response.ContentType = "application/pdf"; Response.AddHeader("content-disposition", "attachment;filename=PaymentInvoice.pdf"); Response.Cache.SetCacheability(HttpCacheability.NoCache); StringWriter sw = new StringWriter(); HtmlTextWriter hw = new HtmlTextWriter(sw); this.Page.RenderControl(hw); StringReader sr = new StringReader(sw.ToString()); Document pdfDoc = new Document(PageSize.A4, 50f, 50f, 50f, 50f); HTMLWorker htmlparser = new HTMLWorker(pdfDoc); PdfWriter.GetInstance(pdfDoc, Response.OutputStream); pdfDoc.Open(); htmlparser.Parse(sr); pdfDoc.Close(); Response.Write(pdfDoc); Response.End(); }
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(); }
private byte[] CreatePDF(string html) { Document document = new Document(); document.SetPageSize(iTextSharp.text.PageSize.A4.Rotate()); document.SetMargins(50, 50, 10, 40); var output = new MemoryStream(); var writer = PdfWriter.GetInstance(document, output); writer.PageEvent = new ImpactAnalysisHeaderHandler(); document.Open(); PdfPTable frontPage = CreateFrontPage(); document.Add(frontPage); iTextSharp.text.html.simpleparser.StyleSheet styles = new iTextSharp.text.html.simpleparser.StyleSheet(); var elem = HTMLWorker.ParseToList(new StringReader(html), styles); foreach (IElement item in elem) { if (item is PdfPTable) { PdfPTable t = item as PdfPTable; if (t != null) { t.SplitLate = false; t.KeepTogether = true; PdfPHelper.FixTables(t); PdfPHelper.FixMainRowsPadding(t); document.Add(t); } } } document.Close(); return(output.ToArray()); }
private void CreatePDFFromHTMLFile(string html, string FileName) { TextReader reader = new StringReader(html); // step 1: creation of a document-object Document document = new Document(PageSize.A3, 30, 30, 30, 30); // step 2: // we create a writer that listens to the document // and directs a XML-stream to a file PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(FileName, 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.Style = 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(); }
/// <summary> Gets the CSS classes. </summary> /// <returns> The CSS classes. </returns> public static StyleSheet GetStyleSheet() { string pdfStyleSheet = OutputSettings.Instance.StyleSheet; if (string.IsNullOrWhiteSpace(pdfStyleSheet)) { return null; } StylesheetParser ssp = new StylesheetParser(); string css = File.ReadAllText(HttpContext.Current.Server.MapPath(pdfStyleSheet)); Stylesheet stylesheet = ssp.Parse(css); StyleSheet styles = new StyleSheet(); foreach (RuleSet ruleSet in stylesheet.RuleSets) { Dictionary<string, string> attributes = ruleSet.Declarations.ToDictionary( declaration => declaration.Name, declaration => declaration.Expression.ToString()); foreach (Selector selector in ruleSet.Selectors) { if (selector.ToString().StartsWith(".", StringComparison.OrdinalIgnoreCase)) { styles.LoadStyle(selector.ToString(), attributes); } else { styles.LoadTagStyle(selector.ToString(), attributes); } } } return styles; }
public byte[] Render(string htmlText, string pageTitle) { byte[] renderedBuffer; using (var outputMemoryStream = new MemoryStream()) { using (var pdfDocument = new Document(PageSize.A4, HorizontalMargin, HorizontalMargin, VerticalMargin, VerticalMargin)) { string arialuniTff = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "ARIALUNI.TTF"); FontFactory.Register(arialuniTff); 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)) { StyleSheet styleSheet = new StyleSheet(); styleSheet.LoadTagStyle(HtmlTags.BODY, HtmlTags.FACE, "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; }
protected void Page_Load(object sender, EventArgs e) { long actionId = Convert.ToInt64(Request.QueryString["id"]); int companyId = Convert.ToInt32(Request.QueryString["companyId"]); var company = new Company(companyId); var res = ActionResult.NoAction; var user = HttpContext.Current.Session["User"] as ApplicationUser; var dictionary = HttpContext.Current.Session["Dictionary"] as Dictionary <string, string>; var action = IncidentAction.ById(actionId, user.CompanyId); string path = HttpContext.Current.Request.PhysicalApplicationPath; if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase)) { path = string.Format(CultureInfo.InvariantCulture, @"{0}\", path); } var formatedDescription = ToolsPdf.NormalizeFileName(action.Description); formatedDescription = formatedDescription.Replace(@"\", "/"); string fileName = string.Format( CultureInfo.InvariantCulture, @"{0}_{1}_Data_{2:yyyyMMddhhmmss}.pdf", dictionary["Item_IncidentAction"], formatedDescription, DateTime.Now); string type = string.Empty; string origin = string.Empty; string originSufix = string.Empty; string reporterType = string.Empty; string reporter = string.Empty; if (action.ActionType == 1) { type = dictionary["Item_IncidentAction_Type1"]; } if (action.ActionType == 2) { type = dictionary["Item_IncidentAction_Type2"]; } if (action.ActionType == 3) { type = dictionary["Item_IncidentAction_Type3"]; } if (action.Origin == 1) { origin = dictionary["Item_IncidentAction_Origin1"]; } if (action.Origin == 2) { origin = dictionary["Item_IncidentAction_Origin2"]; } if (action.Origin == 3) { if (action.IncidentId.HasValue) { var incident = Incident.GetById(action.IncidentId.Value, action.CompanyId); origin = string.Format( CultureInfo.InvariantCulture, @"{0}: {1}", dictionary["Item_Incident"], incident.Description); } } if (action.Origin == 4) { if (action.BusinessRiskId.HasValue) { if (action.BusinessRiskId > Constant.DefaultId) { var businessRisk = BusinessRisk.ById(action.CompanyId, action.BusinessRiskId.Value); origin = businessRisk.Description; originSufix = " (" + dictionary["Item_BusinessRisk"] + ")"; } } } if (action.Origin == 5) { if (action.ObjetivoId.HasValue) { if (action.ObjetivoId > Constant.DefaultId) { var objetivo = Objetivo.ById(Convert.ToInt32(action.ObjetivoId.Value), action.CompanyId); origin = objetivo.Name; originSufix = " (" + dictionary["Item_Objetivo"] + ")"; } } } if (action.Origin == 6) { if (action.Oportunity.Id > Constant.DefaultId) { var oportunidad = Oportunity.ById(Convert.ToInt32(action.Oportunity.Id), action.CompanyId); origin = oportunidad.Description; originSufix = " (" + dictionary["Item_Oportunity"] + ")"; } } else { switch (action.ReporterType) { case 1: reporterType = dictionary["Item_IncidentAction_ReporterType1"]; if (action.Department != null && action.Department.Id > 0) { var department = Department.ById(action.Department.Id, action.CompanyId); reporter = department.Description; } break; case 2: reporterType = dictionary["Item_IncidentAction_ReporterType2"]; if (action.Provider != null && action.Provider.Id > 0) { var provider = Provider.ById(action.Provider.Id, action.CompanyId); reporter = provider.Description; } break; case 3: reporterType = dictionary["Item_IncidentAction_ReporterType3"]; if (action.Customer != null && action.Customer.Id > 0) { var customer = Customer.ById(action.Customer.Id, action.CompanyId); reporter = customer.Description; } break; default: break; } } string status = string.Empty; var document = new iTextSharp.text.Document(PageSize.A4, 30, 30, 65, 55); var writer = PdfWriter.GetInstance(document, new FileStream(Request.PhysicalApplicationPath + "\\Temp\\" + fileName, FileMode.Create)); writer.PageEvent = new TwoColumnHeaderFooter { CompanyLogo = string.Format(CultureInfo.InvariantCulture, @"{0}\images\logos\{1}.jpg", path, companyId), IssusLogo = string.Format(CultureInfo.InvariantCulture, "{0}issus.png", path), Date = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", DateTime.Now), CreatedBy = user.UserName, CompanyId = action.CompanyId, CompanyName = company.Name, Title = dictionary["Item_IncidentAction"].ToUpperInvariant() }; document.Open(); var styles = new iTextSharp.text.html.simpleparser.StyleSheet(); var hw = new iTextSharp.text.html.simpleparser.HTMLWorker(document); var widths = new float[] { 15f, 30f, 15f, 30f }; var table = new PdfPTable(4) { WidthPercentage = 100, HorizontalAlignment = 0 }; table.SetWidths(widths); var borderSides = Rectangle.RIGHT_BORDER + Rectangle.LEFT_BORDER; var borderTBL = Rectangle.TOP_BORDER + Rectangle.BOTTOM_BORDER + Rectangle.LEFT_BORDER; var borderTBR = Rectangle.TOP_BORDER + Rectangle.BOTTOM_BORDER + Rectangle.RIGHT_BORDER; var borderBL = Rectangle.BOTTOM_BORDER + Rectangle.LEFT_BORDER; var borderBR = Rectangle.BOTTOM_BORDER + Rectangle.RIGHT_BORDER; var alignLeft = Element.ALIGN_LEFT; var alignRight = Element.ALIGN_RIGHT; var labelFont = new Font(this.arial, 10, Font.NORMAL, BaseColor.DARK_GRAY); var valueFont = new Font(this.arial, 10, Font.NORMAL, BaseColor.BLACK); // Descripción table.AddCell(LabelCell(dictionary["Item_IncidentAction"], Rectangle.NO_BORDER)); table.AddCell(ValueCell(action.Number.ToString() + " - " + action.Description, ToolsPdf.BorderNone, alignLeft, 3)); // Tipo table.AddCell(LabelCell(dictionary["Item_IncidentAction_Label_Type"], Rectangle.NO_BORDER)); table.AddCell(ValueCell(type, ToolsPdf.BorderNone, alignLeft, 1)); // Origen table.AddCell(LabelCell(dictionary["Item_IncidentAction_Label_Origin"], Rectangle.NO_BORDER)); table.AddCell(ValueCell(origin + originSufix, ToolsPdf.BorderNone, alignLeft, 3)); // Reportador if (action.Origin != 4 && action.Origin != 5 && !string.IsNullOrEmpty(reporter)) { table.AddCell(LabelCell(dictionary["Item_IncidentAction_Label_Reporter"], Rectangle.NO_BORDER)); table.AddCell(ValueCell(reporterType + " (" + reporter + ")", ToolsPdf.BorderNone, alignLeft, 3)); } // WhatHappend table.AddCell(SeparationRow()); table.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_WhatHappened"])); table.AddCell(TextAreaCell(Environment.NewLine + action.WhatHappened, borderSides, alignLeft, 4)); table.AddCell(BlankRow()); table.AddCell(TextAreaCell(dictionary["Item_IncidentAction_Field_Responsible"] + ": " + action.WhatHappenedBy.FullName, borderBL, alignLeft, 2)); table.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "{0}: {1:dd/MM/yyyy}", dictionary["Common_Date"], action.WhatHappenedOn), borderBR, alignRight, 2)); // Causes table.AddCell(SeparationRow()); table.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Causes"])); table.AddCell(TextAreaCell(Environment.NewLine + action.Causes, borderSides, alignLeft, 4)); table.AddCell(BlankRow()); table.AddCell(TextAreaCell(dictionary["Item_IncidentAction_Field_Responsible"] + ": " + action.CausesBy.FullName, borderBL, alignLeft, 2)); table.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "{0}: {1:dd/MM/yyyy}", dictionary["Common_Date"], action.CausesOn), borderBR, alignRight, 2)); // Actions table.AddCell(SeparationRow()); table.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Actions"])); table.AddCell(TextAreaCell(Environment.NewLine + action.Actions, borderSides, alignLeft, 4)); table.AddCell(BlankRow()); table.AddCell(TextAreaCell(dictionary["Item_IncidentAction_Field_Responsible"] + ": " + action.ActionsBy.FullName, borderBL, alignLeft, 2)); table.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "{0}: {1:dd/MM/yyyy}", dictionary["Common_DateExecution"], action.ActionsOn), borderBR, alignRight, 2)); // Monitoring table.AddCell(SeparationRow()); table.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Monitoring"])); table.AddCell(TextAreaCell(Environment.NewLine + action.Monitoring, ToolsPdf.BorderAll, alignLeft, 4)); // Close table.AddCell(SeparationRow()); table.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Close"])); table.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "\n{0}: {1}", dictionary["Item_IncidentAction_Field_Responsible"], action.ClosedBy.FullName), borderTBL, alignLeft, 2)); table.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "\n{0}: {1:dd/MM/yyyy}", dictionary["Common_DateClose"], action.ClosedOn), borderTBR, alignRight, 2)); // Notes table.AddCell(SeparationRow()); table.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Notes"])); table.AddCell(TextAreaCell(Environment.NewLine + action.Notes, ToolsPdf.BorderAll, alignLeft, 4)); document.Add(table); // Costes var costs = IncidentActionCost.GetByIncidentActionId(actionId, companyId); if (costs.Count > 0) { var times = new Font(arial, 8, Font.NORMAL, BaseColor.BLACK); var fontSummary = new Font(arial, 9, Font.BOLD, BaseColor.BLACK); var headerFontFinal = new Font(headerFont, 9, Font.NORMAL, BaseColor.BLACK); // @alex: hay que crear la tabla con 6 columnas en lugar de 5 //var tableCosts = new PdfPTable(5) var tableCosts = new PdfPTable(6) { WidthPercentage = 100, HorizontalAlignment = 1, SpacingBefore = 20f, SpacingAfter = 30f }; // @alex: se añade una nueva columna de 10f para la fecha //tableCosts.SetWidths(new float[] { 35f, 10f, 10f, 10f, 20f }); tableCosts.SetWidths(new float[] { 35f, 10f, 10f, 10f, 10f, 20f }); tableCosts.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentCost_Header_Description"])); // @alex: se añade una nueva cabecera tableCosts.AddCell(ToolsPdf.HeaderCell(dictionary["Common_Date"])); tableCosts.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentCost_Header_Amount"])); tableCosts.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentCost_Header_Quantity"])); tableCosts.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentCost_Header_Total"])); tableCosts.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentCost_Header_ReportedBy"])); decimal total = 0; decimal totalAccion = 0; int cont = 0; int contAccion = 0; // Acciones foreach (var cost in costs.Where(c => c.Active == true)) { tableCosts.AddCell(ToolsPdf.DataCell(cost.Description, times)); // @alex: se añade la columna en la misma posición que en el listado de la ficha tableCosts.AddCell(ToolsPdf.DataCellCenter(cost.Date, times)); tableCosts.AddCell(ToolsPdf.DataCellMoney(cost.Amount, times)); tableCosts.AddCell(ToolsPdf.DataCellMoney(cost.Quantity, times)); tableCosts.AddCell(ToolsPdf.DataCellMoney(cost.Quantity * cost.Amount, times)); tableCosts.AddCell(ToolsPdf.DataCellCenter(cost.Responsible.FullName, times)); total += cost.Amount * cost.Quantity; totalAccion = cost.Amount * cost.Quantity; cont++; contAccion++; } tableCosts.AddCell(new PdfPCell(new Phrase(string.Format( CultureInfo.InvariantCulture, @"{0} {2}: {1}", dictionary["Common_RegisterCount"], contAccion, dictionary["Item_IncidentAction"]), times)) { Border = Rectangle.TOP_BORDER, BackgroundColor = ToolsPdf.SummaryBackgroundColor, Padding = 6f, PaddingTop = 4f, Colspan = 3//@ alex: al haber una columna más el colspan crece de 2 a 3 }); tableCosts.AddCell(new PdfPCell(new Phrase(dictionary["Common_Total"], times)) { Border = Rectangle.TOP_BORDER, BackgroundColor = ToolsPdf.SummaryBackgroundColor, Padding = 6f, PaddingTop = 4f, Colspan = 1, HorizontalAlignment = Rectangle.ALIGN_RIGHT }); tableCosts.AddCell(new PdfPCell(new Phrase(Tools.PdfMoneyFormat(total), times)) { Border = Rectangle.TOP_BORDER, BackgroundColor = ToolsPdf.SummaryBackgroundColor, Padding = 6f, PaddingTop = 4f, Colspan = 1, HorizontalAlignment = Rectangle.ALIGN_RIGHT, }); tableCosts.AddCell(new PdfPCell(new Phrase(string.Format(string.Empty, times))) { Border = Rectangle.TOP_BORDER, BackgroundColor = ToolsPdf.SummaryBackgroundColor, Padding = 6f, PaddingTop = 4f, Colspan = 1 }); document.SetPageSize(PageSize.A4.Rotate()); document.NewPage(); document.Add(tableCosts); } document.Close(); Response.ClearContent(); Response.ClearHeaders(); Response.AddHeader("Content-Disposition", "inline;filename=Accion.pdf"); Response.ContentType = "application/pdf"; Response.WriteFile(Request.PhysicalApplicationPath + "\\Temp\\" + fileName); Response.Flush(); Response.Clear(); }
public void PDFFormato1(string FilePath, int numPaginas, string[] cuerpoHTML, string nomDoc, string title) { try { //Se Crea El Documento tamaño Carta Document document = new Document(PageSize.LETTER, 100, 100, 100, 100); //Se Obtiene la ruta del servidor string ruta = HttpContext.Current.Server.MapPath("~/");; //Indicamos donde se va a guardar eldocumento PdfWriter.GetInstance(document, new FileStream(ruta + "\\\\" + nomDoc + ".pdf", FileMode.Create)); //se abre el documento document.Open(); document.AddTitle(title); for (int i = 0; i < numPaginas; i++) { string HTML = ""; // Crea una imagen iTextSharp.text.Image pdfImage; iTextSharp.text.Image pdflogo; iTextSharp.text.Image pdfInfo; //Se obtiene la ruta de la imagen pdfImage = iTextSharp.text.Image.GetInstance(ruta + "/images/marca.png"); pdflogo = iTextSharp.text.Image.GetInstance(ruta + "/images/logo.png"); pdfInfo = iTextSharp.text.Image.GetInstance(ruta + "/images/Info.png"); //se pone el tamaño pdfImage.ScaleToFit(200, 790); pdflogo.ScaleToFit(200, 790); pdfInfo.ScaleToFit(400, 790); //se Indica la posicion pdfImage.Alignment = iTextSharp.text.Image.UNDERLYING; pdfImage.SetAbsolutePosition(0, 1); pdflogo.Alignment = iTextSharp.text.Image.UNDERLYING; pdflogo.SetAbsolutePosition(400, 685); pdfInfo.Alignment = iTextSharp.text.Image.UNDERLYING; pdfInfo.SetAbsolutePosition(200, 3); //Se agrega la imagen al documento document.Add(pdfImage); document.Add(pdflogo); document.Add(pdfInfo); //se crea un objeto para estilos iTextSharp.text.html.simpleparser.StyleSheet styles = new iTextSharp.text.html.simpleparser.StyleSheet(); //obleto tipo html //iTextSharp.text.html.simpleparser.HTMLWorker hw = new iTextSharp.text.html.simpleparser.HTMLWorker(document,styles); styles.LoadTagStyle("p", "color", "red"); styles.LoadStyle("redBigText", "size", "20pt"); styles.LoadStyle("redBigText", "color", "RED"); //obleto tipo html iTextSharp.text.html.simpleparser.HTMLWorker hw = new iTextSharp.text.html.simpleparser.HTMLWorker(document); if (cuerpoHTML.Count() > i) { HTML = cuerpoHTML[i]; } else { HTML = ""; } /* Paragraph p = new Paragraph(); * p.IndentationLeft = 100; * HTML.HorizontalAlignment = Element.ALIGN_LEFT; * p.Add(outerTable); * document.Add(p);*/ //hw.Parse(new StringReader(HTML),styles); //var parsedHtmlElements = HTMLWorker.ParseToList(new StringReader(HTML), styles); hw.Parse(new StringReader(HTML)); // HTMLWorker.ParseToList(new StringReader(HTML), styles); document.NewPage(); } //se Cierra el document0 document.Close(); //se muestra el documento mostrarPDF(nomDoc + ".pdf", ruta); } catch (Exception ex) { Console.Write(ex.Message); } }
public void ProcessRequest(HttpContext context) { int ShowID = Convert.ToInt32(context.Request["showid"]); int RingID = Convert.ToInt32(context.Request["ringid"]); String cmd = context.Request["doc"].ToString(); Shows show = new Shows(ShowID); ShowDetails sd = new ShowDetails(); DataTable table = sd.GetShowDetails(ShowID).Tables[0]; String pdfPath = context.Server.MapPath(cmd + ".pdf"); Boolean publish = false; if (!String.IsNullOrEmpty(context.Request["publish"]) && context.Request["publish"].ToString() == "1") publish = true; Document doc = new Document(PageSize.A4, -50, -50, 2, 2); Stream output; if (publish) { String path = context.Server.MapPath(@"..\schedules\"); path += DateTime.Today.ToString("yyyy"); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } path += String.Format("\\{0:yyyyMM}_{1}.pdf", show.ShowDate, show.ShowName); output = new FileStream(path, FileMode.Create); } else { output = new MemoryStream(); } var writer = PdfWriter.GetInstance(doc, output); StyleSheet sheet = new StyleSheet(); doc.Open(); Font font = new Font(Font.COURIER, 10, Font.NORMAL, Color.BLACK); Font resFont = new Font(Font.COURIER, 9, Font.ITALIC, Color.BLACK); Font headerFont = new Font(Font.COURIER, 10, Font.BOLD, Color.BLACK); Font headerFont2 = new Font(Font.HELVETICA, 12, Font.BOLD, Color.BLACK); Font ClassTitleFont = new Font(Font.HELVETICA, 16, Font.NORMAL, Color.BLACK); ShowClasses sc = new ShowClasses(); Rings currentRing = new Rings(RingID); List<ShowClasses> showClasses = ShowClasses.GetAllClassesForShowRing(ShowID, RingID); foreach (ShowClasses showClass in showClasses) { PdfPTable ptable = new PdfPTable(3); PdfPCell cell; String grades = showClass.Grades; if (grades.Length == 1) { grades = "Grade " + grades; } else { grades = "Grades " + grades[0] + "-" + grades[grades.Length - 1]; } String tmp = String.Format("Ring No:{5} Class No:{0} {1} {2} {3} ({4})", showClass.ClassNo, showClass.longHeight, showClass.longCatagory, showClass.LongClassName, grades, currentRing.RingNo); cell = new PdfPCell(new Phrase(new Chunk(tmp, ClassTitleFont))); cell.Colspan = 3; cell.BorderWidth = 0; ptable.AddCell(cell); cell = new PdfPCell(new Phrase(new Chunk("", ClassTitleFont))); cell.Colspan = 3; cell.BorderWidth = 0; ptable.AddCell(cell); ptable.AddCell(cell); ptable.AddCell(cell); doc.Add(ptable); DataSet callingList = sc.getCallingList(ShowID, showClass.ID); float[] colWidths = { 35, 50, 200, 200 }; PdfPTable callingListTbl = new PdfPTable(colWidths); cell = new PdfPCell(new Phrase(new Chunk("RO", headerFont))); cell.BorderWidth = 0; callingListTbl.AddCell(cell); cell = new PdfPCell(new Phrase(new Chunk("Ring No", headerFont))); cell.BorderWidth = 0; callingListTbl.AddCell(cell); cell = new PdfPCell(new Phrase(new Chunk("Handler", headerFont))); cell.BorderWidth = 0; callingListTbl.AddCell(cell); cell = new PdfPCell(new Phrase(new Chunk("Dog Name", headerFont))); cell.BorderWidth = 0; callingListTbl.AddCell(cell); int altFlag = 0; Color altLine = Color.LIGHT_GRAY; foreach (DataRow row in callingList.Tables[0].Rows) { Color altColor = Color.WHITE; if (altFlag % 2 == 0 && showClass.EntryType != 5) { altColor = altLine; } cell = new PdfPCell(new Phrase(new Chunk(row["RO"].ToString(), font))); cell.BorderWidth = 0; cell.BorderWidth = 2; cell.BorderColor = Color.RED; cell.BackgroundColor = altColor; cell.HorizontalAlignment = Element.ALIGN_RIGHT; callingListTbl.AddCell(cell); if (showClass.EntryType == 5) { cell = new PdfPCell(new Phrase(new Chunk("Team Name:", headerFont2))); cell.BackgroundColor = altColor; cell.BorderWidth = 1; cell.Colspan = 2; cell.FixedHeight = 30F; callingListTbl.AddCell(cell); cell = new PdfPCell(new Phrase(new Chunk(ShowClasses.expandHeight(row), headerFont2))); cell.BackgroundColor = altColor; cell.BorderWidth = 1; cell.FixedHeight = 30F; cell.HorizontalAlignment = Element.ALIGN_RIGHT; callingListTbl.AddCell(cell); cell = new PdfPCell(new Phrase(new Chunk("", font))); cell.BackgroundColor = altColor; cell.Colspan = 1; cell.BorderWidth = 0; cell.FixedHeight = 30F; callingListTbl.AddCell(cell); } int borderWidth = 0; if (showClass.EntryType == 5) borderWidth = 1; cell = new PdfPCell(new Phrase(new Chunk(row["RingNumber"].ToString(), font))); cell.HorizontalAlignment = Element.ALIGN_RIGHT; cell.BackgroundColor = altColor; cell.BorderWidth = borderWidth; callingListTbl.AddCell(cell); int DefaultHandler = Convert.ToInt32(row["DefaultHandler"]); int AltHandler = Convert.ToInt32(row["AltHandler"]); String handlerName = row["Name"].ToString(); User user; if (DefaultHandler > 0) { user = new User(DefaultHandler); handlerName = user.Name; } if (AltHandler > 0) { user = new User(AltHandler); handlerName = user.Name; } cell = new PdfPCell(new Phrase(new Chunk(handlerName, font))); cell.BackgroundColor = altColor; cell.BorderWidth = borderWidth; callingListTbl.AddCell(cell); cell = new PdfPCell(new Phrase(new Chunk(row["KCName"].ToString(), font))); cell.BackgroundColor = altColor; cell.BorderWidth = borderWidth; callingListTbl.AddCell(cell); if (showClass.EntryType == 4 || showClass.EntryType == 5) { int UserID = Convert.ToInt32(row["UserID"]); int DogID = Convert.ToInt32(row["DogID"]); //MultiDog md = new MultiDog(UserID, DogID, showClass.ID); List<MultiDog> otherHandlers = MultiDog.getMultiDog(UserID, DogID, showClass.ID); String reserves = ""; int dogCnt = 0; foreach (MultiDog md in otherHandlers) { String res = ""; if (dogCnt > 2 && md.Handlername.Length > 0) { if (reserves.Length > 0) reserves += "; "; reserves += String.Format("{0} & {1}", md.Handlername, md.Dogname); } if (dogCnt < 3) { cell = new PdfPCell(new Phrase(new Chunk("", font))); cell.BorderWidth = 0; cell.BackgroundColor = altColor; cell.HorizontalAlignment = Element.ALIGN_RIGHT; callingListTbl.AddCell(cell); cell = new PdfPCell(new Phrase(new Chunk(res, font))); cell.HorizontalAlignment = Element.ALIGN_RIGHT; cell.BackgroundColor = altColor; cell.BorderWidth = 1; callingListTbl.AddCell(cell); cell = new PdfPCell(new Phrase(new Chunk(md.Handlername, font))); cell.BackgroundColor = altColor; cell.BorderWidth = 1; callingListTbl.AddCell(cell); cell = new PdfPCell(new Phrase(new Chunk(md.Dogname, font))); cell.BackgroundColor = altColor; cell.BorderWidth = 1; callingListTbl.AddCell(cell); } dogCnt++; } cell = new PdfPCell(new Phrase(new Chunk("", font))); cell.BackgroundColor = altColor; cell.BorderWidth = 0; cell.FixedHeight = 30F; callingListTbl.AddCell(cell); cell = new PdfPCell(new Phrase(new Chunk("Reserves: " + reserves, resFont))); cell.BackgroundColor = altColor; cell.Colspan = 3; cell.BorderWidth = 1; cell.FixedHeight = 30F; callingListTbl.AddCell(cell); } altFlag++; } doc.Add(callingListTbl); doc.NewPage(); } doc.Close(); if (publish) { } else { context.Response.ClearContent(); context.Response.ContentType = "application/pdf"; context.Response.AddHeader("content-disposition", String.Format("inline;filename=PreviewSchedule.pdf")); context.Response.BinaryWrite((output as MemoryStream).ToArray()); } }
public void ProcessRequest(HttpContext context) { int ShowID = Convert.ToInt32(context.Request["showid"]); Shows show = new Shows(ShowID); String sortby = Convert.ToString(context.Request["sortby"]); Document doc = new Document(PageSize.A4, -50, -50, 2, 2); Stream output = new MemoryStream(); var writer = PdfWriter.GetInstance(doc, output); StyleSheet sheet = new StyleSheet(); doc.Open(); PdfPTable ptable = new PdfPTable(1); PdfPCell cell; cell = new PdfPCell(); cell.FixedHeight = 150; cell.BorderWidth = 0; ptable.AddCell(cell); cell = new PdfPCell(new Phrase(new Chunk("Master List", bigFont))); cell.HorizontalAlignment = Element.ALIGN_CENTER; cell.BorderWidth = 0; cell.FixedHeight = 100; ptable.AddCell(cell); cell = new PdfPCell(new Phrase(new Chunk(show.ShowName, bigFont))); cell.HorizontalAlignment = Element.ALIGN_CENTER; cell.BorderWidth = 0; ptable.AddCell(cell); cell = new PdfPCell(new Phrase(new Chunk(show.ShowDate.ToString("dd MMM yyyy"), bigFont))); cell.BorderWidth = 0; cell.HorizontalAlignment = Element.ALIGN_CENTER; ptable.AddCell(cell); doc.Add(ptable); doc.NewPage(); float[] colWidths = { 150, 65, 175, 200}; int count = 0; String lastName = ""; DataSet masterList = DogClasses.getMasterList(ShowID, sortby); String tmp = ""; ptable = new PdfPTable(colWidths); cell = new PdfPCell(new Phrase(new Chunk("Handler Name", headerFont))); cell.BorderWidth = 0; ptable.AddCell(cell); cell = new PdfPCell(new Phrase("Ring No", headerFont)); cell.BorderWidth = 0; ptable.AddCell(cell); cell = new PdfPCell(new Phrase("Dog Name", headerFont)); cell.BorderWidth = 0; ptable.AddCell(cell); cell = new PdfPCell(new Phrase("Class Details", headerFont)); cell.BorderWidth = 0; ptable.AddCell(cell); doc.Add(ptable); bool topBorder = false; Color altLine = new Color(224, 224, 224); List<Dogs> userDogs = null; foreach (DataRow row in masterList.Tables[0].Rows) { Color altColor = Color.WHITE; if (count % 2 == 0 ) { altColor = altLine; } MasterList masterListItem = new MasterList(row); ptable = new PdfPTable(colWidths); if (lastName == masterListItem.Name) { cell = new PdfPCell(new Phrase(new Chunk("", normalFont))); topBorder = false; } else { if (userDogs != null) { altColor = (altColor == Color.WHITE ? altLine : Color.WHITE); foreach (Dogs di in userDogs.Where(x => x.Status != -1).ToList()) { List<DogClasses> dcList = DogClasses.Retrieve(di.ID, ShowID); cell = new PdfPCell(new Phrase(new Chunk("", normalFont))); cell.BorderWidth = 0; cell.BackgroundColor = altColor; ptable.AddCell(cell); cell = new PdfPCell(new Phrase(new Chunk("", normalFont))); cell.BorderWidth = 0; cell.BackgroundColor = altColor; ptable.AddCell(cell); ptable.AddCell(AddDogDetails(di, dcList, altColor, false)); cell = new PdfPCell(new Phrase(new Chunk("", normalFont))); cell.BorderWidth = 0; cell.BackgroundColor = altColor; ptable.AddCell(cell); count++; altColor = (count % 2 == 0 ? altLine : Color.WHITE); } count++; } topBorder = true; tmp = masterListItem.Name; //if (masterListItem.AltHandler > 0) //{ // User u = new User(masterListItem.AltHandler); // tmp = u.Name; //} var adminInd = ""; var us = new UserShows(masterListItem.UserId, ShowID); var trans = Transaction.GetTransactionForShowUser(us.ID); if (trans.Any() && trans.FirstOrDefault().EnteredBy == (int) Transaction.ENTERED_BY.SHOW_ADMIN_ENTRY) { adminInd = "(A) "; } User u = new User(masterListItem.UserId); userDogs = Dogs.GetAllDogsForHandler(masterListItem.UserId, show.ShowDate); Paragraph para = new Paragraph(); para.Add(new Chunk(adminInd + tmp + Environment.NewLine, normalFont)); para.Add(new Chunk(u.Address + Environment.NewLine , normalFont)); para.Add(new Chunk(u.Postcode, normalFont)); para.Add(new Chunk(Environment.NewLine, normalFont)); if (!string.IsNullOrEmpty(u.EmailAddress)) { para.Add(new Chunk("Email " + u.EmailAddress + Environment.NewLine, normalFont)); } if (!string.IsNullOrEmpty(u.HomePhone)) { para.Add(new Chunk("Home Phone " + u.HomePhone + Environment.NewLine, normalFont)); } if (!string.IsNullOrEmpty(u.Mobile)) { para.Add(new Chunk("Mobile Phone " + u.Mobile + Environment.NewLine, normalFont)); } cell = new PdfPCell(para); cell.BorderColorTop = Color.BLACK; cell.BorderWidthTop = 1; } cell.BorderWidth = 0; cell.BackgroundColor = altColor; ptable.AddCell(cell); cell = new PdfPCell(new Phrase(new Chunk(masterListItem.RingNumber.ToString(), normalFont))); cell.BorderWidth = 0; cell.HorizontalAlignment = Element.ALIGN_CENTER; cell.BackgroundColor = altColor; if (topBorder) { cell.BorderColorTop = Color.BLACK; cell.BorderWidthTop = 1; } ptable.AddCell(cell); var d = userDogs.FirstOrDefault(x => x.ID == masterListItem.DogID); if (d != null) { List<DogClasses> dcList = DogClasses.Retrieve(masterListItem.DogID, ShowID); ptable.AddCell(AddDogDetails(d, dcList, altColor, topBorder)); d.Status = -1; PdfPTable classDetailsTbl = new PdfPTable(1); var p = new Paragraph(); bool first = true; int champClass = -1; foreach (DogClasses dc in dcList) { ShowClasses sc = new ShowClasses(dc.Classid); if (!first) { p.Add(new Chunk(String.Format(",{0,3}:", sc.ClassNo), normalFont)); } else { p.Add(new Chunk(String.Format("{0,3}:", sc.ClassNo), normalFont)); } p.Add(new Chunk(String.Format("{0,3}", dc.RO), normalFontBold)); first = false; if (sc.EntryType == (int)Fpp.Core.Enums.EntryTypes.Championship) { champClass = d.ID; } } cell = new PdfPCell(p); cell.BorderWidth = 0; classDetailsTbl.AddCell(cell); cell = new PdfPCell(classDetailsTbl); cell.BorderWidth = 0; cell.BackgroundColor = altColor; if (topBorder) { cell.BorderColorTop = Color.BLACK; cell.BorderWidthTop = 1; } ptable.AddCell(cell); if (champClass > -1) { cell = new PdfPCell(); cell.BorderWidth = 0; cell.BackgroundColor = altColor; cell.Colspan = 2; ptable.AddCell(cell); p = new Paragraph(); var champWins = DogHistory.GetRecordedWins(champClass); p.Add(new Phrase(new Chunk("Grade 6 Wins" + Environment.NewLine, normalFontBold) )); foreach (var win in champWins) { p.Add(new Chunk(String.Format("{0:dd-MM-yyyy} {1} {2} {3} ", win.WinDate, win.ShowName, win.ClassWon, win.Comments) + Environment.NewLine, normalFont)); } cell = new PdfPCell(p); cell.Colspan = 2; cell.FixedHeight = 100; cell.BorderWidth = 0; cell.BackgroundColor = altColor; ptable.AddCell(cell); } } else { } doc.Add(ptable); lastName = masterListItem.Name; count++; //if (count > 100 ) break; } doc.Close(); context.Response.ClearContent(); context.Response.ContentType = "application/pdf"; context.Response.AddHeader("content-disposition", String.Format("inline;filename=MasterList.pdf")); context.Response.BinaryWrite((output as MemoryStream).ToArray()); }
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); }
public void Dispose() { this._doc.Dispose(); this.HTML = string.Empty; this.page = null; this.style = null; GC.SuppressFinalize(this); }
/// pending: public static StyleSheet getStyleSheet_ApprovedSwitch() { StyleSheet Style = new StyleSheet(); Style.LoadTagStyle(HtmlTags.BODY, HtmlTags.FONTSIZE, "5"); Style.LoadTagStyle(HtmlTags.TH, HtmlTags.TEXTALIGN, "center"); Style.LoadTagStyle(HtmlTags.TH, HtmlTags.FONTWEIGHT, "bolder"); Style.LoadStyle("title", HtmlTags.TEXTALIGN, "center"); //Style.LoadStyle("title", HtmlTags.FONTSIZE, "1em"); Style.LoadStyle("title", HtmlTags.FONTWEIGHT, "bolder"); Style.LoadStyle("left", HtmlTags.WIDTH, "40%"); Style.LoadStyle("left", HtmlTags.FONTWEIGHT, "bold"); Style.LoadStyle("left", "padding", "0px"); Style.LoadStyle("right", "padding", "0px"); Style.LoadStyle("right", HtmlTags.WIDTH, "60%"); Style.LoadStyle("right", HtmlTags.PADDINGLEFT, "0.5em"); return Style; }
/// <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(); }
// --------------------------------------------------------------------------- /** * Sets the styles for the HTML to PDF conversion * @param styles a StyleSheet object */ public void SetStyles(StyleSheet styles) { this.styles = styles; }
public static ArrayList ParseToList(TextReader reader, StyleSheet style) { return ParseToList(reader, style, null); }
public static ArrayList ParseToList(TextReader reader, StyleSheet style, Hashtable interfaceProps) { HTMLWorker worker = new HTMLWorker(null); if (style != null) worker.Style = style; worker.document = worker; worker.InterfaceProps = interfaceProps; worker.objectList = new ArrayList(); worker.Parse(reader); return worker.objectList; }
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); }
/// <summary> /// Creates a new PDF document template. Use PageSizes.{DocumentSize} /// </summary> public HtmlToPdfBuilder(Rectangle size) { this.PageSize = size; this._Pages = new List<HtmlPdfPage>(); this._Styles = new StyleSheet(); }
private byte[] CreatePDF(string html) { Document document = new Document(); document.SetPageSize(iTextSharp.text.PageSize.A4.Rotate()); document.SetMargins(50, 50, 10, 40); var output = new MemoryStream(); var writer = PdfWriter.GetInstance(document, output); writer.PageEvent = new ImpactAnalysisHeaderHandler(); document.Open(); PdfPTable frontPage = CreateFrontPage(); document.Add(frontPage); iTextSharp.text.html.simpleparser.StyleSheet styles = new iTextSharp.text.html.simpleparser.StyleSheet(); var elem = HTMLWorker.ParseToList(new StringReader(html), styles); foreach (IElement item in elem) { if (item is PdfPTable) { PdfPTable t = item as PdfPTable; if (t != null) { t.SplitLate = false; t.KeepTogether = true; PdfPHelper.FixTables(t); PdfPHelper.FixMainRowsPadding(t); document.Add(t); } } } document.Close(); return output.ToArray(); }
// public ActionResult QuotationPDF(string QuotationId) public FileResult QuotationPDF(string QuotationId) { string filenm = ""; var fpath = ""; string contentType = ""; try { //string QuotationId = frm["id"].ToString(); fpath = HttpContext.Server.MapPath("~/PDFFiles/Quotation/"); ssmtbl_QuotationModel objQuot = new ssmtbl_QuotationModel(); objQuot = objQuotAppData.GetOneQuotationForApproval(QuotationId); ssmtbl_FeasibilityModel modelFeasibility = new ssmtbl_FeasibilityModel(); modelFeasibility = objFesiData.GetOneFeasibility(Convert.ToInt32(objQuot.InquiryNo)); string str = objQuot.QuotationNo.Substring(0, 8); filenm = str + "_" + objQuot.CustomerName + "_" + objQuot.InquiryNo + "_" + objQuot.new_Version_No + ".pdf"; Document doc = new Document(PageSize.A4, 25, 25, 10, 20); PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(fpath + filenm, FileMode.Create)); doc.Open(); iTextSharp.text.html.simpleparser.StyleSheet styles = new iTextSharp.text.html.simpleparser.StyleSheet(); iTextSharp.text.html.simpleparser.HTMLWorker hw = new iTextSharp.text.html.simpleparser.HTMLWorker(doc); iTextSharp.text.Image image1 = iTextSharp.text.Image.GetInstance(HttpContext.Server.MapPath("~/NewCssAndTheme/img/ssmlogo.jpg")); image1.Alignment = iTextSharp.text.Image.ALIGN_CENTER; image1.SetAbsolutePosition(20, 780); image1.ScaleToFit(80f, 80f); doc.Add(image1); string pdfbody = "<div style='font: 10px; border= 1'>"; pdfbody += "<div style='text-align:center'>"; pdfbody += "<font size='3'>SHREE SIDDHESHWARI METAL FORGING PRIVATE LIMITED</font>"; pdfbody += "</div>"; pdfbody += "<div style='text-align:center;>"; pdfbody += "<font size='medium'>J-489/490,M.I.D.C BHOSARI, PUNE-26</font>"; pdfbody += "</div>"; pdfbody += "<div style='text-align:center;>"; pdfbody += "<font size='medium'>Email - [email protected] Tel: 020-27130120</font>"; pdfbody += "</div>"; //doc.Add(Chunk.NEWLINE); //hw.Parse(new StringReader(pdfbody)); pdfbody += "<div style='text-align:center;'>"; pdfbody += "<font size='3' font-weight='bold'>QUOTATION</font>"; pdfbody += "</div>"; //doc.Add(Chunk.NEWLINE); //hw.Parse(new StringReader(pdfbody)); pdfbody += "<div style='text-align:right; font-size: medium'>"; pdfbody += "<h4 style='text-align:right'>Quotation # " + objQuot.QuotationNo; pdfbody += "</h4>"; //pdfbody += "<small> Revision Number:" + objQuot.new_Version_No; pdfbody += "<small> Date: " + objQuot.CreatedOn.Date.ToString("dd-MMM-yyyy"); pdfbody += "</small>"; pdfbody += "</div>"; //doc.Add(Chunk.NEWLINE); //hw.Parse(new StringReader(pdfbody)); pdfbody += "<div style='text-align:Left; font-size: medium'>"; pdfbody += "To, <br/>" + objQuot.CustomerName; pdfbody += "<br/>" + objQuot.address; pdfbody += "</div>"; // pdfbody += "<table border='0' cellpadding='5' cellspacing='0'>"; //pdfbody += "<tbody >"; //pdfbody += "<tr>"; //pdfbody += "<th style='text-align:left'>"; //pdfbody += "Quotation Number:- " + objQuot.QuotationNo; //pdfbody += "</th>"; //pdfbody += "<th style='text-align:left'>"; //pdfbody += "Revision Number:- " + objQuot.new_Version_No; //pdfbody += "</th>"; //pdfbody += "</tr>"; //pdfbody += "<tr>"; //pdfbody += "<th style='text-align:left'>"; //pdfbody += " "; //pdfbody += "</th>"; //pdfbody += "<th style='text-align:left'>"; //pdfbody += "Date:- " + objQuot.CreatedOn.Date.ToString("dd-MMM-yyyy"); //pdfbody += "</th>"; //pdfbody += "</tr>"; //pdfbody += "</tbody>"; //pdfbody += "</table>"; //doc.Add(Chunk.NEWLINE); //hw.Parse(new StringReader(pdfbody)); pdfbody += "<br/> <table border='0' cellpadding='3' cellspacing='0' style='font-size: medium'>"; pdfbody += "<tbody >"; pdfbody += "<tr>"; //pdfbody += "<th width='5%' style='text-align:left; width:5%'>"; //pdfbody += "<b>I</b>"; //pdfbody += "</th>"; pdfbody += "<th>"; pdfbody += "Part Description: " + objQuot.PartDescription; pdfbody += " | Material: " + objQuot.Material + " | Customer Part No:" + objQuot.PartNo; pdfbody += "<br/> Heat Treatment: " + objQuot.HeatTreatmentText + " | Hardness: Min: " + modelFeasibility.hardnessmin; pdfbody += " Max: " + modelFeasibility.hardnessmax + " " + modelFeasibility.hardnessunits; pdfbody += "</th>"; pdfbody += "</tr>"; pdfbody += "</tbody>"; pdfbody += "</table>"; //pdfbody = "<table border='1' cellpadding='3' cellspacing='0'>"; //pdfbody += "<tbody >"; //pdfbody += "<tr>"; //pdfbody += "<th width='5%' style='text-align:left; width:5%'>"; //pdfbody += "<b>I</b>"; //pdfbody += "</th>"; //pdfbody += "<th style='text-align:left'>"; //pdfbody += "Part Description:- " + objQuot.PartDescription + "<br />"; //pdfbody += "Material:- " + objQuot.Material + "<br />"; //pdfbody += "Customer:- " + objQuot.CustomerName + "<br />"; //pdfbody += "</th>"; //pdfbody += "<th style='text-align:left'>"; //pdfbody += "Part No:- " + objQuot.PartNo + "<br />"; //pdfbody += "Heat Treatment:- " + objQuot.HeatTreatmentText + "<br />"; //pdfbody += "Min:- " + modelFeasibility.hardnessmin + " Max:- " + modelFeasibility.hardnessmax+" "+modelFeasibility.hardnessunits+"" ; //pdfbody += "</th>"; //pdfbody += "</tr>"; //pdfbody += "</tbody>"; //pdfbody += "</table>"; pdfbody += "<table border='1' cellpadding='2' cellspacing='0' style='font-size: medium'>"; pdfbody += "<tbody>"; pdfbody += "<tr>"; pdfbody += "<th width='5%' style='text-align:left; width:5%'>"; pdfbody += "<b> I</b>"; pdfbody += "</th>"; pdfbody += "<th style='text-align:left'>"; pdfbody += "Component Weight Details <br />"; //pdfbody += "<br />"; pdfbody += "Gross Weight (kg): " + objQuot.GrossWeight; pdfbody += " Cut Weight (kg): " + objQuot.CutWeight; pdfbody += " Forged Net Weight(kg): " + objQuot.NetWeight; pdfbody += "</th>"; pdfbody += "</tr>"; pdfbody += "</tbody>"; pdfbody += "</table>"; pdfbody += "<table border='1' cellpadding='5' cellspacing='0' style='font-size: medium'>"; pdfbody += "<tbody >"; pdfbody += "<tr>"; pdfbody += "<th width='5%' style='text-align:left; width:5%'>"; pdfbody += "<b>II</b>"; pdfbody += "</th>"; pdfbody += "<th style='text-align:left'>"; pdfbody += "Raw Material Cost Details"; // table inside th pdfbody += "<table border='1' cellpadding='2' cellspacing='0'>"; pdfbody += "<tbody>"; pdfbody += "<tr>"; pdfbody += "<th style='text-align:left' bgcolor='#f1f1f1' width='50%'>"; pdfbody += "Particulars"; pdfbody += "</th>"; pdfbody += "<th style='text-align:left' bgcolor='#f1f1f1'>"; pdfbody += "Basic Rate (Rs/kg)"; pdfbody += "</th>"; pdfbody += "<th style='text-align:left' bgcolor='#f1f1f1'>"; pdfbody += "Net Cost (Rs)"; pdfbody += "</th>"; pdfbody += "</tr>"; pdfbody += "<tr>"; pdfbody += "<th style='text-align:left'>"; pdfbody += "Steel Cost"; pdfbody += "</th>"; pdfbody += "<th style='text-align:right'>"; pdfbody += objQuot.SteelCost; pdfbody += "</th>"; pdfbody += "<th style='text-align:right'>"; pdfbody += Convert.ToDecimal(objQuot.SteelCost * objQuot.GrossWeight).ToString("0.00"); pdfbody += "</th>"; pdfbody += "</tr>"; pdfbody += "<tr>"; pdfbody += "<th style='text-align:left'>"; pdfbody += "Transportation"; pdfbody += "</th>"; pdfbody += "<th style='text-align:right'>"; pdfbody += objQuot.Transportation; pdfbody += "</th>"; pdfbody += "<th style='text-align:right'>"; pdfbody += Convert.ToDecimal(objQuot.Transportation * objQuot.GrossWeight).ToString("0.00"); pdfbody += "</th>"; pdfbody += "</tr>"; pdfbody += "<tr>"; pdfbody += "<th style='text-align:left'>"; pdfbody += "Total"; pdfbody += "</th>"; pdfbody += "<th style='text-align:right'>"; pdfbody += Convert.ToDecimal(objQuot.SteelCost + objQuot.Transportation).ToString("0.00"); pdfbody += "</th>"; pdfbody += "<th style='text-align:right'>"; pdfbody += objQuot.TotalRowMaterialCost; pdfbody += "</th>"; pdfbody += "</tr>"; pdfbody += "</tbody>"; pdfbody += "</table>"; pdfbody += "</th>"; pdfbody += "</tr>"; pdfbody += "</tbody>"; pdfbody += "</table>"; // ************** //doc.Add(Chunk.NEWLINE); //hw.Parse(new StringReader(pdfbody)); pdfbody += "<table border='1' cellpadding='5' cellspacing='0'style='font-size: medium'>"; pdfbody += "<tbody >"; pdfbody += "<tr>"; pdfbody += "<th width='5%' style='text-align:left; width:5%'>"; pdfbody += "<b>III</b>"; pdfbody += "</th>"; pdfbody += "<th style='text-align:left'>"; pdfbody += "Conversion Rate Details <br />"; // table inside th pdfbody += "<table border='1' cellpadding='2' cellspacing='0'>"; pdfbody += "<tbody >"; pdfbody += "<tr>"; pdfbody += "<th style='text-align:left' bgcolor='#f1f1f1' width='50%'>"; pdfbody += "Particulars"; pdfbody += "</th>"; pdfbody += "<th style='text-align:left' bgcolor='#f1f1f1'>"; pdfbody += "Basic Rate (Rs/kg)"; pdfbody += "</th>"; pdfbody += "<th style='text-align:left' bgcolor='#f1f1f1'>"; pdfbody += "Net Cost (Rs)"; pdfbody += "</th>"; pdfbody += "</tr>"; foreach (var item in modelFeasibility.ssmtbl_Feasibility_OperationsInvolvedModel) { if (item.Operations_Involved == 1 && item.Operations_Involved_Select) { pdfbody += "<tr>"; pdfbody += "<th style='text-align:left'>"; pdfbody += "Cutting (Sq In)"; pdfbody += "</th>"; pdfbody += "<th style='text-align:right'>"; pdfbody += objQuot.CuttingSquare1; pdfbody += "</th>"; pdfbody += "<th style='text-align:right'>"; pdfbody += objQuot.CuttingSquare2; pdfbody += "</th>"; pdfbody += "</tr>"; } if (item.Operations_Involved == 2 && item.Operations_Involved_Select) { pdfbody += "<tr>"; pdfbody += "<th style='text-align:left'>"; pdfbody += "Forging"; pdfbody += "</th>"; pdfbody += "<th style='text-align:right'>"; pdfbody += objQuot.Forging1; pdfbody += "</th>"; pdfbody += "<th style='text-align:right'>"; pdfbody += objQuot.Forging1; pdfbody += "</th>"; pdfbody += "</tr>"; } if (item.Operations_Involved == 3 && item.Operations_Involved_Select) { pdfbody += "<tr>"; pdfbody += "<th style='text-align:left'>"; pdfbody += "Heat Treatment Cost (Net Wt)"; pdfbody += "</th>"; pdfbody += "<th style='text-align:right'>"; pdfbody += objQuot.HeatTreatment1; pdfbody += "</th>"; pdfbody += "<th style='text-align:right'>"; pdfbody += objQuot.HeatTreatment2; pdfbody += "</th>"; pdfbody += "</tr>"; } if (item.Operations_Involved == 4 && item.Operations_Involved_Select) { pdfbody += "<tr>"; pdfbody += "<th style='text-align:left'>"; pdfbody += "Shot Blasting (Net Wt)"; pdfbody += "</th>"; pdfbody += "<th style='text-align:right'>"; pdfbody += objQuot.ShotBlasting1; pdfbody += "</th>"; pdfbody += "<th style='text-align:right'>"; pdfbody += objQuot.ShotBlasting2; pdfbody += "</th>"; pdfbody += "</tr>"; } if (item.Operations_Involved == 5 && item.Operations_Involved_Select) { pdfbody += "<tr>"; pdfbody += "<th style='text-align:left'>"; pdfbody += "MPI"; pdfbody += "</th>"; pdfbody += "<th style='text-align:right'>"; pdfbody += objQuot.MPI1; pdfbody += "</th>"; pdfbody += "<th style='text-align:right'>"; pdfbody += objQuot.MPI2; pdfbody += "</th>"; pdfbody += "</tr>"; } if (item.Operations_Involved == 13 && item.Operations_Involved_Select) { pdfbody += "<tr>"; pdfbody += "<th style='text-align:left'>"; pdfbody += "Grinding (Per Piece)"; pdfbody += "</th>"; pdfbody += "<th style='text-align:right'>"; pdfbody += objQuot.Grinding1; pdfbody += "</th>"; pdfbody += "<th style='text-align:right'>"; pdfbody += objQuot.Grinding2; pdfbody += "</th>"; pdfbody += "</tr>"; } if (item.Operations_Involved == 14 && item.Operations_Involved_Select) { pdfbody += "<tr>"; pdfbody += "<th style='text-align:left'>"; pdfbody += "Cold Coining (Per Piece)"; pdfbody += "</th>"; pdfbody += "<th style='text-align:right'>"; pdfbody += objQuot.ColdCoining1; pdfbody += "</th>"; pdfbody += "<th style='text-align:right'>"; pdfbody += objQuot.ColdCoining2; pdfbody += "</th>"; pdfbody += "</tr>"; } if (item.Operations_Involved == 15 && item.Operations_Involved_Select) { pdfbody += "<tr>"; pdfbody += "<th style='text-align:left'>"; pdfbody += "Machining (Per Piece)"; pdfbody += "</th>"; pdfbody += "<th style='text-align:right'>"; pdfbody += objQuot.Machining1; pdfbody += "</th>"; pdfbody += "<th style='text-align:right'>"; pdfbody += objQuot.Machining2; pdfbody += "</th>"; pdfbody += "</tr>"; } } pdfbody += "<tr>"; pdfbody += "<th style='text-align:left'>"; pdfbody += "Die Maintaince Cost (Per Piece)"; pdfbody += "</th>"; pdfbody += "<th style='text-align:right'>"; pdfbody += objQuot.DieMaintenance1; pdfbody += "</th>"; pdfbody += "<th style='text-align:right'>"; pdfbody += objQuot.DieMaintenance2; pdfbody += "</th>"; pdfbody += "</tr>"; pdfbody += "<tr>"; pdfbody += "<th style='text-align:left'>"; pdfbody += "Total Coversion Cost"; pdfbody += "</th>"; pdfbody += "<th style='text-align:right'>"; // pdfbody += Convert.ToDecimal(objQuot.DieMaintenance1+ objQuot.Machining1+ objQuot.ColdCoining1+ objQuot.Grinding1+ objQuot.MPI1+ objQuot.ShotBlasting1+ objQuot.HeatTreatment1 + objQuot.Forging1+ objQuot.CuttingSquare1).ToString("0.00"); pdfbody += ""; pdfbody += "</th>"; pdfbody += "<th style='text-align:right'>"; pdfbody += objQuot.TotalConverstionCost; pdfbody += "</th>"; pdfbody += "</tr>"; pdfbody += "</tbody>"; pdfbody += "</table>"; pdfbody += "</th>"; pdfbody += "</tr>"; pdfbody += "</tbody>"; pdfbody += "</table>"; // ************** //doc.Add(Chunk.NEWLINE); //hw.Parse(new StringReader(pdfbody)); pdfbody += "<table border='1' cellpadding='5' cellspacing='0' style='font-size: medium'>"; pdfbody += "<tbody >"; pdfbody += "<tr>"; pdfbody += "<th width='5%' style='text-align:left; width:5%'>"; pdfbody += "<b>IV</b>"; pdfbody += "</th>"; pdfbody += "<th style='text-align:left'>"; pdfbody += "Total Component Cost (II+III) "; pdfbody += "</th>"; pdfbody += "<th style='text-align:right'>"; pdfbody += +objQuot.TotalComponentCost; pdfbody += "</th>"; pdfbody += "</tr>"; pdfbody += "</tbody>"; pdfbody += "</table>"; //doc.Add(Chunk.NEWLINE); //hw.Parse(new StringReader(pdfbody)); pdfbody += "<table border='1' cellpadding='5' cellspacing='0' style='font-size: medium'>"; pdfbody += "<tbody >"; pdfbody += "<tr>"; pdfbody += "<th width='5%' style='text-align:left; width:5%'>"; pdfbody += "<b>V</b>"; pdfbody += "</th>"; pdfbody += "<th style='text-align:left'>"; pdfbody += "Initial Die Cost "; pdfbody += "</th>"; pdfbody += "<th style='text-align:right'>"; pdfbody += +objQuot.InitialDieCost; pdfbody += "</th>"; pdfbody += "</tr>"; pdfbody += "</tbody>"; pdfbody += "</table>"; //if (objQuot.totallycost!="") //{ // pdfbody += "<table border='1' cellpadding='5' cellspacing='0' style='font-size: medium'>"; // pdfbody += "<tbody >"; // pdfbody += "<tr>"; // pdfbody += "<th width='5%' style='text-align:left; width:5%'>"; // pdfbody += "<b>VI</b>"; // pdfbody += "</th>"; // pdfbody += "<th style='text-align:left'>"; // pdfbody += "Total Other Cost "; // pdfbody += "</th>"; // pdfbody += "<th style='text-align:right'>"; // pdfbody += objQuot.totallycost; // pdfbody += "</th>"; // pdfbody += "</tr>"; // pdfbody += "</tbody>"; // pdfbody += "</table>"; //} // // //doc.Add(Chunk.NEWLINE); //hw.Parse(new StringReader(pdfbody)); pdfbody += "<table border='1' cellpadding='2' cellspacing='0' style='font-size: medium'>"; pdfbody += "<tbody >"; pdfbody += "<tr>"; pdfbody += "<th style='text-align:left'>"; pdfbody += "Terms And Conditions: "; pdfbody += "</th>"; pdfbody += "</tr>"; pdfbody += "<tr>"; var i = 1; foreach (var item in objQuot.ssmtbl_TermsNCondtionModel) { pdfbody += "<th style='text-align:left'>"; pdfbody += +i + ". " + item.TermsNConditionContent; pdfbody += "</th>"; i++; } pdfbody += "</tr>"; pdfbody += "</tbody>"; pdfbody += "</table>"; //doc.Add(Chunk.NEWLINE); //hw.Parse(new StringReader(pdfbody)); //pdfbody += "<table border='1' cellpadding='2' cellspacing='0'>"; //pdfbody += "<tbody >"; //pdfbody += "<tr>"; //pdfbody += "<th style='text-align:left'>"; //pdfbody += "Prepared By:- " + objQuot.Createdby; //pdfbody += "</th>"; //pdfbody += "<th style='text-align:left'>"; //pdfbody += "Approved By:- " + objQuot.ApprovedBy; //pdfbody += "</th>"; //pdfbody += "</tr>"; //pdfbody += "<tr>"; //pdfbody += "<th style='text-align:left'>"; //pdfbody += "Prepared Date:- " + objQuot.CreatedOn.Date.ToString("dd-MMM-yyyy"); //pdfbody += "</th>"; //pdfbody += "<th style='text-align:left'>"; //pdfbody += "Approved Date:- " + objQuot.ApprovalDate.Date.ToString("dd-MMM-yyyy"); //pdfbody += "</th>"; //pdfbody += "</tr>"; //pdfbody += "</tbody>"; //pdfbody += "</table>"; pdfbody += "</div>"; doc.Add(Chunk.NEWLINE); hw.Parse(new StringReader(pdfbody)); doc.Close(); contentType = "application/pdf"; return(File(HttpContext.Server.MapPath("~/PDFFiles/Quotation/") + filenm, contentType, filenm)); } catch (Exception ex) { ErrorHandlerClass.LogError(ex); } // return View(); return(File(HttpContext.Server.MapPath("~/PDFFiles/Quotation/") + filenm, contentType, filenm)); }
public void ProcessRequest(HttpContext context) { int ShowID = Convert.ToInt32(context.Request["showid"]); Shows show = new Shows(ShowID); String sortby = Convert.ToString(context.Request["sortby"]); ShowDetails sd = new ShowDetails(); DataTable table = sd.GetShowDetails(ShowID).Tables[0]; Document doc = new Document(PageSize.A4, -10, -50, 2, 2); Stream output = new MemoryStream(); var writer = PdfWriter.GetInstance(doc, output); StyleSheet sheet = new StyleSheet(); doc.Open(); Font smallFont = new Font(Font.COURIER, 8, Font.NORMAL, Color.BLACK); Font normalFont = new Font(Font.COURIER, 8, Font.NORMAL, Color.BLACK); Font normalFontBold = new Font(Font.COURIER, 8, Font.BOLD, Color.BLACK); Font headerFont = new Font(Font.HELVETICA, 12, Font.BOLD, Color.BLACK); Font ClassTitleFont = new Font(Font.HELVETICA, 16, Font.NORMAL, Color.BLACK); Font bigFont = new Font(Font.HELVETICA, 25, Font.NORMAL, Color.BLACK); Font mediumFont = new Font(Font.HELVETICA, 20, Font.NORMAL, Color.BLACK); PdfPTable ptable = new PdfPTable(1); PdfPCell cell; cell = new PdfPCell(); cell.FixedHeight = 150; cell.BorderWidth = 0; ptable.AddCell(cell); cell = new PdfPCell(new Phrase(new Chunk("Master List", bigFont))); cell.HorizontalAlignment = Element.ALIGN_CENTER; cell.BorderWidth = 0; cell.FixedHeight = 100; ptable.AddCell(cell); cell = new PdfPCell(new Phrase(new Chunk(show.ShowName, bigFont))); cell.HorizontalAlignment = Element.ALIGN_CENTER; cell.BorderWidth = 0; ptable.AddCell(cell); cell = new PdfPCell(new Phrase(new Chunk(show.ShowDate.ToString("dd MMM yyyy"), bigFont))); cell.BorderWidth = 0; cell.HorizontalAlignment = Element.ALIGN_CENTER; ptable.AddCell(cell); doc.Add(ptable); doc.NewPage(); float[] colWidths = { 100, 40, 175, 200}; int count = 0; String lastName = ""; DataSet masterList = DogClasses.getMasterList(ShowID, sortby); String tmp = ""; ptable = new PdfPTable(colWidths); cell = new PdfPCell(new Phrase(new Chunk("Handler Name", headerFont))); cell.BorderWidth = 0; ptable.AddCell(cell); cell = new PdfPCell(new Phrase("Ring No", headerFont)); cell.BorderWidth = 0; ptable.AddCell(cell); cell = new PdfPCell(new Phrase("Dog Name", headerFont)); cell.BorderWidth = 0; ptable.AddCell(cell); cell = new PdfPCell(new Phrase("Class Details", headerFont)); cell.BorderWidth = 0; ptable.AddCell(cell); doc.Add(ptable); bool topBorder = false; Color altLine = new Color(224, 224, 224); foreach (DataRow row in masterList.Tables[0].Rows) { Color altColor = Color.WHITE; if (count % 2 == 0 ) { altColor = altLine; } MasterList masterListItem = new MasterList(row); ptable = new PdfPTable(colWidths); if (lastName == masterListItem.Name) { cell = new PdfPCell(new Phrase(new Chunk("", normalFont))); topBorder = false; } else { topBorder = true; tmp = masterListItem.Name; //if (masterListItem.AltHandler > 0) //{ // User u = new User(masterListItem.AltHandler); // tmp = u.Name; //} cell = new PdfPCell(new Phrase(new Chunk(tmp, normalFont))); cell.BorderColorTop = Color.BLACK; cell.BorderWidthTop = 1; } cell.BorderWidth = 0; cell.BackgroundColor = altColor; ptable.AddCell(cell); cell = new PdfPCell(new Phrase(new Chunk(masterListItem.RingNumber.ToString(), normalFont))); cell.BorderWidth = 0; cell.HorizontalAlignment = Element.ALIGN_CENTER; cell.BackgroundColor = altColor; if (topBorder) { cell.BorderColorTop = Color.BLACK; cell.BorderWidthTop = 1; } ptable.AddCell(cell); Paragraph p = new Paragraph(); Phrase ph = new Phrase(); ph.Add(new Chunk(masterListItem.KCName, normalFont)); ph.Add(Chunk.NEWLINE); ph.Add(new Chunk(masterListItem.KCNumber, normalFont)); cell = new PdfPCell(ph); cell.BorderWidth = 0; cell.BackgroundColor = altColor; if (topBorder) { cell.BorderColorTop = Color.BLACK; cell.BorderWidthTop = 1; } ptable.AddCell(cell); PdfPTable classDetailsTbl = new PdfPTable(1); List<DogClasses> dcList = DogClasses.Retrieve(masterListItem.DogID, ShowID); p = new Paragraph(); bool first = true; foreach (DogClasses dc in dcList) { ShowClasses sc = new ShowClasses(dc.Classid); if (!first) { p.Add(new Chunk(String.Format(", {0,3}:", sc.ClassNo), normalFont)); } else { p.Add(new Chunk(String.Format("{0,3}:", sc.ClassNo), normalFont)); } p.Add(new Chunk(String.Format("{0,3}", dc.RO), normalFontBold)); first = false; } cell = new PdfPCell(p); cell.BorderWidth = 0; classDetailsTbl.AddCell(cell); cell = new PdfPCell(classDetailsTbl); cell.BorderWidth = 0; cell.BackgroundColor = altColor; if (topBorder) { cell.BorderColorTop = Color.BLACK; cell.BorderWidthTop = 1; } ptable.AddCell(cell); doc.Add(ptable); lastName = masterListItem.Name; count++; //if (count > 100 ) break; } doc.Close(); context.Response.ClearContent(); context.Response.ContentType = "application/pdf"; context.Response.AddHeader("content-disposition", String.Format("inline;filename=PreviewSchedule.pdf")); context.Response.BinaryWrite((output as MemoryStream).ToArray()); }
public ActionResult printPDF() { string pdfBody = string.Empty; pdfBody += "<table>"; pdfBody += "<tr>"; pdfBody += "<td> C </ td >"; pdfBody += "<td> RoseWater</td>"; pdfBody += "<td></td>"; pdfBody += "</tr>"; pdfBody += "<tr>"; pdfBody += "<td>Date:01/06/201</td>"; pdfBody += "<td>Name:Nasser</td>"; pdfBody += "<td>Te:1234566</td>"; pdfBody += "</tr>"; foreach (var itm in db.Customers.OrderBy(x => x.CustName).ToList()) { pdfBody += "<tr>"; pdfBody += "<td>" + itm.CustName + "</td>"; pdfBody += "<td>" + itm.Tel + "</td>"; pdfBody += "<td>" + itm.CustId + "</td>"; pdfBody += "</tr>"; } pdfBody += "</table>"; Document document = new Document(); //string filenm = "UserList.pdf"; string filenm = "BillNo-" + DateTime.Now.Ticks + ".pdf"; var fpath = HttpContext.Server.MapPath("~/Documents/PDFDocuments/"); //PngWriter.GetInstance(document, new FileStream(fpath + filenm, FileMode.Create)); PdfWriter oPdfWriter = PdfWriter.GetInstance(document, new FileStream(fpath + filenm, FileMode.Create)); document.Open(); //If you want to add phrase: Phrase titl = new Phrase("\nCustomer Copy\n"); titl.Font.SetStyle(Font.BOLD); document.Add(titl); iTextSharp.text.html.simpleparser.StyleSheet styles = new iTextSharp.text.html.simpleparser.StyleSheet(); iTextSharp.text.html.simpleparser.HTMLWorker hw = new iTextSharp.text.html.simpleparser.HTMLWorker(document); hw.Parse(new StringReader(pdfBody)); var logo = iTextSharp.text.Image.GetInstance(Server.MapPath("~/Content/images/logo.png")); logo.SetAbsolutePosition(300, 750); document.Add(logo); string jsText = "var res = app.setTimeOut(‘var pp = this.getPrintParams();pp.interactive = pp.constants.interactionLevel.full;this.print(pp);’, 200);"; PdfAction js = PdfAction.JavaScript(jsText, oPdfWriter); oPdfWriter.AddJavaScript(js); document.Close(); Response.ClearContent(); Response.ClearHeaders(); Response.AddHeader("Content-Disposition", "inline;filename=" + filenm + ""); Response.ContentType = "application/pdf"; Response.WriteFile(HttpContext.Server.MapPath("~/Documents/PDFDocuments/") + filenm); Response.Flush(); Response.Clear(); //printMyPDF("UserList.pdf"); ViewBag.myPDF = filenm; return(View()); }
public static void ExportData(System.Data.DataTable dt, string ExportFileName) { //if (sfd.FilterIndex == 1) //{ // bool ExcelImport = false; // if (W.Show("Will this file be Imported into MS EXCEL?", "EXCEL", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question) == DialogResult.Yes) // ExcelImport = true; // using (StreamWriter sw = new StreamWriter(sfd.FileName)) // { // StringBuilder sb = new StringBuilder(); // foreach (DataColumn dc in dt.Columns) // { // sb.Append(dc.ColumnName + ","); // } // sw.WriteLine(sb.ToString().Substring(0, sb.ToString().Length - 1)); // foreach (DataRow dr in dt.Rows) // { // sb = new StringBuilder(); // string rec = ""; // foreach (DataColumn dc in dt.Columns) // { // if (ExcelImport) // rec = @"=" + "\"" + dr[dc.ColumnName].ToString() + "\""; // else // rec = dr[dc.ColumnName].ToString(); // sb.Append(rec + ","); // } // sw.WriteLine(sb.ToString().Substring(0, sb.ToString().Length - 1)); // } // } //} //else if (sfd.FilterIndex == 2) //{ //Document is inbuilt class, available in iTextSharp Document document = new Document(PageSize.A4, 80, 50, 30, 65); StringBuilder strData = new StringBuilder(string.Empty); try { StringWriter sw = new StringWriter(); sw.WriteLine(Environment.NewLine); sw.WriteLine(Environment.NewLine); sw.WriteLine(Environment.NewLine); sw.WriteLine(Environment.NewLine); StreamWriter strWriter = new StreamWriter(ExportFileName, false, Encoding.UTF8); //strWriter.Write("<html><head><link href=Style.css rel=stylesheet type=text/css /></head><body>" + htw.InnerWriter.ToString() + "</body></html>"); #region Write in StreamWriter string sError = string.Empty; int iNoOfColsinaPage = 7; int iRunningColCount = 0; strWriter.Write("<HTML><BODY><TABLE>"); foreach (DataColumn dc in dt.Columns) { if (iRunningColCount % iNoOfColsinaPage == 0) { strWriter.Write("<TR>"); } strWriter.Write("<TD> " + dc.ColumnName + " </TD>"); iRunningColCount++; if (iRunningColCount % iNoOfColsinaPage == 0) { strWriter.Write("</TR>"); } } foreach (DataRow dr in dt.Rows) { iRunningColCount = 0; foreach (DataColumn dc in dt.Columns) { if (iRunningColCount % iNoOfColsinaPage == 0) { strWriter.Write("<TR>"); } strWriter.Write("<TD>" + dr[dc.ColumnName].ToString() + " </TD>"); iRunningColCount++; if (iRunningColCount % iNoOfColsinaPage == 0) { strWriter.Write("</TR>"); } } } strWriter.Write("</TABLE></BODY></HTML>"); //sb = strWriter.to .Replace("</TD><TR>", "</TD></TR><TR>"); #endregion strWriter.Close(); strWriter.Dispose(); iTextSharp.text.html.simpleparser. StyleSheet styles = new iTextSharp.text.html.simpleparser.StyleSheet(); styles.LoadTagStyle("ol", "leading", "16,0"); List <IElement> objects; styles.LoadTagStyle("li", "face", "garamond"); styles.LoadTagStyle("span", "size", "8px"); styles.LoadTagStyle("body", "font-family", "times new roman"); styles.LoadTagStyle("body", "font-size", "10px"); StreamReader sr = new StreamReader(ExportFileName, Encoding.Default); objects = HTMLWorker.ParseToList(sr, styles); sr.Close(); PdfWriter.GetInstance(document, new FileStream(ExportFileName, FileMode.Create)); document.Add(new Header("stylesheet", "Style.css")); document.Open(); document.NewPage(); for (int k = 0; k < objects.Count; k++) { document.Add((IElement)objects[k]); } } catch (Exception ex) { //throw ex; } finally { document.Close(); } }
public void ProcessRequest(HttpContext context) { int ShowID = Convert.ToInt32(context.Request["showid"]); int RingID = Convert.ToInt32(context.Request["ringid"]); String cmd = context.Request["doc"].ToString(); Shows show = new Shows(ShowID); ShowDetails sd = new ShowDetails(); DataTable table = sd.GetShowDetails(ShowID).Tables[0]; String pdfPath = context.Server.MapPath(cmd + ".pdf"); Boolean publish = false; if (!String.IsNullOrEmpty(context.Request["publish"]) && context.Request["publish"].ToString() == "1") publish = true; Document doc = new Document(PageSize.A4, -50, -50, 2, 2); Stream output; if (publish) { String path = context.Server.MapPath(@"..\schedules\"); path += DateTime.Today.ToString("yyyy"); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } path += String.Format("\\{0:yyyyMM}_{1}.pdf", show.ShowDate, show.ShowName); output = new FileStream(path, FileMode.Create); } else { output = new MemoryStream(); } var writer = PdfWriter.GetInstance(doc, output); StyleSheet sheet = new StyleSheet(); doc.Open(); Font smallFont = new Font(Font.COURIER, 8, Font.NORMAL, Color.BLACK); Font normalFont = new Font(Font.COURIER, 10, Font.NORMAL, Color.BLACK); Font headerFont = new Font(Font.HELVETICA, 12, Font.BOLD, Color.BLACK); Font ClassTitleFont = new Font(Font.HELVETICA, 16, Font.NORMAL, Color.BLACK); Font bigFont = new Font(Font.HELVETICA, 25, Font.NORMAL, Color.BLACK); Font mediumFont = new Font(Font.HELVETICA, 20, Font.NORMAL, Color.BLACK); ShowClasses sc = new ShowClasses(); Rings currentRing = new Rings(RingID); List<ShowClasses> showClasses = ShowClasses.GetAllClassesForShowRing(ShowID, RingID); PdfPTable callingListTbl = null; foreach (ShowClasses showClass in showClasses) { List<int> resultCnts = ShowClasses.getDogsInClass(showClass.ID, (showClass.Catagory == 0)); int gradeidx = 0; foreach (int dogCounts in resultCnts) { PdfPTable ptable = new PdfPTable(3); PdfPCell cell; String grades; String subTitle; if (showClass.Catagory == 0) { if (gradeidx < showClass.Grades.Length) { grades = "Grade " + showClass.Grades[gradeidx]; } else { grades = showClass.Grades; } subTitle = String.Format("{0} {1} {2} {3} - Judge: {4}", showClass.longHeight, showClass.longCatagory, showClass.LongClassName, grades, Judge.getJudgeForClass(showClass.ID)); } else { if (showClass.Grades.Length == 1) { grades = showClass.Grades; } else { grades = showClass.Grades[0] + " - " + showClass.Grades[showClass.Grades.Length - 1]; } subTitle = String.Format("{0} {1} {3} {2} - Judge: {4}", showClass.longHeight, showClass.longCatagory, showClass.LongClassName, grades, Judge.getJudgeForClass(showClass.ID)); } String tmp = String.Format("Result Sheet - Ring No:{0}", currentRing.RingNo); cell = new PdfPCell(new Phrase(new Chunk(tmp, bigFont))); cell.Colspan = 2; cell.BorderWidth = 0; ptable.AddCell(cell); tmp = String.Format("Class No:{0}", showClass.ClassNo); cell = new PdfPCell(new Phrase(new Chunk(tmp, bigFont))); cell.HorizontalAlignment = Element.ALIGN_CENTER; cell.BorderWidth = 2; cell.Padding = 5; ptable.AddCell(cell); cell = new PdfPCell(new Phrase(new Chunk(subTitle, mediumFont))); cell.Colspan = 3; cell.BorderWidth = 0; ptable.AddCell(cell); cell = new PdfPCell(new Phrase(new Chunk("", ClassTitleFont))); cell.Colspan = 3; cell.BorderWidth = 0; ptable.AddCell(cell); ptable.AddCell(cell); ptable.AddCell(cell); doc.Add(ptable); float[] colWidths = { 75, 75, 200, 200, 50, 75 }; callingListTbl = new PdfPTable(colWidths); cell = new PdfPCell(new Phrase(new Chunk("Place", headerFont))); cell.BorderWidth = 1; cell.BorderWidthBottom = 0; cell.FixedHeight = 35f; cell.HorizontalAlignment = Element.ALIGN_CENTER; callingListTbl.AddCell(cell); cell = new PdfPCell(new Phrase(new Chunk("Ring Number", headerFont))); cell.BorderWidth = 1; cell.BorderWidthBottom = 0; cell.HorizontalAlignment = Element.ALIGN_CENTER; callingListTbl.AddCell(cell); cell = new PdfPCell(new Phrase(new Chunk("Handler", headerFont))); cell.BorderWidth = 1; cell.BorderWidthBottom = 0; cell.HorizontalAlignment = Element.ALIGN_CENTER; callingListTbl.AddCell(cell); cell = new PdfPCell(new Phrase(new Chunk("Dog Name", headerFont))); cell.BorderWidth = 1; cell.BorderWidthBottom = 0; cell.HorizontalAlignment = Element.ALIGN_CENTER; callingListTbl.AddCell(cell); cell = new PdfPCell(new Phrase(new Chunk("Clear/ Faults", headerFont))); cell.BorderWidth = 1; cell.BorderWidthBottom = 0; cell.HorizontalAlignment = Element.ALIGN_CENTER; callingListTbl.AddCell(cell); cell = new PdfPCell(new Phrase(new Chunk("Time", headerFont))); cell.BorderWidth = 1; cell.BorderWidthBottom = 0; cell.HorizontalAlignment = Element.ALIGN_CENTER; callingListTbl.AddCell(cell); int maxRosettes = calcRosettes(dogCounts); int maxTrophies = calcTrophies(dogCounts); float rowHeight = 25f; if (showClass.EntryType == 4) { rowHeight = 65f; } else if (showClass.EntryType == 5) { rowHeight = 120f; } for (int resultRow = 0; resultRow < maxRosettes; resultRow++) { int bwb = 0; if (resultRow == maxRosettes - 1) { bwb = 1; } Color background = Color.WHITE; if (maxTrophies > 0) { background = Color.LIGHT_GRAY; } maxTrophies--; cell = new PdfPCell(new Phrase(new Chunk(calcPlace(resultRow + 1), normalFont))); cell.BorderWidth = 1; cell.BorderWidthBottom = bwb; cell.FixedHeight = rowHeight; cell.HorizontalAlignment = Element.ALIGN_CENTER; cell.BackgroundColor = background; callingListTbl.AddCell(cell); cell = new PdfPCell(new Phrase(new Chunk("", normalFont))); cell.BorderWidth = 1; cell.BackgroundColor = background; cell.BorderWidthBottom = bwb; callingListTbl.AddCell(cell); callingListTbl.AddCell(cell); callingListTbl.AddCell(cell); callingListTbl.AddCell(cell); callingListTbl.AddCell(cell); } doc.Add(callingListTbl); doc.NewPage(); gradeidx++; } } doc.Close(); if (publish) { } else { context.Response.ClearContent(); context.Response.ContentType = "application/pdf"; context.Response.AddHeader("content-disposition", String.Format("inline;filename=PreviewSchedule.pdf")); context.Response.BinaryWrite((output as MemoryStream).ToArray()); } }
private void download(HttpContext context, List<int> ids) { Document doc = new Document(PageSize.A4, -50, -50, 2, 2); Stream output; output = new MemoryStream(); var writer = PdfWriter.GetInstance(doc, output); StyleSheet sheet = new StyleSheet(); doc.Open(); Font font = new Font(Font.COURIER, 10, Font.NORMAL, Color.BLACK); Font resFont = new Font(Font.COURIER, 9, Font.ITALIC, Color.BLACK); Font headerFont = new Font(Font.COURIER, 10, Font.BOLD, Color.BLACK); Font headerFont2 = new Font(Font.HELVETICA, 12, Font.NORMAL, Color.BLACK); Font headerFont3 = new Font(Font.HELVETICA, 16, Font.NORMAL, Color.BLACK); Font ClassTitleFont = new Font(Font.HELVETICA, 24, Font.NORMAL, Color.BLACK); PdfPTable ptable = new PdfPTable(new float[] { 20, 200, 50}); PdfPCell cell; foreach (int id in ids) { ptable = new PdfPTable(3); var judge = new Judge(id); var showDetails = new ShowDetails(judge.ShowDetailsID); var user = new User(judge.UserID); cell = new PdfPCell(new Phrase(new Chunk("First Place Processing", ClassTitleFont))); cell.Border = 0; cell.Colspan = 3; ptable.AddCell(cell); cell = new PdfPCell(); cell.Border = 0; cell.Colspan = 3; cell.FixedHeight = 18f; ptable.AddCell(cell); cell = new PdfPCell(new Phrase(new Chunk( String.Format("{0}\n{1}\n{2}\n\n{3}", user.Name, user.Address, user.Postcode, user.EmailAddress), headerFont2))); cell.Border = 0; cell.Colspan = 3; ptable.AddCell(cell); cell = new PdfPCell( new Phrase( new Chunk( string.Format(@" Hi, This is to confirm the classes you will be judging at our show {0} on the {1:dddd, dd MMMM yyyy}.", show.ShowName, showDetails.ShowDate) , headerFont2))); cell.Border = 0; cell.Colspan = 3; ptable.AddCell(cell); cell = new PdfPCell(); cell.Border = 0; cell.Colspan = 3; cell.FixedHeight = 18f; ptable.AddCell(cell); var classesDS = judge.getClassesForJudge(); if (classesDS.Tables.Count > 0) { var total = 0; foreach (DataRow classRow in classesDS.Tables[0].Rows) { var dic = Utils.CalcDogsInCalc(classRow); cell = new PdfPCell(new Phrase(new Chunk(string.Format("{0,5})",classRow["ClsNo"]) , headerFont2))); cell.Border = 0; cell.Colspan = 1; cell.HorizontalAlignment = Element.ALIGN_RIGHT; ptable.AddCell(cell); var classes = String.Format("{3} {4} {7} {5} {6} - {1}\n", classRow["ClassID"], dic, classRow["ClsNo"], ShowClasses.expandHeight(classRow), ShowClasses.expandCatagory(classRow), classRow["LongName"], classRow["Name"], ShowClasses.shortenGrades(classRow) ); cell = new PdfPCell(new Phrase(new Chunk(classes, headerFont2))); cell.Border = 0; cell.Colspan = 2; ptable.AddCell(cell); total += dic; } cell = new PdfPCell(new Phrase("")); cell.Border = 0; cell.Colspan = 3; cell.FixedHeight = 18f; ptable.AddCell(cell); var totals = String.Format("Totals number of dogs {0}\n", total ); cell = new PdfPCell(new Phrase("")); cell.Border = 0; cell.Colspan = 1; ptable.AddCell(cell); cell = new PdfPCell(new Phrase(new Chunk(totals, headerFont3))); cell.Border = 0; cell.Colspan = 2; ptable.AddCell(cell); cell = new PdfPCell(new Phrase(new Chunk( @" Can I request that if you would like us to set up your course at the show, could you send me your course plan 7 days before the show at the latest? If you do not forward to me I will assume that you wish to set your course yourself or with friends, which is fine. If you wish to set your course up yourself then I will just need to know if you require any special or extra equipment at least 10 days before the show. Attached is a full list of equipment supplied in a standard set from First Contact. A continental breakfast & lunch will be available for you, your scribe and ring manager. If you can supply enough people to man the ring all day we will pay £100, also can you confirm any ring party / full ring party 10 days before the show. Many thanks Jackie Kenny Dog Vegas show secretary", headerFont2))); cell.Border = 0; cell.Colspan = 3; ptable.AddCell(cell); } doc.Add(ptable); doc.NewPage(); } doc.Close(); context.Response.ClearContent(); context.Response.ContentType = "application/pdf"; context.Response.AddHeader("content-disposition", "inline;filename=JudgesClassConfirmation.pdf"); context.Response.BinaryWrite((output as MemoryStream).ToArray()); }
/** * Parses an HTML source to a List of Element objects * @param reader the HTML source * @param style a StyleSheet object * @param tags a map containing supported tags and their processors * @param providers map containing classes with extra info * @return a List of Element objects * @throws IOException * @since 5.0.6 */ public static List<IElement> ParseToList(TextReader reader, StyleSheet style, IDictionary<String, IHTMLTagProcessor> tags, Dictionary<String, Object> providers) { HTMLWorker worker = new HTMLWorker(null, tags, style); worker.document = worker; worker.SetProviders(providers); worker.objectList = new List<IElement>(); worker.Parse(reader); return worker.objectList; }
/** * Creates a new instance of HTMLWorker * @param document A class that implements <CODE>DocListener</CODE> * @param tags A map containing the supported tags * @param style A StyleSheet * @since 5.0.6 */ public HTMLWorker(IDocListener document, IDictionary<String, IHTMLTagProcessor> tags, StyleSheet style) { this.document = document; SetSupportedTags(tags); SetStyleSheet(style); }
/** * Parses an HTML source to a List of Element objects * @param reader the HTML source * @param style a StyleSheet object * @return a List of Element objects * @throws IOException */ public static List<IElement> ParseToList(TextReader reader, StyleSheet style) { return ParseToList(reader, style, null); }
/** * Parses an HTML source to a List of Element objects * @param reader the HTML source * @param style a StyleSheet object * @param providers map containing classes with extra info * @return a List of Element objects * @throws IOException */ public static List<IElement> ParseToList(TextReader reader, StyleSheet style, Dictionary<String, Object> providers) { return ParseToList(reader, style, null, providers); }
public void GeneralLetter(String CreditControlID) { try { BillCreditControlList Vwobj = new BillCreditControlList(); Vwobj = BAL.BillCreditControlModel.ViewCreditControlReminderLetter(CreditControlID); if (Vwobj != null) { var document = new Document(PageSize.A4, 50, 50, 25, 25); String PDFName = Vwobj.BillNo + "-" + Vwobj.ID.ToString() + ".pdf"; var filePath = Path.Combine(Server.MapPath("~/PdfContent/CreditControl/Letter"), PDFName); // var output = new MemoryStream(); var output = new FileStream(filePath, FileMode.Create); var writer = PdfWriter.GetInstance(document, output); try { // Open the Document for writing document.Open(); // Read in the contents of the Receipt.htm file... StyleSheet styles = new StyleSheet(); //styles.LoadTagStyle(HtmlTags.H1, HtmlTags.FONTSIZE, "16"); //styles.LoadTagStyle(HtmlTags.P, HtmlTags.FONTSIZE, "10"); //styles.LoadTagStyle(HtmlTags.P, HtmlTags.m, "#ff0000"); //styles.LoadTagStyle(HtmlTags.CLASS, HtmlTags.COLOR, "#ff0000"); styles.LoadTagStyle(HtmlTags.TD, HtmlTags.ALIGN, "left"); styles.LoadTagStyle(HtmlTags.TD, HtmlTags.CELLPADDING, "10"); styles.LoadTagStyle(HtmlTags.P, HtmlTags.P, "margin-bottom:20px"); styles.LoadTagStyle(HtmlTags.P, HtmlTags.SPAN, "text-decoration:underline;"); styles.LoadStyle("Subject", "ALIGN", "center"); styles.LoadStyle("Subject", "FONTSIZE", "26px"); styles.LoadStyle("Subject", "color", "#ff0000"); styles.LoadStyle("c_outstanding", "font-size", "20px"); styles.LoadStyle("c_outstanding", "text-align", "center"); String contents = System.IO.File.ReadAllText(Server.MapPath("~/HTMLTemplate/GeneralLetter.htm")); // Replace the placeholders with the user-specified text contents = contents.Replace("[CustomerName]", Vwobj.ConsumerName.Trim()); contents = contents.Replace("[AddressLine1]", Vwobj.ConsumerAddress.Trim()); contents = contents.Replace("[AddressLine2]", Vwobj.ConsumerCounty.Trim()); contents = contents.Replace("[AddressLine3]", Vwobj.ConsumerCity.Trim()); contents = contents.Replace("[PostCode]", Vwobj.ConsumerZipCode.Trim()); contents = contents.Replace("[Amount]", Vwobj.LastBillAmount.ToString().Trim()); //' contents = contents.Replace("[propertyAddress]", Vwobj.PropertyNo.Trim()); contents = contents.Replace("[sitename]", Vwobj.SiteName.Trim()); contents = contents.Replace("[balanceofaccount]", Vwobj.Balance.ToString()); contents = contents.Replace("[invoicedateFrom]", Vwobj.InvoiceDateForm); contents = contents.Replace("[invoicedateTo]", Vwobj.InvoiceDateTo); contents = contents.Replace("[InvioceDate]", Vwobj.InvoiceDate); contents = contents.Replace("[ClientName]", Vwobj.ClientName); contents = contents.Replace("[ClientTelephoneNumber]", Vwobj.ClientTelephone); contents = contents.Replace("[ClientEmailAddress]", Vwobj.ClientEmail); var parsedHtmlElements = HTMLWorker.ParseToList(new StringReader(contents), styles); // Enumerate the elements, adding each one to the Document... foreach (var htmlElement in parsedHtmlElements) { document.Add(htmlElement as IElement); } writer.CloseStream = false; document.Close(); output.Dispose(); } catch (Exception ex) { output.Dispose(); document.Dispose(); } }//if }//try catch (Exception ex) { throw; } }
/** * Setter for the StyleSheet * @param style the StyleSheet */ virtual public void SetStyleSheet(StyleSheet style) { if (style == null) style = new StyleSheet(); this.style = style; }
public void GenerateReminder1(String CreditControlID ) { try { BillCreditControlList Vwobj = new BillCreditControlList(); Vwobj = BAL.BillCreditControlModel.ViewCreditControlReminderLetter(CreditControlID); if (Vwobj != null) { // Boolean flag = false; var document = new Document(PageSize.A4, 10, 10, 10, 10); String PDFName = Vwobj.BillNo.ToString() + Vwobj.ValidationType + "_"+Vwobj.ID + ".pdf"; var filePath = Path.Combine(Server.MapPath("~/PdfContent/CreditControl/Reminder"), PDFName); // var output = new MemoryStream(); var output = new FileStream(filePath, FileMode.Create); var writer = PdfWriter.GetInstance(document, output); writer.PageEvent = new HeaderFooter(CreditControlID); try { // Open the Document for writing document.Open(); // Read in the contents of the Receipt.htm file... StyleSheet styles = new StyleSheet(); String contents = System.IO.File.ReadAllText(Server.MapPath("~/HTMLTemplate/ReminderLetter1.htm")); // Replace the placeholders with the user-specified text String clientLogo = String.Empty; // contents = contents.Replace("[ClientImage]", clientLogo); contents = contents.Replace("[ConsumerName]", Vwobj.ConsumerName.Trim()); // contents = contents.Replace("[PropertyNO]", Bill.PropertyNo.Trim()); contents = contents.Replace("[ConsumerAddress]", Vwobj.ConsumerAddress.Trim()); if (Vwobj.ConsumerAddress2 != null) { contents = contents.Replace("[ConsumerAddress2]", "<br/>" + Vwobj.ConsumerAddress2.Trim()); } else { contents = contents.Replace("[ConsumerAddress2]", " "); } contents = contents.Replace("[ConsumerCity]", Vwobj.ConsumerCity.Trim()); contents = contents.Replace("[ConsumerCountry]", Vwobj.ConsumerCounty.Trim()); contents = contents.Replace("[ConsumerZipCode]", Vwobj.ConsumerZipCode.Trim()); contents = contents.Replace("[balanceofaccount]", Vwobj.Balance.ToString()); contents = contents.Replace("[Client]", Vwobj.ClientName.Trim()); contents = contents.Replace("[ClientAddress]", Vwobj.ClientAddress.Trim()); if (Vwobj.ClientAddress2 != null) { contents = contents.Replace("[ClientAddress2]", "<br/>" + Vwobj.ClientAddress2.Trim()); } else { contents = contents.Replace("[ClientAddress2]", ""); } contents = contents.Replace("[ClientCity]", Vwobj.ClientCity.Trim()); contents = contents.Replace("[ClientCounty]", Vwobj.ClientCounty.Trim()); contents = contents.Replace("[ClientZipCode]", Vwobj.ClientZipCode.Trim()); contents = contents.Replace("[CompRegistrationNo]", Vwobj.CompRegistrationNo !=null? Vwobj.CompRegistrationNo :""); contents = contents.Replace("[Amount]", Vwobj.LastBillAmount.ToString().Trim()); contents = contents.Replace("[ReminderDate]", Vwobj.ReminderDate != null? Vwobj.ReminderDate.ToString().Trim():""); if (Vwobj.PropertyAddress != null) { contents = contents.Replace("[PropertyAddress]", Vwobj.PropertyAddress.ToString().Trim()); } else { contents = contents.Replace("[PropertyAddress]", ""); } if (Vwobj.TemplateTelephone != null) { contents = contents.Replace("[TemplateTelephone]", Vwobj.TemplateTelephone); } else { contents = contents.Replace("[TemplateTelephone]", ""); } if (Vwobj.TemplateEmail != null) { contents = contents.Replace("[TemplateEmail]", Vwobj.TemplateEmail); } else { contents = contents.Replace("[TemplateEmail]", ""); } if (Vwobj.OpeningHour != null) { contents = contents.Replace("[OpeningHour]", Vwobj.OpeningHour); } else { contents = contents.Replace("[OpeningHour]", ""); } contents = contents.Replace("[ClosingHour]", Vwobj.ClosingHour != null? Vwobj.ClosingHour:"" ); contents = contents.Replace("[TemplateAddress]", Vwobj.TemplateAddress != null? Vwobj.TemplateAddress :""); contents = contents.Replace("[TemplateCity]", Vwobj.TemplateCity != null? Vwobj.TemplateCity:""); contents = contents.Replace("[TemplateCounty]", Vwobj.TemplateCounty != null ? Vwobj.TemplateCounty:"" ); contents = contents.Replace("[TemplateZipcode]", Vwobj.TemplateZipcode != null? Vwobj.TemplateZipcode:""); StringBuilder PaymentList = new StringBuilder(); if (Vwobj.DirectDebit == "1") { PaymentList.Append("<td align='center' valign='top' ><table><tr><td align='center' valign='top'> <img src='" + Server.MapPath("~/Images/img1.jpg") + "' height='50' align='center' alt=' '></td> </tr><tr><td align='center' >Please call us on " + Vwobj.TemplateTelephone + " to set up or amend your fixed or variable Direct Debit </td></tr></table></td>"); } if (Vwobj.PayPoint == "1") { PaymentList.Append("<td valign='top' style='font-size:10px; text-align:center; padding:10px;'>"); String PayPointImg = "<img src='" + Server.MapPath("~/Images/pay_point_pdf.png") + "' height='30' alt=' '>"; PaymentList.Append(PayPointImg); PaymentList.Append("<div style='clear:both'></div>"); PaymentList.Append(" Pay by Cash at any PayPoint outlet using your payment card</td>"); } if (Vwobj.PayZone == "1") { PaymentList.Append("<td valign='top' style='font-size:10px; text-align:center; padding:10px;'>"); String PayZoneImg = "<img src='" + Server.MapPath("~/Images/pay_zone_pdf.png") + "'height='30' alt=' '>"; PaymentList.Append(PayZoneImg); PaymentList.Append("<div style='clear:both'></div>"); PaymentList.Append(" Pay by Cash at any PayZone outlet using your payment card</td>"); } if (Vwobj.PostOffice == "1") { PaymentList.Append("<td valign='top' style='font-size:10px; text-align:center; padding:10px;'>"); String PostOfficeImg = "<img src='" + Server.MapPath("~/Images/payment_card_pdf.png") + "' height='30' alt=' '>"; PaymentList.Append(PostOfficeImg); PaymentList.Append("<div style='clear:both'></div>"); PaymentList.Append(" Pay by Cash at any Post Office branch using your payment card</td>"); } if (Vwobj.BankTransfer == "1") { PaymentList.Append("<td valign='top'>"); String BankTransferImg = "<img src='" + Server.MapPath("~/Images/bank_transfer_pdf.png") + "' height='30' alt=' '>"; PaymentList.Append(BankTransferImg); PaymentList.Append("<div style='clear:both'></div>"); PaymentList.Append("Our account details for Bank Transfers: "); if (Vwobj.SortCode != null) { PaymentList.Append("Sort Code " + Vwobj.SortCode); } if (Vwobj.ClientBankAccountNo != null) { PaymentList.Append(" Account Number "); PaymentList.Append(Vwobj.ClientBankAccountNo != null?Vwobj.ClientBankAccountNo :""); } PaymentList.Append("</td>"); } if (Vwobj.TelephonePay == "1") { PaymentList.Append("<td valign='top' align='center' style='font-size:10px; text-align:center; padding:10px;'>"); String telephonepaypngImg = "<img src='" + Server.MapPath("~/Images/telephone_pay_pdf.png") + "' height='30' alt=' '>"; PaymentList.Append(telephonepaypngImg); PaymentList.Append("<div style='clear:both'></div>"); PaymentList.Append("Pay by Credit or Debit Card by calling "); PaymentList.Append(Vwobj.TemplateTelephone != null? Vwobj.TemplateTelephone:""); PaymentList.Append("</td>"); } if (Vwobj.OnlinePay == "1") { PaymentList.Append("<td valign='top' align='center' style='font-size:10px; text-align:center; padding:10px;'>"); String OnlinePaypngImg = "<img src='" + Server.MapPath("~/Images/online_pay_pdf.png") + "' height='30' alt=' '>"; PaymentList.Append(OnlinePaypngImg); PaymentList.Append("<div style='clear:both'></div>"); PaymentList.Append("Pay by Credit or Debit Card. Visit your online account for App and SMS details"); PaymentList.Append("</td>"); } if (Vwobj.OnlineNTelephonePay == "1") { PaymentList.Append("<td valign='top' style='font-size:10px; text-align:center; padding:10px;'>"); String OnlineNTelephonePayImg = "<img src='" + Server.MapPath("~/Images/telephone_online_pay_pdf.png") + "' height='30' alt=' '>"; PaymentList.Append(OnlineNTelephonePayImg); PaymentList.Append("<div style='clear:both'></div>"); PaymentList.Append("Pay by Credit or Debit Card calling "); PaymentList.Append(Vwobj.TemplateTelephone != null?Vwobj.TemplateTelephone :"" ); PaymentList.Append(" visit www.mysycous.com</td>"); } contents = contents.Replace("[PaymentOption]", PaymentList.ToString()); // Step 4: Parse the HTML string into a collection of elements... var parsedHtmlElements = HTMLWorker.ParseToList(new StringReader(contents), styles); // Enumerate the elements, adding each one to the Document... foreach (var htmlElement in parsedHtmlElements) { document.Add(htmlElement as IElement); } writer.CloseStream = false; document.Close(); output.Dispose(); //Get the pointer to the beginning of the stream. // output.Position = 0; // MailCls email = new MailCls(); // email.EmailTo = "*****@*****.**"; //// email.EmailTo = "*****@*****.**"; // email.EmailSubject = "Reminder Letter 1"; // email.Body = " Plz check It"; // email.DispalyName = "sarajit"; // email.Attachment = 0; // email.stream = output; // email.Email_Sent(); // output.Dispose(); // document.Dispose(); } catch (Exception ex) { output.Dispose(); document.Dispose(); } }//if }//try catch (Exception ex) { throw; } }
public byte[] ProcessRequest(int ShowId, int[] UserIds) { Shows show = new Shows(ShowId); Document doc = new Document(PageSize.A4.Rotate(), 10, 10, 0, 10); Stream output = new MemoryStream(); var writer = PdfWriter.GetInstance(doc, output); writer.PageEvent = new RPPageEvents(); StyleSheet sheet = new StyleSheet(); doc.Open(); int pageCount = 0; foreach (int UserId in UserIds) { printedOnPage = true; List<int> defaultUsers = new List<int>(); UserShows userShow = new UserShows(UserId, ShowId); coverPage(userShow, doc); if (_fromAdmin) { PdfPCell cell = new PdfPCell(new Phrase(new Chunk(" ", pageFont))); cell.BorderWidth = 0; doc.Add(cell); doc.NewPage(); } printRingForUser(userShow, UserId, doc, ref defaultUsers, ref pageCount); List<int> tmp = null; foreach (int defid in defaultUsers) { if (pageCount % 2 != 0) { PdfPCell cell = new PdfPCell(new Phrase(new Chunk(" ", pageFont))); cell.BorderWidth = 0; doc.Add(cell); printedOnPage = false; doc.NewPage(); } pageCount = 0; printedOnPage = true; printRingForUser(userShow, defid, doc, ref tmp, ref pageCount); } drawTeamPairs(doc, userShow); if (pageCount % 2 != 0) { PdfPCell cell = new PdfPCell(new Phrase(new Chunk(" ", pageFont))); cell.BorderWidth = 0; doc.Add(cell); printedOnPage = false; doc.NewPage(); } pageCount = 0; } doc.Close(); return (output as MemoryStream).ToArray(); }
public void ProcessRequest(HttpContext context) { //PDFBuilder.HtmlToPdfBuilder builder = new HtmlToPdfBuilder(PageSize.A4); //builder.AddPage(); //builder.ImportStylesheet(context.Server.MapPath("pdfstylesheet.css")); int ShowID = Convert.ToInt32(context.Request["showid"]); Shows show = new Shows(ShowID); ShowDetails sd = new ShowDetails(); DataTable table = sd.GetShowDetails(ShowID).Tables[0]; String pdfPath = context.Server.MapPath("PreviewSchedule.pdf"); String contents = File.ReadAllText(context.Server.MapPath("schedule1FrontPage.html")); Boolean publish = false; if (!String.IsNullOrEmpty(context.Request["publish"]) && context.Request["publish"].ToString() == "1") publish = true; String logoImg = context.Server.MapPath("FirstContactAgility.png") ; contents = contents.Replace("[CLUBLOGO]", "src='" + logoImg + "'"); contents = contents.Replace("[SHOWDATES]", show.ShowDate.ToString("dddd, dd MMM yyyy")); contents = contents.Replace("[CLUBNAME]", show.ShowName); contents = contents.Replace("[SHOWVENUE]", show.Venue + ", " + show.VenuePostcode); contents = contents.Replace("[OPENTIME]", "8:00am"); contents = contents.Replace("[BRIEFING]", "8:15am"); contents = contents.Replace("[JUDGINGSTARTS]", "8:30am"); contents = contents.Replace("[SdHOWVENUE]", show.Venue + "," + show.VenuePostcode); contents = contents.Replace("[CLOSINGDATE]", show.ClosingDate.ToString("dd MMM yyyy")); contents = contents.Replace("[CHAIRMANNAME]", show.Chairman.Name); contents = contents.Replace("[CHAIRMANADDRESS]", show.Chairman.AddressDetails); contents = contents.Replace("[SECRETARYNAME]", show.Secretary.Name); contents = contents.Replace("[SECRETARYADDRESS]", show.Secretary.AddressDetails); contents = contents.Replace("[TREASURERNAME]", show.Treasurer.Name); contents = contents.Replace("[TREASURERADDRESS]", show.Treasurer.AddressDetails); contents = contents.Replace("[SHOWSECNAME]", show.ShowSec.Name); contents = contents.Replace("[SHOWSECADDRESS]", show.ShowSec.AddressDetails); contents = contents.Replace("[SHOWMANAGERNAME]", show.ShowManager.Name); contents = contents.Replace("[SHOWMANAGERADDRESS]", show.ShowManager.AddressDetails); contents = contents.Replace("[EQUIPMENTNAME]", show.Equipment.Name); contents = contents.Replace("[EQUIPMENTADDRESS]", show.Equipment.AddressDetails); contents = contents.Replace("[VETNAME]", show.Vet.Name); contents = contents.Replace("[VETADDRESS]", show.Vet.AddressDetails); contents = contents.Replace("[SHOWENTRIESNAME]", show.ShowEntries.Name); contents = contents.Replace("[SHOWENTRIESADDRESS]", show.ShowEntries.AddressDetails); contents = contents.Replace("[PAYABLENAME]", show.Payable.Name); contents = contents.Replace("[PAYABLEADDRESS]", show.Payable.AddressDetails); Document doc = new Document(PageSize.A4, 25, 10, 10, 10); Stream output ; if (publish) { String path = context.Server.MapPath(@"..\schedules\"); path += DateTime.Today.ToString("yyyy"); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } path += String.Format("\\{0:yyyyMMM}_{1}.pdf", show.ShowDate, show.ShowName); output = new FileStream(path, FileMode.Create); show.setStatus(Shows.SHOW_STATUS.PUBLISHED); } else { output = new MemoryStream(); } var writer = PdfWriter.GetInstance(doc, output); StyleSheet sheet = new StyleSheet(); doc.Open(); var parsedHTML = HTMLWorker.ParseToList(new StringReader(contents), sheet); foreach (var htmlElement in parsedHTML) { doc.Add(htmlElement as IElement); } doc.NewPage(); foreach (DataRow row in table.Rows) { ShowDetails _showDetails = new ShowDetails(row); DataTable showDayTable = _showDetails.GetDayData(true); String dayHtml = generateClassesForDay(_showDetails.ShowDetailsID, showDayTable); doc.NewPage(); var dayClasses = HTMLWorker.ParseToList(new StringReader(dayHtml), sheet); foreach (var htmlElement in dayClasses) { doc.Add(htmlElement as IElement); } }; doc.NewPage(); contents = File.ReadAllText(context.Server.MapPath("schedule2RulesNRegs.html")); parsedHTML = HTMLWorker.ParseToList(new StringReader(contents), sheet); foreach (var htmlElement in parsedHTML) { doc.Add(htmlElement as IElement); } #if TEST foreach (DataRow row in table.Rows) { PdfPTable pdfTable = new PdfPTable(5); ShowDetails _showDetails = new ShowDetails(row); DataTable showDayTable = _showDetails.GetDayData(true); String dateThing = getDateOrdinalSuffix(_showDetails.ShowDate.Day); String datestr = _showDetails.ShowDate.ToString("dddd MMM d").ToUpper() + dateThing; PdfPCell pdfCell = new PdfPCell(); pdfCell = new PdfPCell(new Phrase(datestr )); pdfCell.Colspan = 5; pdfTable.AddCell(pdfCell); pdfTable.AddCell("ClsNo"); pdfCell = new PdfPCell(new Phrase("Name")); pdfCell.Colspan = 3; pdfTable.AddCell(pdfCell); pdfTable.AddCell("Grades"); pdfTable = new PdfPTable(5); foreach (DataRow clsRow in showDayTable.Rows) { PdfPTable grades = new PdfPTable(7); String str = clsRow["grades"].ToString(); for (int i = 1; i <= 7; i++) { if (str.IndexOf((char)(i + 48)) > -1) { grades.AddCell(i.ToString()); } else { grades.AddCell(" "); } } pdfTable.AddCell(clsRow["ClsNo"].ToString() ); pdfCell = new PdfPCell(new Phrase(clsRow["Name"].ToString())); pdfCell.Colspan = 3; pdfTable.AddCell(pdfCell); pdfTable.AddCell(grades); doc.Add(pdfTable); } doc.NewPage(); } #endif doc.Close(); if (publish) { } else { context.Response.ClearContent(); context.Response.ContentType = "application/pdf"; context.Response.AddHeader("content-disposition", String.Format("inline;filename=PreviewSchedule.pdf")); context.Response.BinaryWrite( (output as MemoryStream).ToArray()); } }
// --------------------------------------------------------------------------- public override void Write(Stream stream) { using (ZipFile zip = new ZipFile()) { HtmlMovies2 movies = new HtmlMovies2(); // create a StyleSheet StyleSheet styles = new StyleSheet(); styles.LoadTagStyle("ul", "indent", "10"); styles.LoadTagStyle("li", "leading", "14"); styles.LoadStyle("country", "i", ""); styles.LoadStyle("country", "color", "#008080"); styles.LoadStyle("director", "b", ""); styles.LoadStyle("director", "color", "midnightblue"); movies.SetStyles(styles); // create extra properties Dictionary<String,Object> map = new Dictionary<String, Object>(); map.Add(HTMLWorker.FONT_PROVIDER, new MyFontFactory()); map.Add(HTMLWorker.IMG_PROVIDER, new MyImageFactory()); movies.SetProviders(map); // creates HTML and PDF (reusing a method from the super class) byte[] pdf = movies.CreateHtmlAndPdf(stream); zip.AddEntry(HTML, movies.Html.ToString()); zip.AddEntry(RESULT1, pdf); zip.AddEntry(RESULT2, movies.CreatePdf()); // add the images so the static html file works foreach (Movie movie in PojoFactory.GetMovies()) { zip.AddFile( Path.Combine( Utility.ResourcePosters, string.Format("{0}.jpg", movie.Imdb) ), "" ); } zip.Save(stream); } }
public override void ProcessRequest(HttpContext context) { int ShowID = Convert.ToInt32(context.Request["showid"]); Shows show = new Shows(ShowID); DateTime fromDate, toDate; if (string.IsNullOrEmpty(context.Request["FromDate"])) { fromDate = DateTime.MinValue; } else { fromDate = DateTime.Parse(context.Request["FromDate"].ToString()); } if (string.IsNullOrEmpty(context.Request["ToDate"])) { toDate = DateTime.MaxValue; } else { toDate = DateTime.Parse(context.Request["ToDate"].ToString()).AddDays(1).AddMinutes(-1); } doc = new Document(PageSize.A4, -10, -50, 100, 50); Stream output = new MemoryStream(); var writer = PdfWriter.GetInstance(doc, output); var pageEvent = new Fpp.Core.PdfDocuments.ITextEvents(); pageEvent.Header = "Online Payments"; pageEvent.SubHeader = string.Format("{0} {1}", show.ShowName, show.ShowDate.ToString("dd MMM yyyy")); writer.PageEvent = pageEvent; StyleSheet sheet = new StyleSheet(); doc.Open(); ptable = new PdfPTable(headerWidths); var masterList = Transaction.getOnlineUserTransactions(ShowID) .Where(x => x.TransactionDate >= fromDate && x.TransactionDate <= toDate).OrderByDescending(x => x.TransactionDate).ToList(); //PrintReport("", masterList); var fixedFees = ShowDiscounts.getDiscountsByType(ShowID, -1, (int)DiscountTypes.TransactionCharge).Sum(x => x.Amount); PrintReport("Club Transaction List", masterList .Where(x => x.TransactionType == TransactionTypes.ShowEntryPayment && Regex.IsMatch(x.Comment, @"^\d+$") && x.Amount > 0) .OrderByDescending( x=> x.TransactionDate) .ToList(), fixedFees, true); doc.Close(); context.Response.ClearContent(); context.Response.ContentType = "application/pdf"; context.Response.AddHeader("content-disposition", String.Format("inline;filename=ClubTransactions-{0:ddMMMyyyy}.pdf", show.ShowDate)); context.Response.BinaryWrite((output as MemoryStream).ToArray()); }