/// <summary> /// Add a page that includes a bullet list. /// </summary> /// <param name="doc"></param> private void AddPageWithBulletList(iTextSharp.text.Document doc, List <string> data, string listName, string warningMessage) { // Add a new page to the document doc.NewPage(); // The header at the top of the page is an anchor linked to by the table of contents. iTextSharp.text.Anchor contentsAnchor = new iTextSharp.text.Anchor(listName, this.largeFont); contentsAnchor.Name = "research"; // Add the header anchor to the page this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_CENTER, this.largeFont, contentsAnchor); // Create an unordered bullet list. The 10f argument separates the bullet from the text by 10 points iTextSharp.text.List list = new iTextSharp.text.List(iTextSharp.text.List.UNORDERED, 10f); list.SetListSymbol("\u2022"); // Set the bullet symbol (without this a hypen starts each list item) list.IndentationLeft = 20f; // Indent the list 20 points foreach (var emp in data) { list.Add(new ListItem(emp, this.standardFont)); } doc.Add(list); // Add the list to the page // Add some white space and another heading this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_CENTER, this.largeFont, new Chunk("\n\n\n")); this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_CENTER, this.largeFont, new Chunk("WARNING (!)\n\n")); // Add some final text to the page this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_LEFT, this.standardFont, new Chunk(warningMessage)); }
/// <summary> /// 添加链接 /// </summary> /// <param name="Content">链接文字</param> /// <param name="FontSize">字体大小</param> /// <param name="Reference">链接地址</param> public void AddAnchorReference(string Content, float FontSize, string Reference) { SetFont(FontSize); Anchor auc = new Anchor(Content, font); auc.Reference = Reference; document.Add(auc); }
/// <summary> /// Add a page that includes a bullet list. /// </summary> /// <param name="doc"></param> private void AddPageWithBulletList(iTextSharp.text.Document doc) { // Add a new page to the document doc.NewPage(); // The header at the top of the page is an anchor linked to by the table of contents. iTextSharp.text.Anchor contentsAnchor = new iTextSharp.text.Anchor("RESEARCH\n\n", _largeFont); contentsAnchor.Name = "research"; // Add the header anchor to the page this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_CENTER, _largeFont, contentsAnchor); // Create an unordered bullet list. The 10f argument separates the bullet from the text by 10 points iTextSharp.text.List list = new iTextSharp.text.List(iTextSharp.text.List.UNORDERED, 10f); list.SetListSymbol("\u2022"); // Set the bullet symbol (without this a hypen starts each list item) list.IndentationLeft = 20f; // Indent the list 20 points list.Add(new iTextSharp.text.ListItem("Lift, thrust, drag, and gravity are the four forces that act on a plane.", _standardFont)); list.Add(new iTextSharp.text.ListItem("A plane should be light to help fight against gravity's pull to the ground.", _standardFont)); list.Add(new iTextSharp.text.ListItem("Gravity will have less effect on a plane built from the lightest materials available.", _standardFont)); list.Add(new iTextSharp.text.ListItem("In order to fly well, airplanes must be stable.", _standardFont)); list.Add(new iTextSharp.text.ListItem("A plane that is unstable will either pitch up into a stall, or nose-dive.", _standardFont)); doc.Add(list); // Add the list to the page // Add some white space and another heading this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_CENTER, _largeFont, new Chunk("\n\n\nHYPOTHESIS\n\n")); // Add some final text to the page this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_LEFT, _standardFont, new Chunk("Given five paper airplanes made out of newspaper, printer paper, construction paper, paper towel, and posterboard, the airplane made out of printer paper will fly the furthest.")); }
/// <summary> /// Add a page that contains embedded hyperlinks to external resources /// </summary> /// <param name="doc"></param> private void AddPageWithExternalLinks(Document doc) { // Generate external links to be embedded in the page Anchor linkAnchor1 = new Anchor("realtor.com", _standardFont); Anchor linkAnchor2 = new Anchor("cnn", _standardFont); Anchor linkAnchor3 = new Anchor("microsoft", _standardFont); linkAnchor1.Reference = "http://www.realtor.com"; linkAnchor2.Reference = "http://www.cnn.com/"; linkAnchor3.Reference = "http://www.microsoft.com/"; // The header at the top of the page is an anchor linked to by the table of contents. iTextSharp.text.Anchor contentsAnchor = new iTextSharp.text.Anchor("RESULTS\n\n", _largeFont); contentsAnchor.Name = "end"; // Add a new page to the document doc.NewPage(); // Add text to the page this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_CENTER, _largeFont, contentsAnchor); this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_LEFT, _standardFont, new Chunk("Document sent to client")); this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_CENTER, _largeFont, new Chunk("\n\n\n")); this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_CENTER, _largeFont, new Chunk("Links\n\n")); // Add the links to the page this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_LEFT, _standardFont, linkAnchor1); this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_LEFT, _standardFont, linkAnchor2); this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_LEFT, _standardFont, linkAnchor3); }
/// <summary> /// Add a page that includes a bullet list. /// </summary> /// <param name="doc"></param> private void AddPageWithBulletList(iTextSharp.text.Document doc) { // Add a new page to the document doc.NewPage(); // The header at the top of the page is an anchor linked to by the table of contents. iTextSharp.text.Anchor contentsAnchor = new iTextSharp.text.Anchor("Beginning page\n\n", _largeFont); contentsAnchor.Name = "start"; // Add the header anchor to the page this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_CENTER, _largeFont, contentsAnchor); // Create an unordered bullet list. The 10f argument separates the bullet from the text by 10 points iTextSharp.text.List list = new iTextSharp.text.List(iTextSharp.text.List.UNORDERED, 10f); list.SetListSymbol("\u2022"); // Set the bullet symbol (without this a hypen starts each list item) list.IndentationLeft = 20f; // Indent the list 20 points list.Add(new ListItem("Print document", _standardFont)); list.Add(new ListItem("Route to mail room", _standardFont)); list.Add(new ListItem("Route to accounting", _standardFont)); list.Add(new ListItem("Check approval", _standardFont)); list.Add(new ListItem("Send the check", _standardFont)); doc.Add(list); // Add the list to the page // Add some white space and another heading this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_CENTER, _largeFont, new Chunk("\n\n\n")); this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_CENTER, _largeFont, new Chunk("Error condition\n\n")); // Add some final text to the page this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_LEFT, _standardFont, new Chunk("In case of error, check will be manually approved")); }
/// <summary> /// 添加链接点 /// </summary> /// <param name="Content">链接文字</param> /// <param name="FontSize">字体大小</param> /// <param name="Name">链接点名</param> public void AddAnchorName(string Content, float FontSize, string Name) { SetFont(FontSize); Anchor auc = new Anchor(Content, font); auc.Name = Name; document.Add(auc); }
/// <summary> /// Add a page containing a single image. Set the page size to match the image size. /// </summary> /// <param name="doc"></param> /// <param name="imagePath"></param> private void AddPageWithImage(iTextSharp.text.Document doc, String imagePath) { // Read the image file iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(new Uri(imagePath)); // Set the page size to the dimensions of the image BEFORE adding a new page to the document. // Pad the height a bit to leave room for the page header. float imageWidth = image.Width; float imageHeight = image.Height; doc.SetMargins(0, 0, 0, 0); doc.SetPageSize(new iTextSharp.text.Rectangle(imageWidth, imageHeight + 100)); // Add a new page doc.NewPage(); // The header at the top of the page is an anchor linked to by the table of contents. iTextSharp.text.Anchor contentsAnchor = new iTextSharp.text.Anchor("\nGRAPH\n\n", _largeFont); contentsAnchor.Name = "graph"; // Add the anchor and image to the page this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_CENTER, _largeFont, contentsAnchor); doc.Add(image); image = null; }
/// <summary> /// Add a page that contains embedded hyperlinks to external resources /// </summary> /// <param name="doc"></param> private void AddPageWithExternalLinks(Document doc) { // Generate external links to be embedded in the page iTextSharp.text.Anchor bibliographyAnchor1 = new Anchor("http://teacher.scholastic.com/paperairplane/airplane.htm", _standardFont); bibliographyAnchor1.Reference = "http://teacher.scholastic.com/paperairplane/airplane.htm"; Anchor bibliographyAnchor2 = new Anchor("http://www.eecs.berkeley.edu/Programs/doublex/spring02/paperairplane.html", _standardFont); bibliographyAnchor1.Reference = "http://www.eecs.berkeley.edu/Programs/doublex/spring02/paperairplane.html"; Anchor bibliographyAnchor3 = new Anchor("http://www.exo.net/~pauld/activities/flying/PaperAirplaneScience.html", _standardFont); bibliographyAnchor1.Reference = "http://www.exo.net/~pauld/activities/flying/PaperAirplaneScience.html"; Anchor bibliographyAnchor4 = new Anchor("http://www.littletoyairplanes.com/theoryofflight/02whyplanes.html", _standardFont); bibliographyAnchor4.Reference = "http://www.littletoyairplanes.com/theoryofflight/02whyplanes.html"; // The header at the top of the page is an anchor linked to by the table of contents. iTextSharp.text.Anchor contentsAnchor = new iTextSharp.text.Anchor("RESULTS\n\n", _largeFont); contentsAnchor.Name = "results"; // Add a new page to the document doc.NewPage(); // Add text to the page this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_CENTER, _largeFont, contentsAnchor); this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_LEFT, _standardFont, new Chunk("My hypothesis was incorrect. The paper airplane made out of construction paper flew the furthest.\n\n\n")); this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_CENTER, _largeFont, new Chunk("BIBLIOGRAPHY\n\n")); // Add the links to the page this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_LEFT, _standardFont, bibliographyAnchor1); this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_LEFT, _standardFont, bibliographyAnchor2); this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_LEFT, _standardFont, bibliographyAnchor3); this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_LEFT, _standardFont, bibliographyAnchor4); }
private static void SetAnchor(ISPage iSPage, Chapter chapter, Dictionary<string, int> pageMap) { Anchor anchorTarget = new Anchor(iSPage.RoomId); anchorTarget.Name = iSPage.RoomId; Paragraph targetParagraph = new Paragraph(); targetParagraph.Add(anchorTarget); chapter.Add(targetParagraph); }
// =========================================================================== public void Write(Stream stream) { var SQL = @"SELECT DISTINCT mc.country_id, c.country, count(*) AS c FROM film_country c, film_movie_country mc WHERE c.id = mc.country_id GROUP BY mc.country_id, country ORDER BY c DESC"; // step 1 using (Document document = new Document()) { // step 2 PdfWriter.GetInstance(document, stream); // step 3 document.Open(); // step 4 using (var c = AdoDB.Provider.CreateConnection()) { c.ConnectionString = AdoDB.CS; using (DbCommand cmd = c.CreateCommand()) { cmd.CommandText = SQL; c.Open(); using (var r = cmd.ExecuteReader()) { while (r.Read()) { Paragraph country = new Paragraph(); // the name of the country will be a destination Anchor dest = new Anchor( r["country"].ToString(), FilmFonts.BOLD ); dest.Name = r["country_id"].ToString(); country.Add(dest); country.Add(string.Format(": {0} movies", r["c"].ToString())); document.Add(country); // loop over the movies foreach (Movie movie in PojoFactory.GetMovies(r["country_id"].ToString())) { // the movie title will be an external link Anchor imdb = new Anchor(movie.MovieTitle); imdb.Reference = string.Format( "http://www.imdb.com/title/tt{0}/", movie.Imdb ); document.Add(imdb); document.Add(Chunk.NEWLINE); } document.NewPage(); } // Create an internal link to the first page Anchor toUS = new Anchor("Go back to the first page."); toUS.Reference = "#US"; document.Add(toUS); } } } } }
public static Anchor GetAnchor(Properties attributes) { Anchor anchor = new Anchor(GetPhrase(attributes)); String value; value = attributes[ElementTags.NAME]; if (value != null) { anchor.Name = value; } value = (String)attributes.Remove(ElementTags.REFERENCE); if (value != null) { anchor.Reference = value; } return anchor; }
/// <summary> /// Add a page that contains embedded hyperlinks to external resources /// </summary> /// <param name="doc"></param> private void AddPageWithExternalLinks(Document doc) { // Generate external links to be embedded in the page iTextSharp.text.Anchor bibliographyAnchor1 = new Anchor("Click here to explore our project in GitHub", this.linkFont); bibliographyAnchor1.Reference = "https://github.com/TripleBounty/VideoRentalSystem"; // The header at the top of the page is an anchor linked to by the table of contents. iTextSharp.text.Anchor contentsAnchor = new iTextSharp.text.Anchor("\n\n", this.largeFont); contentsAnchor.Name = "results"; // Add a new page to the document doc.NewPage(); // Add text to the page this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_CENTER, this.largeFont, contentsAnchor); this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_CENTER, this.largeFont, new Chunk("BIBLIOGRAPHY\n\n")); // Add the links to the page this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_LEFT, this.standardFont, bibliographyAnchor1); }
public void Run(Stream stream, CMSDataContext Db, IEnumerable<ContributorInfo> q, int set = 0) { pageEvents.set = set; pageEvents.PeopleId = 0; IEnumerable<ContributorInfo> contributors = q; var toDate = ToDate.Date.AddHours(24).AddSeconds(-1); PdfContentByte dc; var font = FontFactory.GetFont(FontFactory.HELVETICA, 11); var boldfont = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 11); var doc = new Document(PageSize.LETTER); doc.SetMargins(36f, 30f, 24f, 36f); var w = PdfWriter.GetInstance(doc, stream); w.PageEvent = pageEvents; doc.Open(); dc = w.DirectContent; var prevfid = 0; var runningtotals = Db.ContributionsRuns.OrderByDescending(mm => mm.Id).First(); runningtotals.Processed = 0; Db.SubmitChanges(); var count = 0; foreach (var ci in contributors) { if (set > 0 && pageEvents.FamilySet[ci.PeopleId] != set) continue; var contributions = APIContribution.contributions(Db, ci, FromDate, toDate).ToList(); var pledges = APIContribution.pledges(Db, ci, toDate).ToList(); var giftsinkind = APIContribution.GiftsInKind(Db, ci, FromDate, toDate).ToList(); var nontaxitems = Db.Setting("DisplayNonTaxOnStatement", "false").ToBool() ? APIContribution.NonTaxItems(Db, ci, FromDate, toDate).ToList() : new List<ContributionInfo>(); if ((contributions.Count + pledges.Count + giftsinkind.Count + nontaxitems.Count) == 0) { runningtotals.Processed += 1; runningtotals.CurrSet = set; Db.SubmitChanges(); if (set == 0) pageEvents.FamilySet[ci.PeopleId] = 0; continue; } pageEvents.NextPeopleId = ci.PeopleId; doc.NewPage(); if (prevfid != ci.FamilyId) { prevfid = ci.FamilyId; pageEvents.EndPageSet(); pageEvents.PeopleId = ci.PeopleId; } if (set == 0) pageEvents.FamilySet[ci.PeopleId] = 0; count++; var css = @" <style> h1 { font-size: 24px; font-weight:normal; margin-bottom:0; } h2 { font-size: 11px; font-weight:normal; margin-top: 0; } p { font-size: 11px; } </style> "; //----Church Name var t1 = new PdfPTable(1); t1.TotalWidth = 72f * 5f; t1.DefaultCell.Border = Rectangle.NO_BORDER; string html1 = Db.ContentHtml("StatementHeader", Resource1.ContributionStatementHeader); string html2 = Db.ContentHtml("StatementNotice", Resource1.ContributionStatementNotice); var mh = new MyHandler(); using (var sr = new StringReader(css + html1)) XMLWorkerHelper.GetInstance().ParseXHtml(mh, sr); var cell = new PdfPCell(t1.DefaultCell); foreach (var e in mh.elements) if (e.Chunks.Count > 0) cell.AddElement(e); //cell.FixedHeight = 72f * 1.25f; t1.AddCell(cell); t1.AddCell("\n"); var t1a = new PdfPTable(1); t1a.TotalWidth = 72f * 5f; t1a.DefaultCell.Border = Rectangle.NO_BORDER; var ae = new PdfPTable(1); ae.DefaultCell.Border = Rectangle.NO_BORDER; ae.WidthPercentage = 100; var a = new PdfPTable(1); a.DefaultCell.Indent = 25f; a.DefaultCell.Border = Rectangle.NO_BORDER; a.AddCell(new Phrase(ci.Name, font)); foreach (var line in ci.MailingAddress.SplitLines()) a.AddCell(new Phrase(line, font)); cell = new PdfPCell(a) { Border = Rectangle.NO_BORDER }; //cell.FixedHeight = 72f * 1.0625f; ae.AddCell(cell); cell = new PdfPCell(t1a.DefaultCell); cell.AddElement(ae); t1a.AddCell(ae); //-----Notice var t2 = new PdfPTable(1); t2.TotalWidth = 72f * 3f; t2.DefaultCell.Border = Rectangle.NO_BORDER; t2.AddCell(Db.Setting("NoPrintDateOnStatement") ? new Phrase($"\nID:{ci.PeopleId} {ci.CampusId}", font) : new Phrase($"\nPrint Date: {DateTime.Now:d} (id:{ci.PeopleId} {ci.CampusId})", font)); t2.AddCell(""); var mh2 = new MyHandler(); using (var sr = new StringReader(css + html2)) XMLWorkerHelper.GetInstance().ParseXHtml(mh2, sr); cell = new PdfPCell(t1.DefaultCell); foreach (var e in mh2.elements) if (e.Chunks.Count > 0) cell.AddElement(e); t2.AddCell(cell); // POSITIONING OF ADDRESSES //----Header var yp = doc.BottomMargin + Db.Setting("StatementRetAddrPos", "10.125").ToFloat() * 72f; t1.WriteSelectedRows(0, -1, doc.LeftMargin - 0.1875f * 72f, yp, dc); yp = doc.BottomMargin + Db.Setting("StatementAddrPos", "8.3375").ToFloat() * 72f; t1a.WriteSelectedRows(0, -1, doc.LeftMargin, yp, dc); yp = doc.BottomMargin + 10.125f * 72f; t2.WriteSelectedRows(0, -1, doc.LeftMargin + 72f * 4.4f, yp, dc); //----Contributions doc.Add(new Paragraph(" ")); doc.Add(new Paragraph(" ") { SpacingBefore = 72f * 2.125f }); doc.Add(new Phrase($"\n Period: {FromDate:d} - {toDate:d}", boldfont)); var pos = w.GetVerticalPosition(true); var ct = new ColumnText(dc); float gutter = 20f; float colwidth = (doc.Right - doc.Left - gutter) / 2; var t = new PdfPTable(new[] { 10f, 24f, 10f }); t.WidthPercentage = 100; t.DefaultCell.Border = Rectangle.NO_BORDER; t.HeaderRows = 2; cell = new PdfPCell(t.DefaultCell); cell.Colspan = 3; cell.Phrase = new Phrase("Contributions\n", boldfont); t.AddCell(cell); t.DefaultCell.Border = Rectangle.BOTTOM_BORDER; t.AddCell(new Phrase("Date", boldfont)); t.AddCell(new Phrase("Description", boldfont)); cell = new PdfPCell(t.DefaultCell); cell.HorizontalAlignment = Element.ALIGN_RIGHT; cell.Phrase = new Phrase("Amount", boldfont); t.AddCell(cell); t.DefaultCell.Border = Rectangle.NO_BORDER; var total = 0m; foreach (var c in contributions) { t.AddCell(new Phrase(c.ContributionDate.ToShortDateString(), font)); t.AddCell(new Phrase(c.Fund, font)); cell = new PdfPCell(t.DefaultCell); cell.HorizontalAlignment = Element.ALIGN_RIGHT; cell.Phrase = new Phrase(c.ContributionAmount.ToString("N2"), font); t.AddCell(cell); total += (c.ContributionAmount); } t.DefaultCell.Border = Rectangle.TOP_BORDER; cell = new PdfPCell(t.DefaultCell); cell.Colspan = 2; cell.Phrase = new Phrase("Total Contributions for period", boldfont); t.AddCell(cell); cell = new PdfPCell(t.DefaultCell); cell.HorizontalAlignment = Element.ALIGN_RIGHT; cell.Phrase = new Phrase(total.ToString("N2"), font); t.AddCell(cell); ct.AddElement(t); //------Pledges if (pledges.Count > 0) { t = new PdfPTable(new float[] { 16f, 12f, 12f }); t.WidthPercentage = 100; t.DefaultCell.Border = Rectangle.NO_BORDER; t.HeaderRows = 2; cell = new PdfPCell(t.DefaultCell); cell.Colspan = 3; cell.Phrase = new Phrase("\n\nPledges\n", boldfont); t.AddCell(cell); t.DefaultCell.Border = Rectangle.BOTTOM_BORDER; t.AddCell(new Phrase("Fund", boldfont)); cell = new PdfPCell(t.DefaultCell); cell.HorizontalAlignment = Element.ALIGN_RIGHT; cell.Phrase = new Phrase("Pledge", boldfont); t.AddCell(cell); cell = new PdfPCell(t.DefaultCell); cell.HorizontalAlignment = Element.ALIGN_RIGHT; cell.Phrase = new Phrase("Given", boldfont); t.AddCell(cell); t.DefaultCell.Border = Rectangle.NO_BORDER; foreach (var c in pledges) { t.AddCell(new Phrase(c.Fund, font)); cell = new PdfPCell(t.DefaultCell); cell.HorizontalAlignment = Element.ALIGN_RIGHT; cell.Phrase = new Phrase(c.PledgeAmount.ToString2("N2"), font); t.AddCell(cell); cell = new PdfPCell(t.DefaultCell); cell.HorizontalAlignment = Element.ALIGN_RIGHT; cell.Phrase = new Phrase(c.ContributionAmount.ToString2("N2"), font); t.AddCell(cell); } ct.AddElement(t); } //------Gifts In Kind if (giftsinkind.Count > 0) { t = new PdfPTable(new float[] { 12f, 18f, 20f }); t.WidthPercentage = 100; t.DefaultCell.Border = Rectangle.NO_BORDER; t.HeaderRows = 2; cell = new PdfPCell(t.DefaultCell); cell.Colspan = 3; cell.Phrase = new Phrase("\n\nGifts in Kind\n", boldfont); t.AddCell(cell); t.DefaultCell.Border = Rectangle.BOTTOM_BORDER; t.AddCell(new Phrase("Date", boldfont)); cell = new PdfPCell(t.DefaultCell); cell.Phrase = new Phrase("Fund", boldfont); t.AddCell(cell); cell = new PdfPCell(t.DefaultCell); cell.Phrase = new Phrase("Description", boldfont); t.AddCell(cell); t.DefaultCell.Border = Rectangle.NO_BORDER; foreach (var c in giftsinkind) { t.AddCell(new Phrase(c.ContributionDate.ToShortDateString(), font)); cell = new PdfPCell(t.DefaultCell); cell.Phrase = new Phrase(c.Fund, font); t.AddCell(cell); cell = new PdfPCell(t.DefaultCell); cell.Phrase = new Phrase(c.Description, font); t.AddCell(cell); } ct.AddElement(t); } //-----Summary t = new PdfPTable(new float[] { 29f, 9f }); t.WidthPercentage = 100; t.DefaultCell.Border = Rectangle.NO_BORDER; t.HeaderRows = 2; cell = new PdfPCell(t.DefaultCell); cell.Colspan = 2; cell.Phrase = new Phrase("\n\nPeriod Summary\n", boldfont); t.AddCell(cell); t.DefaultCell.Border = Rectangle.BOTTOM_BORDER; t.AddCell(new Phrase("Fund", boldfont)); cell = new PdfPCell(t.DefaultCell); cell.HorizontalAlignment = Element.ALIGN_RIGHT; cell.Phrase = new Phrase("Amount", boldfont); t.AddCell(cell); t.DefaultCell.Border = Rectangle.NO_BORDER; foreach (var c in APIContribution.quarterlySummary(Db, ci, FromDate, toDate)) { t.AddCell(new Phrase(c.Fund, font)); cell = new PdfPCell(t.DefaultCell); cell.HorizontalAlignment = Element.ALIGN_RIGHT; cell.Phrase = new Phrase(c.ContributionAmount.ToString("N2"), font); t.AddCell(cell); } t.DefaultCell.Border = Rectangle.TOP_BORDER; t.AddCell(new Phrase("Total contributions for period", boldfont)); cell = new PdfPCell(t.DefaultCell); cell.HorizontalAlignment = Element.ALIGN_RIGHT; cell.Phrase = new Phrase(total.ToString("N2"), font); t.AddCell(cell); ct.AddElement(t); //------NonTax if (nontaxitems.Count > 0) { t = new PdfPTable(new float[] { 10f, 24f, 10f }); t.WidthPercentage = 100; t.DefaultCell.Border = Rectangle.NO_BORDER; t.HeaderRows = 2; cell = new PdfPCell(t.DefaultCell); cell.Colspan = 3; cell.Phrase = new Phrase("\n\nNon Tax-Deductible Items\n", boldfont); t.AddCell(cell); t.DefaultCell.Border = Rectangle.BOTTOM_BORDER; t.AddCell(new Phrase("Date", boldfont)); t.AddCell(new Phrase("Description", boldfont)); cell = new PdfPCell(t.DefaultCell); cell.HorizontalAlignment = Element.ALIGN_RIGHT; cell.Phrase = new Phrase("Amount", boldfont); t.AddCell(cell); t.DefaultCell.Border = Rectangle.NO_BORDER; var ntotal = 0m; foreach (var c in nontaxitems) { t.AddCell(new Phrase(c.ContributionDate.ToShortDateString(), font)); t.AddCell(new Phrase(c.Fund, font)); cell = new PdfPCell(t.DefaultCell); cell.HorizontalAlignment = Element.ALIGN_RIGHT; cell.Phrase = new Phrase(c.ContributionAmount.ToString("N2"), font); t.AddCell(cell); ntotal += (c.ContributionAmount); } t.DefaultCell.Border = Rectangle.TOP_BORDER; cell = new PdfPCell(t.DefaultCell); cell.Colspan = 2; cell.Phrase = new Phrase("Total Non Tax-Deductible Items for period", boldfont); t.AddCell(cell); cell = new PdfPCell(t.DefaultCell); cell.HorizontalAlignment = Element.ALIGN_RIGHT; cell.Phrase = new Phrase(ntotal.ToString("N2"), font); t.AddCell(cell); ct.AddElement(t); } var col = 0; var status = 0; while (ColumnText.HasMoreText(status)) { if (col == 0) ct.SetSimpleColumn(doc.Left, doc.Bottom, doc.Left + colwidth, pos); else if (col == 1) ct.SetSimpleColumn(doc.Right - colwidth, doc.Bottom, doc.Right, pos); status = ct.Go(); ++col; if (col > 1) { col = 0; pos = doc.Top; doc.NewPage(); } } runningtotals.Processed += 1; runningtotals.CurrSet = set; Db.SubmitChanges(); } if (count == 0) { doc.NewPage(); doc.Add(new Paragraph("no data")); var a = new Anchor("see this help document docs.touchpointsoftware.com/Finance/ContributionStatements.html") { Reference = "http://docs.touchpointsoftware.com/Finance/ContributionStatements.html#troubleshooting" }; doc.Add(a); } doc.Close(); if (set == LastSet()) runningtotals.Completed = DateTime.Now; Db.SubmitChanges(); }
private static void WriteChoices(ISPage iSPage, Dictionary<string, int> pageMap, Chapter chapter) { chapter.Add(new iTextSharp.text.Phrase(String.Format("\nYou have {0} choices:\n", iSPage.Choices.Count))); foreach (Choice choice in iSPage.Choices) { if(pageMap.ContainsKey(choice.RoomId)) { Anchor anchor = new Anchor(String.Format("{0} - Page {1}\n", choice.Text, pageMap[choice.RoomId])); anchor.Reference = "#" + choice.RoomId; Paragraph paragraph = new Paragraph(); paragraph.Add(anchor); chapter.Add(paragraph); //Chunk chunk = new Chunk(String.Format("{0} - Page {1}\n", choice.Text, pageMap[choice.RoomId])); //PdfAction action = PdfAction.GotoLocalPage(pageMap[choice.RoomId], new PdfDestination(0), ); //chunk.SetAction(action); } else { chapter.Add(new iTextSharp.text.Phrase(String.Format("{0} - Page {1}\n", choice.Text, "XXX"))); } } }
// --------------------------------------------------------------------------- // replace XmlHandler.endElement() from Java example public void EndElement(string name) { switch (name) { case "directors": FlushStack(); Paragraph p = new Paragraph( String.Format("Year: {0}; duration: {0}; ", year, duration) ); Anchor link = new Anchor("link to IMDB"); link.Reference = String.Format("http://www.imdb.com/title/tt{0}/", imdb); p.Add(link); stack.Push(p); break; case "countries": case "title": FlushStack(); break; case "original": case "movie": CurrentChunk = Chunk.NEWLINE; UpdateStack(); break; case "director": case "country": ListItem listItem = (ListItem) stack.Pop(); List list = (List) stack.Pop(); list.Add(listItem); stack.Push(list); break; } }
private Anchor getAnchor(FontSelector fontSelector, CellAttributes attributes) { var text = getText(attributes); var url = getUrl(attributes); var anchor = new Anchor(fontSelector.Process(text.ToSafeString())) { Reference = url }; return anchor; }
/// <summary> /// Print an order to PDF /// </summary> /// <param name="stream">Stream</param> /// <param name="orders">Orders</param> /// <param name="lang">Language</param> public virtual void PrintOrdersToPdf(Stream stream, IList<Order> orders, Language lang) { if (stream == null) throw new ArgumentNullException("stream"); if (orders == null) throw new ArgumentNullException("orders"); if (lang == null) throw new ArgumentNullException("lang"); var pageSize = PageSize.A4; if (_pdfSettings.LetterPageSizeEnabled) { pageSize = PageSize.LETTER; } var doc = new Document(pageSize); PdfWriter.GetInstance(doc, stream); doc.Open(); //fonts var titleFont = GetFont(); titleFont.SetStyle(Font.BOLD); titleFont.Color = BaseColor.BLACK; var font = GetFont(); var attributesFont = GetFont(); attributesFont.SetStyle(Font.ITALIC); int ordCount = orders.Count; int ordNum = 0; foreach (var order in orders) { #region Header //logo var logoPicture = _pictureService.GetPictureById(_pdfSettings.LogoPictureId); var logoExists = logoPicture != null; //header var headerTable = new PdfPTable(logoExists ? 2 : 1); headerTable.WidthPercentage = 100f; if (logoExists) headerTable.SetWidths(new[] { 50, 50 }); //logo if (logoExists) { var logoFilePath = _pictureService.GetThumbLocalPath(logoPicture, 0, false); var cellLogo = new PdfPCell(Image.GetInstance(logoFilePath)); cellLogo.Border = Rectangle.NO_BORDER; headerTable.AddCell(cellLogo); } //store info var cell = new PdfPCell(); cell.Border = Rectangle.NO_BORDER; cell.AddElement(new Paragraph(String.Format(_localizationService.GetResource("PDFInvoice.Order#", lang.Id), order.Id), titleFont)); var anchor = new Anchor(_storeInformationSettings.StoreUrl.Trim(new char[] { '/' }), font); anchor.Reference = _storeInformationSettings.StoreUrl; cell.AddElement(new Paragraph(anchor)); cell.AddElement(new Paragraph(String.Format(_localizationService.GetResource("PDFInvoice.OrderDate", lang.Id), _dateTimeHelper.ConvertToUserTime(order.CreatedOnUtc, DateTimeKind.Utc).ToString("D", new CultureInfo(lang.LanguageCulture))), font)); headerTable.AddCell(cell); doc.Add(headerTable); #endregion #region Addresses var addressTable = new PdfPTable(2); addressTable.WidthPercentage = 100f; addressTable.SetWidths(new[] { 50, 50 }); //billing info cell = new PdfPCell(); cell.Border = Rectangle.NO_BORDER; cell.AddElement(new Paragraph(_localizationService.GetResource("PDFInvoice.BillingInformation", lang.Id), titleFont)); if (_addressSettings.CompanyEnabled && !String.IsNullOrEmpty(order.BillingAddress.Company)) cell.AddElement(new Paragraph(" " + String.Format(_localizationService.GetResource("PDFInvoice.Company", lang.Id), order.BillingAddress.Company), font)); cell.AddElement(new Paragraph(" " + String.Format(_localizationService.GetResource("PDFInvoice.Name", lang.Id), order.BillingAddress.FirstName + " " + order.BillingAddress.LastName), font)); if (_addressSettings.PhoneEnabled) cell.AddElement(new Paragraph(" " + String.Format(_localizationService.GetResource("PDFInvoice.Phone", lang.Id), order.BillingAddress.PhoneNumber), font)); if (_addressSettings.FaxEnabled && !String.IsNullOrEmpty(order.BillingAddress.FaxNumber)) cell.AddElement(new Paragraph(" " + String.Format(_localizationService.GetResource("PDFInvoice.Fax", lang.Id), order.BillingAddress.FaxNumber), font)); if (_addressSettings.StreetAddressEnabled) cell.AddElement(new Paragraph(" " + String.Format(_localizationService.GetResource("PDFInvoice.Address", lang.Id), order.BillingAddress.Address1), font)); if (_addressSettings.StreetAddress2Enabled && !String.IsNullOrEmpty(order.BillingAddress.Address2)) cell.AddElement(new Paragraph(" " + String.Format(_localizationService.GetResource("PDFInvoice.Address2", lang.Id), order.BillingAddress.Address2), font)); if (_addressSettings.CityEnabled || _addressSettings.StateProvinceEnabled || _addressSettings.ZipPostalCodeEnabled) cell.AddElement(new Paragraph(" " + String.Format("{0}, {1} {2}", order.BillingAddress.City, order.BillingAddress.StateProvince != null ? order.BillingAddress.StateProvince.GetLocalized(x => x.Name, lang.Id) : "", order.BillingAddress.ZipPostalCode), font)); if (_addressSettings.CountryEnabled && order.BillingAddress.Country != null) cell.AddElement(new Paragraph(" " + String.Format("{0}", order.BillingAddress.Country != null ? order.BillingAddress.Country.GetLocalized(x => x.Name, lang.Id) : ""), font)); //VAT number if (!String.IsNullOrEmpty(order.VatNumber)) cell.AddElement(new Paragraph(" " + String.Format(_localizationService.GetResource("PDFInvoice.VATNumber", lang.Id), order.VatNumber), font)); //payment method var paymentMethod = _paymentService.LoadPaymentMethodBySystemName(order.PaymentMethodSystemName); string paymentMethodStr = paymentMethod != null ? paymentMethod.GetLocalizedFriendlyName(_localizationService, lang.Id) : order.PaymentMethodSystemName; if (!String.IsNullOrEmpty(paymentMethodStr)) { cell.AddElement(new Paragraph(" ")); cell.AddElement(new Paragraph(" " + String.Format(_localizationService.GetResource("PDFInvoice.PaymentMethod", lang.Id), paymentMethodStr), font)); cell.AddElement(new Paragraph()); } //purchase order number (we have to find a better to inject this information because it's related to a certain plugin) if (paymentMethod != null && paymentMethod.PluginDescriptor.SystemName.Equals("Payments.PurchaseOrder", StringComparison.InvariantCultureIgnoreCase)) { cell.AddElement(new Paragraph(" ")); cell.AddElement(new Paragraph(" " + String.Format(_localizationService.GetResource("PDFInvoice.PurchaseOrderNumber", lang.Id), order.PurchaseOrderNumber), font)); cell.AddElement(new Paragraph()); } addressTable.AddCell(cell); //shipping info if (order.ShippingStatus != ShippingStatus.ShippingNotRequired) { if (order.ShippingAddress == null) throw new NopException(string.Format("Shipping is required, but address is not available. Order ID = {0}", order.Id)); cell = new PdfPCell(); cell.Border = Rectangle.NO_BORDER; cell.AddElement(new Paragraph(_localizationService.GetResource("PDFInvoice.ShippingInformation", lang.Id), titleFont)); if (!String.IsNullOrEmpty(order.ShippingAddress.Company)) cell.AddElement(new Paragraph(" " + String.Format(_localizationService.GetResource("PDFInvoice.Company", lang.Id), order.ShippingAddress.Company), font)); cell.AddElement(new Paragraph(" " + String.Format(_localizationService.GetResource("PDFInvoice.Name", lang.Id), order.ShippingAddress.FirstName + " " + order.ShippingAddress.LastName), font)); if (_addressSettings.PhoneEnabled) cell.AddElement(new Paragraph(" " + String.Format(_localizationService.GetResource("PDFInvoice.Phone", lang.Id), order.ShippingAddress.PhoneNumber), font)); if (_addressSettings.FaxEnabled && !String.IsNullOrEmpty(order.ShippingAddress.FaxNumber)) cell.AddElement(new Paragraph(" " + String.Format(_localizationService.GetResource("PDFInvoice.Fax", lang.Id), order.ShippingAddress.FaxNumber), font)); if (_addressSettings.StreetAddressEnabled) cell.AddElement(new Paragraph(" " + String.Format(_localizationService.GetResource("PDFInvoice.Address", lang.Id), order.ShippingAddress.Address1), font)); if (_addressSettings.StreetAddress2Enabled && !String.IsNullOrEmpty(order.ShippingAddress.Address2)) cell.AddElement(new Paragraph(" " + String.Format(_localizationService.GetResource("PDFInvoice.Address2", lang.Id), order.ShippingAddress.Address2), font)); if (_addressSettings.CityEnabled || _addressSettings.StateProvinceEnabled || _addressSettings.ZipPostalCodeEnabled) cell.AddElement(new Paragraph(" " + String.Format("{0}, {1} {2}", order.ShippingAddress.City, order.ShippingAddress.StateProvince != null ? order.ShippingAddress.StateProvince.GetLocalized(x => x.Name, lang.Id) : "", order.ShippingAddress.ZipPostalCode), font)); if (_addressSettings.CountryEnabled && order.ShippingAddress.Country != null) cell.AddElement(new Paragraph(" " + String.Format("{0}", order.ShippingAddress.Country != null ? order.ShippingAddress.Country.GetLocalized(x => x.Name, lang.Id) : ""), font)); cell.AddElement(new Paragraph(" ")); cell.AddElement(new Paragraph(" " + String.Format(_localizationService.GetResource("PDFInvoice.ShippingMethod", lang.Id), order.ShippingMethod), font)); cell.AddElement(new Paragraph()); addressTable.AddCell(cell); } else { cell = new PdfPCell(new Phrase(" ")); cell.Border = Rectangle.NO_BORDER; addressTable.AddCell(cell); } doc.Add(addressTable); doc.Add(new Paragraph(" ")); #endregion #region Products //products doc.Add(new Paragraph(_localizationService.GetResource("PDFInvoice.Product(s)", lang.Id), titleFont)); doc.Add(new Paragraph(" ")); var orderProductVariants = _orderService.GetAllOrderProductVariants(order.Id, null, null, null, null, null, null); var productsTable = new PdfPTable(_catalogSettings.ShowProductSku ? 5 : 4); productsTable.WidthPercentage = 100f; productsTable.SetWidths(_catalogSettings.ShowProductSku ? new[] { 40, 15, 15, 15, 15 } : new[] { 40, 20, 20, 20 }); //product name cell = new PdfPCell(new Phrase(_localizationService.GetResource("PDFInvoice.ProductName", lang.Id), font)); cell.BackgroundColor = BaseColor.LIGHT_GRAY; cell.HorizontalAlignment = Element.ALIGN_CENTER; productsTable.AddCell(cell); //SKU if (_catalogSettings.ShowProductSku) { cell = new PdfPCell(new Phrase(_localizationService.GetResource("PDFInvoice.SKU", lang.Id), font)); cell.BackgroundColor = BaseColor.LIGHT_GRAY; cell.HorizontalAlignment = Element.ALIGN_CENTER; productsTable.AddCell(cell); } //price cell = new PdfPCell(new Phrase(_localizationService.GetResource("PDFInvoice.ProductPrice", lang.Id), font)); cell.BackgroundColor = BaseColor.LIGHT_GRAY; cell.HorizontalAlignment = Element.ALIGN_CENTER; productsTable.AddCell(cell); //qty cell = new PdfPCell(new Phrase(_localizationService.GetResource("PDFInvoice.ProductQuantity", lang.Id), font)); cell.BackgroundColor = BaseColor.LIGHT_GRAY; cell.HorizontalAlignment = Element.ALIGN_CENTER; productsTable.AddCell(cell); //total cell = new PdfPCell(new Phrase(_localizationService.GetResource("PDFInvoice.ProductTotal", lang.Id), font)); cell.BackgroundColor = BaseColor.LIGHT_GRAY; cell.HorizontalAlignment = Element.ALIGN_CENTER; productsTable.AddCell(cell); for (int i = 0; i < orderProductVariants.Count; i++) { var orderProductVariant = orderProductVariants[i]; var pv = orderProductVariant.ProductVariant; //product name string name = ""; if (!String.IsNullOrEmpty(pv.GetLocalized(x => x.Name, lang.Id))) name = string.Format("{0} ({1})", pv.Product.GetLocalized(x => x.Name, lang.Id), pv.GetLocalized(x => x.Name, lang.Id)); else name = pv.Product.GetLocalized(x => x.Name, lang.Id); cell = new PdfPCell(); cell.AddElement(new Paragraph(name, font)); cell.HorizontalAlignment = Element.ALIGN_LEFT; var attributesParagraph = new Paragraph(HtmlHelper.ConvertHtmlToPlainText(orderProductVariant.AttributeDescription, true, true), attributesFont); cell.AddElement(attributesParagraph); productsTable.AddCell(cell); //SKU if (_catalogSettings.ShowProductSku) { var sku = pv.FormatSku(orderProductVariant.AttributesXml, _productAttributeParser); cell = new PdfPCell(new Phrase(sku ?? String.Empty, font)); cell.HorizontalAlignment = Element.ALIGN_CENTER; productsTable.AddCell(cell); } //price string unitPrice = string.Empty; switch (order.CustomerTaxDisplayType) { case TaxDisplayType.ExcludingTax: { var opvUnitPriceExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(orderProductVariant.UnitPriceExclTax, order.CurrencyRate); unitPrice = _priceFormatter.FormatPrice(opvUnitPriceExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, lang, false); } break; case TaxDisplayType.IncludingTax: { var opvUnitPriceInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(orderProductVariant.UnitPriceInclTax, order.CurrencyRate); unitPrice = _priceFormatter.FormatPrice(opvUnitPriceInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, lang, true); } break; } cell = new PdfPCell(new Phrase(unitPrice, font)); cell.HorizontalAlignment = Element.ALIGN_LEFT; productsTable.AddCell(cell); //qty cell = new PdfPCell(new Phrase(orderProductVariant.Quantity.ToString(), font)); cell.HorizontalAlignment = Element.ALIGN_LEFT; productsTable.AddCell(cell); //total string subTotal = string.Empty; switch (order.CustomerTaxDisplayType) { case TaxDisplayType.ExcludingTax: { var opvPriceExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(orderProductVariant.PriceExclTax, order.CurrencyRate); subTotal = _priceFormatter.FormatPrice(opvPriceExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, lang, false); } break; case TaxDisplayType.IncludingTax: { var opvPriceInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(orderProductVariant.PriceInclTax, order.CurrencyRate); subTotal = _priceFormatter.FormatPrice(opvPriceInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, lang, true); } break; } cell = new PdfPCell(new Phrase(subTotal, font)); cell.HorizontalAlignment = Element.ALIGN_LEFT; productsTable.AddCell(cell); } doc.Add(productsTable); #endregion #region Checkout attributes if (!String.IsNullOrEmpty(order.CheckoutAttributeDescription)) { doc.Add(new Paragraph(" ")); string attributes = HtmlHelper.ConvertHtmlToPlainText(order.CheckoutAttributeDescription, true, true); var pCheckoutAttributes = new Paragraph(attributes, font); pCheckoutAttributes.Alignment = Element.ALIGN_RIGHT; doc.Add(pCheckoutAttributes); doc.Add(new Paragraph(" ")); } #endregion #region Totals //subtotal doc.Add(new Paragraph(" ")); switch (order.CustomerTaxDisplayType) { case TaxDisplayType.ExcludingTax: { var orderSubtotalExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderSubtotalExclTax, order.CurrencyRate); string orderSubtotalExclTaxStr = _priceFormatter.FormatPrice(orderSubtotalExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, lang, false); var p = new Paragraph(String.Format("{0} {1}", _localizationService.GetResource("PDFInvoice.Sub-Total", lang.Id), orderSubtotalExclTaxStr), font); p.Alignment = Element.ALIGN_RIGHT; doc.Add(p); } break; case TaxDisplayType.IncludingTax: { var orderSubtotalInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderSubtotalInclTax, order.CurrencyRate); string orderSubtotalInclTaxStr = _priceFormatter.FormatPrice(orderSubtotalInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, lang, true); var p = new Paragraph(String.Format("{0} {1}", _localizationService.GetResource("PDFInvoice.Sub-Total", lang.Id), orderSubtotalInclTaxStr), font); p.Alignment = Element.ALIGN_RIGHT; doc.Add(p); } break; } //discount (applied to order subtotal) if (order.OrderSubTotalDiscountExclTax > decimal.Zero) { switch (order.CustomerTaxDisplayType) { case TaxDisplayType.ExcludingTax: { var orderSubTotalDiscountExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderSubTotalDiscountExclTax, order.CurrencyRate); string orderSubTotalDiscountInCustomerCurrencyStr = _priceFormatter.FormatPrice(-orderSubTotalDiscountExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, lang, false); var p = new Paragraph(String.Format("{0} {1}", _localizationService.GetResource("PDFInvoice.Discount", lang.Id), orderSubTotalDiscountInCustomerCurrencyStr), font); p.Alignment = Element.ALIGN_RIGHT; doc.Add(p); } break; case TaxDisplayType.IncludingTax: { var orderSubTotalDiscountInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderSubTotalDiscountInclTax, order.CurrencyRate); string orderSubTotalDiscountInCustomerCurrencyStr = _priceFormatter.FormatPrice(-orderSubTotalDiscountInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, lang, true); var p = new Paragraph(String.Format("{0} {1}", _localizationService.GetResource("PDFInvoice.Discount", lang.Id), orderSubTotalDiscountInCustomerCurrencyStr), font); p.Alignment = Element.ALIGN_RIGHT; doc.Add(p); } break; } } //shipping if (order.ShippingStatus != ShippingStatus.ShippingNotRequired) { switch (order.CustomerTaxDisplayType) { case TaxDisplayType.ExcludingTax: { var orderShippingExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderShippingExclTax, order.CurrencyRate); string orderShippingExclTaxStr = _priceFormatter.FormatShippingPrice(orderShippingExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, lang, false); var p = new Paragraph(String.Format("{0} {1}", _localizationService.GetResource("PDFInvoice.Shipping", lang.Id), orderShippingExclTaxStr), font); p.Alignment = Element.ALIGN_RIGHT; doc.Add(p); } break; case TaxDisplayType.IncludingTax: { var orderShippingInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderShippingInclTax, order.CurrencyRate); string orderShippingInclTaxStr = _priceFormatter.FormatShippingPrice(orderShippingInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, lang, true); var p = new Paragraph(String.Format("{0} {1}", _localizationService.GetResource("PDFInvoice.Shipping", lang.Id), orderShippingInclTaxStr), font); p.Alignment = Element.ALIGN_RIGHT; doc.Add(p); } break; } } //payment fee if (order.PaymentMethodAdditionalFeeExclTax > decimal.Zero) { switch (order.CustomerTaxDisplayType) { case TaxDisplayType.ExcludingTax: { var paymentMethodAdditionalFeeExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.PaymentMethodAdditionalFeeExclTax, order.CurrencyRate); string paymentMethodAdditionalFeeExclTaxStr = _priceFormatter.FormatPaymentMethodAdditionalFee(paymentMethodAdditionalFeeExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, lang, false); var p = new Paragraph(String.Format("{0} {1}", _localizationService.GetResource("PDFInvoice.PaymentMethodAdditionalFee", lang.Id), paymentMethodAdditionalFeeExclTaxStr), font); p.Alignment = Element.ALIGN_RIGHT; doc.Add(p); } break; case TaxDisplayType.IncludingTax: { var paymentMethodAdditionalFeeInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.PaymentMethodAdditionalFeeInclTax, order.CurrencyRate); string paymentMethodAdditionalFeeInclTaxStr = _priceFormatter.FormatPaymentMethodAdditionalFee(paymentMethodAdditionalFeeInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, lang, true); var p = new Paragraph(String.Format("{0} {1}", _localizationService.GetResource("PDFInvoice.PaymentMethodAdditionalFee", lang.Id), paymentMethodAdditionalFeeInclTaxStr), font); p.Alignment = Element.ALIGN_RIGHT; doc.Add(p); } break; } } //tax string taxStr = string.Empty; var taxRates = new SortedDictionary<decimal, decimal>(); bool displayTax = true; bool displayTaxRates = true; if (_taxSettings.HideTaxInOrderSummary && order.CustomerTaxDisplayType == TaxDisplayType.IncludingTax) { displayTax = false; } else { if (order.OrderTax == 0 && _taxSettings.HideZeroTax) { displayTax = false; displayTaxRates = false; } else { taxRates = order.TaxRatesDictionary; displayTaxRates = _taxSettings.DisplayTaxRates && taxRates.Count > 0; displayTax = !displayTaxRates; var orderTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderTax, order.CurrencyRate); taxStr = _priceFormatter.FormatPrice(orderTaxInCustomerCurrency, true, order.CustomerCurrencyCode, false, lang); } } if (displayTax) { var p = new Paragraph(String.Format("{0} {1}", _localizationService.GetResource("PDFInvoice.Tax", lang.Id), taxStr), font); p.Alignment = Element.ALIGN_RIGHT; doc.Add(p); } if (displayTaxRates) { foreach (var item in taxRates) { string taxRate = String.Format(_localizationService.GetResource("PDFInvoice.TaxRate", lang.Id), _priceFormatter.FormatTaxRate(item.Key)); string taxValue = _priceFormatter.FormatPrice(_currencyService.ConvertCurrency(item.Value, order.CurrencyRate), true, order.CustomerCurrencyCode, false, lang); var p = new Paragraph(String.Format("{0} {1}", taxRate, taxValue), font); p.Alignment = Element.ALIGN_RIGHT; doc.Add(p); } } //discount (applied to order total) if (order.OrderDiscount > decimal.Zero) { var orderDiscountInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderDiscount, order.CurrencyRate); string orderDiscountInCustomerCurrencyStr = _priceFormatter.FormatPrice(-orderDiscountInCustomerCurrency, true, order.CustomerCurrencyCode, false, lang); var p = new Paragraph(String.Format("{0} {1}", _localizationService.GetResource("PDFInvoice.Discount", lang.Id), orderDiscountInCustomerCurrencyStr), font); p.Alignment = Element.ALIGN_RIGHT; doc.Add(p); } //gift cards foreach (var gcuh in order.GiftCardUsageHistory) { string gcTitle = string.Format(_localizationService.GetResource("PDFInvoice.GiftCardInfo", lang.Id), gcuh.GiftCard.GiftCardCouponCode); string gcAmountStr = _priceFormatter.FormatPrice(-(_currencyService.ConvertCurrency(gcuh.UsedValue, order.CurrencyRate)), true, order.CustomerCurrencyCode, false, lang); var p = new Paragraph(String.Format("{0} {1}", gcTitle, gcAmountStr), font); p.Alignment = Element.ALIGN_RIGHT; doc.Add(p); } //reward points if (order.RedeemedRewardPointsEntry != null) { string rpTitle = string.Format(_localizationService.GetResource("PDFInvoice.RewardPoints", lang.Id), -order.RedeemedRewardPointsEntry.Points); string rpAmount = _priceFormatter.FormatPrice(-(_currencyService.ConvertCurrency(order.RedeemedRewardPointsEntry.UsedAmount, order.CurrencyRate)), true, order.CustomerCurrencyCode, false, lang); var p = new Paragraph(String.Format("{0} {1}", rpTitle, rpAmount), font); p.Alignment = Element.ALIGN_RIGHT; doc.Add(p); } //order total var orderTotalInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderTotal, order.CurrencyRate); string orderTotalStr = _priceFormatter.FormatPrice(orderTotalInCustomerCurrency, true, order.CustomerCurrencyCode, false, lang); var pTotal = new Paragraph(String.Format("{0} {1}", _localizationService.GetResource("PDFInvoice.OrderTotal", lang.Id), orderTotalStr), titleFont); pTotal.Alignment = Element.ALIGN_RIGHT; doc.Add(pTotal); #endregion #region Order notes if (_pdfSettings.RenderOrderNotes) { var orderNotes = order.OrderNotes .Where(on => on.DisplayToCustomer) .OrderByDescending(on => on.CreatedOnUtc) .ToList(); if (orderNotes.Count > 0) { doc.Add(new Paragraph(_localizationService.GetResource("PDFInvoice.OrderNotes", lang.Id), titleFont)); doc.Add(new Paragraph(" ")); var notesTable = new PdfPTable(2); notesTable.WidthPercentage = 100f; notesTable.SetWidths(new[] { 30, 70 }); //created on cell = new PdfPCell(new Phrase(_localizationService.GetResource("PDFInvoice.OrderNotes.CreatedOn", lang.Id), font)); cell.BackgroundColor = BaseColor.LIGHT_GRAY; cell.HorizontalAlignment = Element.ALIGN_CENTER; notesTable.AddCell(cell); //note cell = new PdfPCell(new Phrase(_localizationService.GetResource("PDFInvoice.OrderNotes.Note", lang.Id), font)); cell.BackgroundColor = BaseColor.LIGHT_GRAY; cell.HorizontalAlignment = Element.ALIGN_CENTER; notesTable.AddCell(cell); foreach (var orderNote in orderNotes) { cell = new PdfPCell(); cell.AddElement(new Paragraph(_dateTimeHelper.ConvertToUserTime(orderNote.CreatedOnUtc, DateTimeKind.Utc).ToString(), font)); cell.HorizontalAlignment = Element.ALIGN_LEFT; notesTable.AddCell(cell); cell = new PdfPCell(); cell.AddElement(new Paragraph(HtmlHelper.ConvertHtmlToPlainText(orderNote.FormatOrderNoteText(), true, true), font)); cell.HorizontalAlignment = Element.ALIGN_LEFT; notesTable.AddCell(cell); } doc.Add(notesTable); } } #endregion ordNum++; if (ordNum < ordCount) { doc.NewPage(); } } doc.Close(); }
/// <summary> /// Build a hyperlink /// </summary> /// <param name="TextToDisplay">Text To Display</param> /// <param name="UrlToLinkTo">Url To Link To</param> /// <returns>Anchor</returns> private Anchor BuildAnchor(string TextToDisplay, string UrlToLinkTo) { //example on how to add this //var Link = new Paragraph(); //Link.SpacingAfter = 5; //Link.Add(new Chunk("View Your Search: ", new iTextSharp.text.Font(Font.FontFamily.HELVETICA, SubHeadingFontSize, Font.BOLD))); //Link.Add(BuildAnchor()); //Doc.Add(Link); //build the anchor Anchor AnchorToRender = new Anchor(TextToDisplay, new iTextSharp.text.Font(Font.FontFamily.HELVETICA, 10, Font.BOLD, new BaseColor(0, 0, 255))); //set the link (the uri) AnchorToRender.Reference = UrlToLinkTo; //return the anchor return AnchorToRender; }
/** * Constructs a RtfAnchor based on a RtfField * * @param doc The RtfDocument this RtfAnchor belongs to * @param anchor The Anchor this RtfAnchor is based on */ public RtfAnchor(RtfDocument doc, Anchor anchor) : base(doc) { this.url = anchor.Reference; this.content = new RtfPhrase(doc, anchor); }
private void ReportBody() { #region Table header _fontStyle = FontFactory.GetFont("Tahoma", 8f, 1); _pdfPCell = new PdfPCell(new Phrase("Creó", _fontStyle)); //_pdfPCell.Colspan = _totalColum; _pdfPCell.HorizontalAlignment = Element.ALIGN_CENTER; _pdfPCell.VerticalAlignment = Element.ALIGN_MIDDLE; //_pdfPCell.Border = 0; _pdfPCell.BackgroundColor = BaseColor.LIGHT_GRAY; //_pdfPCell.ExtraParagraphSpace = 0; _pdfPTable.AddCell(_pdfPCell); _pdfPCell = new PdfPCell(new Phrase("Estado", _fontStyle)); //_pdfPCell.Colspan = _totalColum; _pdfPCell.HorizontalAlignment = Element.ALIGN_CENTER; _pdfPCell.VerticalAlignment = Element.ALIGN_MIDDLE; //_pdfPCell.Border = 0; _pdfPCell.BackgroundColor = BaseColor.LIGHT_GRAY; //_pdfPCell.ExtraParagraphSpace = 0; _pdfPTable.AddCell(_pdfPCell); _pdfPCell = new PdfPCell(new Phrase("Titulo", _fontStyle)); //_pdfPCell.Colspan = _totalColum; _pdfPCell.HorizontalAlignment = Element.ALIGN_CENTER; _pdfPCell.VerticalAlignment = Element.ALIGN_MIDDLE; //_pdfPCell.Border = 0; _pdfPCell.BackgroundColor = BaseColor.LIGHT_GRAY; //_pdfPCell.ExtraParagraphSpace = 0; _pdfPTable.AddCell(_pdfPCell); _pdfPCell = new PdfPCell(new Phrase("Cliente", _fontStyle)); //_pdfPCell.Colspan = _totalColum; _pdfPCell.HorizontalAlignment = Element.ALIGN_CENTER; _pdfPCell.VerticalAlignment = Element.ALIGN_MIDDLE; //_pdfPCell.Border = 0; _pdfPCell.BackgroundColor = BaseColor.LIGHT_GRAY; //_pdfPCell.ExtraParagraphSpace = 0; _pdfPTable.AddCell(_pdfPCell); _pdfPCell = new PdfPCell(new Phrase("Asignado a", _fontStyle)); //_pdfPCell.Colspan = _totalColum; _pdfPCell.HorizontalAlignment = Element.ALIGN_CENTER; _pdfPCell.VerticalAlignment = Element.ALIGN_MIDDLE; //_pdfPCell.Border = 0; _pdfPCell.BackgroundColor = BaseColor.LIGHT_GRAY; //_pdfPCell.ExtraParagraphSpace = 0; _pdfPTable.AddCell(_pdfPCell); _pdfPCell = new PdfPCell(new Phrase("Tiempo", _fontStyle)); //_pdfPCell.Colspan = _totalColum; _pdfPCell.HorizontalAlignment = Element.ALIGN_CENTER; _pdfPCell.VerticalAlignment = Element.ALIGN_MIDDLE; //_pdfPCell.Border = 0; _pdfPCell.BackgroundColor = BaseColor.LIGHT_GRAY; //_pdfPCell.ExtraParagraphSpace = 0; _pdfPTable.AddCell(_pdfPCell); _pdfPTable.CompleteRow(); #endregion #region table body _fontStyle = FontFactory.GetFont("Tahoma", 8f, 0); int Id = 1; foreach (Issue issue in _issues) { _pdfPCell = new PdfPCell(new Phrase(issue.CreadaPorId.ToString(), _fontStyle)); //_pdfPCell.Colspan = _totalColum; _pdfPCell.HorizontalAlignment = Element.ALIGN_CENTER; _pdfPCell.VerticalAlignment = Element.ALIGN_MIDDLE; //_pdfPCell.Border = 0; _pdfPCell.BackgroundColor = BaseColor.WHITE; //_pdfPCell.ExtraParagraphSpace = 0; _pdfPTable.AddCell(_pdfPCell); _pdfPCell = new PdfPCell(new Phrase(issue.FechaCerradaString, _fontStyle)); //_pdfPCell.Colspan = _totalColum; _pdfPCell.HorizontalAlignment = Element.ALIGN_CENTER; _pdfPCell.VerticalAlignment = Element.ALIGN_MIDDLE; //_pdfPCell.Border = 0; _pdfPCell.BackgroundColor = BaseColor.WHITE; //_pdfPCell.ExtraParagraphSpace = 0; _pdfPTable.AddCell(_pdfPCell); Anchor titulo = new iTextSharp.text.Anchor(issue.Titulo); titulo.Font.Size = 7; titulo.Reference = issue.FechaCreadaString; //_pdfPCell.Colspan = _totalColum; titulo.Font.Color = BaseColor.BLUE; _pdfPCell.HorizontalAlignment = Element.ALIGN_CENTER; _pdfPCell.VerticalAlignment = Element.ALIGN_MIDDLE; //_pdfPCell.Border = 0; _pdfPCell.BackgroundColor = BaseColor.WHITE; //_pdfPCell.ExtraParagraphSpace = 0; _pdfPTable.AddCell(titulo); _pdfPCell = new PdfPCell(new Phrase(issue.Clientes.Nombre.ToString(), _fontStyle)); //_pdfPCell.Colspan = _totalColum; _pdfPCell.HorizontalAlignment = Element.ALIGN_CENTER; _pdfPCell.VerticalAlignment = Element.ALIGN_MIDDLE; //_pdfPCell.Border = 0; _pdfPCell.BackgroundColor = BaseColor.WHITE; //_pdfPCell.ExtraParagraphSpace = 0; _pdfPTable.AddCell(_pdfPCell); _pdfPCell = new PdfPCell(new Phrase(issue.TecnicoAsignadoId.ToString(), _fontStyle)); //_pdfPCell.Colspan = _totalColum; _pdfPCell.HorizontalAlignment = Element.ALIGN_CENTER; _pdfPCell.VerticalAlignment = Element.ALIGN_MIDDLE; //_pdfPCell.Border = 0; _pdfPCell.BackgroundColor = BaseColor.WHITE; //_pdfPCell.ExtraParagraphSpace = 0; _pdfPTable.AddCell(_pdfPCell); Anchor tiempo = new iTextSharp.text.Anchor(issue.TiempoDedicado.ToString()); tiempo.Font.Size = 7; tiempo.Reference = issue.FechaCreadaString; //_pdfPCell.Colspan = _totalColum; _pdfPCell.HorizontalAlignment = Element.ALIGN_CENTER; _pdfPCell.VerticalAlignment = Element.ALIGN_MIDDLE; //_pdfPCell.Border = 0; _pdfPCell.BackgroundColor = BaseColor.WHITE; //_pdfPCell.ExtraParagraphSpace = 0; _pdfPTable.AddCell(tiempo); _pdfPTable.CompleteRow(); } #endregion }
public static void Genera(string sourcePath,string content) { sourcePath = HttpContext.Current.Server.MapPath(sourcePath); //定义一个Document,并设置页面大小为A4,竖向 iTextSharp.text.Document doc = new Document(PageSize.A4); try { //写实例 PdfWriter.GetInstance(doc, new FileStream(sourcePath, FileMode.Create)); //打开document doc.Open(); //载入字体 BaseFont baseFont = BaseFont.CreateFont( "C:\\WINDOWS\\FONTS\\SIMHEI.TTF", //黑体 BaseFont.IDENTITY_H, //横向字体 BaseFont.NOT_EMBEDDED); iTextSharp.text.Font font = new iTextSharp.text.Font(baseFont, 9); //写入一个段落, Paragraph doc.Add(new Paragraph("第一段:" + content, font)); doc.Add(new Paragraph("这是第二段 !", font)); #region 图片 //以下代码用来添加图片,此时图片是做为背景加入到pdf文件当中的: Stream inputImageStream = new FileStream(HttpContext.Current.Server.MapPath("~/images/logo.jpg"), FileMode.Open, FileAccess.Read, FileShare.Read); iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(inputImageStream); image.SetAbsolutePosition(0, 0); image.Alignment = iTextSharp.text.Image.UNDERLYING; //这里可以设定图片是做为背景还是做为元素添加到文件中 doc.Add(image); #endregion #region 其他元素 doc.Add(new Paragraph("Hello World")); //另起一行。有几种办法建立一个段落,如: Paragraph p1 = new Paragraph(new Chunk("This is my first paragraph.\n", FontFactory.GetFont(FontFactory.HELVETICA, 12))); Paragraph p2 = new Paragraph(new Phrase("This is my second paragraph.", FontFactory.GetFont(FontFactory.HELVETICA, 12))); Paragraph p3 = new Paragraph("This is my third paragraph.", FontFactory.GetFont(FontFactory.HELVETICA, 12)); //所有有些对象将被添加到段落中: p1.Add("you can add string here\n\t"); p1.Add(new Chunk("you can add chunks \n")); p1.Add(new Phrase("or you can add phrases.\n")); doc.Add(p1); doc.Add(p2); doc.Add(p3); //创建了一个内容为“hello World”、红色、斜体、COURIER字体、尺寸20的一个块: Chunk chunk = new Chunk("创建了一个内容为“hello World”、红色、斜体、COURIER字体、尺寸20的一个块", FontFactory.GetFont(FontFactory.COURIER, 20, iTextSharp.text.Font.COURIER, new iTextSharp.text.Color(255, 0, 0))); doc.Add(chunk); //如果你希望一些块有下划线或删除线,你可以通过改变字体风格简单做到: Chunk chunk1 = new Chunk("This text is underlined", FontFactory.GetFont(FontFactory.HELVETICA, 12, iTextSharp.text.Font.UNDEFINED)); Chunk chunk2 = new Chunk("This font is of type ITALIC | STRIKETHRU", FontFactory.GetFont(FontFactory.HELVETICA, 12, iTextSharp.text.Font.ITALIC | iTextSharp.text.Font.STRIKETHRU)); //改变块的背景 chunk2.SetBackground(new iTextSharp.text.Color(0xFF, 0xFF, 0x00)); //上标/下标 chunk1.SetTextRise(5); doc.Add(chunk1); doc.Add(chunk2); //外部链接示例: Anchor anchor = new Anchor("website", FontFactory.GetFont(FontFactory.HELVETICA, 12, iTextSharp.text.Font.UNDEFINED, new iTextSharp.text.Color(0, 0, 255))); anchor.Reference = "http://itextsharp.sourceforge.net"; anchor.Name = "website"; //内部链接示例: Anchor anchor1 = new Anchor("This is an internal link\n\n"); anchor1.Name = "link1"; Anchor anchor2 = new Anchor("Click here to jump to the internal link\n\f"); anchor2.Reference = "#link1"; doc.Add(anchor); doc.Add(anchor1); doc.Add(anchor2); //排序列表示例: List list = new List(true, 20); list.Add(new ListItem("First line")); list.Add(new ListItem("The second line is longer to see what happens once the end of the line is reached. Will it start on a new line?")); list.Add(new ListItem("Third line")); doc.Add(list); //文本注释: Annotation a = new Annotation("authors", "Maybe its because I wanted to be an author myself that I wrote iText."); doc.Add(a); //包含页码没有任何边框的页脚。 iTextSharp.text.HeaderFooter footer = new iTextSharp.text.HeaderFooter(new Phrase("This is page: "), true); footer.Border = iTextSharp.text.Rectangle.NO_BORDER; doc.Footer = footer; //Chapter对象和Section对象自动构建一个树: iTextSharp.text.Font f1 = new iTextSharp.text.Font(); f1.SetStyle(iTextSharp.text.Font.BOLD); Paragraph cTitle = new Paragraph("This is chapter 1", f1); Chapter chapter = new Chapter(cTitle, 1); Paragraph sTitle = new Paragraph("This is section 1 in chapter 1", f1); Section section = chapter.AddSection(sTitle, 1); doc.Add(chapter); //构建了一个简单的表: Table aTable = new Table(4, 4); aTable.AutoFillEmptyCells = true; aTable.AddCell("2.2", new System.Drawing.Point(2, 2)); aTable.AddCell("3.3", new System.Drawing.Point(3, 3)); aTable.AddCell("2.1", new System.Drawing.Point(2, 1)); aTable.AddCell("1.3", new System.Drawing.Point(1, 3)); doc.Add(aTable); //构建了一个不简单的表: Table table = new Table(3); table.BorderWidth = 1; table.BorderColor = new iTextSharp.text.Color(0, 0, 255); table.Cellpadding = 5; table.Cellspacing = 5; Cell cell = new Cell("header"); cell.Header = true; cell.Colspan = 3; table.AddCell(cell); cell = new Cell("example cell with colspan 1 and rowspan 2"); cell.Rowspan = 2; cell.BorderColor = new iTextSharp.text.Color(255, 0, 0); table.AddCell(cell); table.AddCell("1.1"); table.AddCell("2.1"); table.AddCell("1.2"); table.AddCell("2.2"); table.AddCell("cell test1"); cell = new Cell("big cell"); cell.Rowspan = 2; cell.Colspan = 2; cell.BackgroundColor = new iTextSharp.text.Color(0xC0, 0xC0, 0xC0); table.AddCell(cell); table.AddCell("cell test2"); // 改变了单元格“big cell”的对齐方式: cell.HorizontalAlignment = Element.ALIGN_CENTER; cell.VerticalAlignment = Element.ALIGN_MIDDLE; doc.Add(table); #endregion //关闭document doc.Close(); //打开PDF,看效果 //Process.Start(sourcePath); } catch (DocumentException de) { Console.WriteLine(de.Message); Console.ReadKey(); } catch (IOException io) { Console.WriteLine(io.Message); Console.ReadKey(); } }
public byte[] CreatePdf(IEnumerable<Models.Contact> data) { byte[] result; using (MemoryStream ms = new MemoryStream()) { Document pDoc = new Document(PageSize.A4); PdfWriter writer = PdfWriter.GetInstance(pDoc, ms); pDoc.Open(); iTextSharp.text.Font contentFont = iTextSharp.text.FontFactory.GetFont("Arial", 13, iTextSharp.text.Font.HELVETICA); string dir = Environment.GetEnvironmentVariable("windir"); dir += @"\Fonts\times.ttf"; BaseFont bf = BaseFont.CreateFont(dir, BaseFont.IDENTITY_H, true); iTextSharp.text.Font font = new iTextSharp.text.Font(bf,11); PdfPTable table = new PdfPTable(new float [] {50, 300, 300}); PdfPCell cell = new PdfPCell(new Phrase("Danh sách nhân viên trung tâm dự báo nhân lực TPHCM", font)); cell.Colspan = 3; cell.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right cell.BackgroundColor = BaseColor.LIGHT_GRAY; table.AddCell(cell); table.AddCell("STT"); table.AddCell("Tên"); table.AddCell("Email"); int index = 1; foreach (var item in data) { table.AddCell(index.ToString()); table.AddCell(new Phrase(item.Name, font)); Anchor anchor = new Anchor(item.Email); anchor.Reference = "mailto://" + item.Email; Phrase phase = new Phrase(); phase.Add(anchor); table.AddCell(phase); index++; } pDoc.Add(table); pDoc.Close(); result = ms.GetBuffer(); } return result; }
/// <summary> /// Add a page that includes a bullet list. /// </summary> /// <param name="doc"></param> private void AddPageWithBulletList(iTextSharp.text.Document doc) { // Add a new page to the document doc.NewPage(); // The header at the top of the page is an anchor linked to by the table of contents. iTextSharp.text.Anchor contentsAnchor = new iTextSharp.text.Anchor("RESEARCH\n\n", _largeFont); contentsAnchor.Name = "research"; // Add the header anchor to the page this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_CENTER, _largeFont, contentsAnchor); // Create an unordered bullet list. The 10f argument separates the bullet from the text by 10 points iTextSharp.text.List list = new iTextSharp.text.List(iTextSharp.text.List.UNORDERED, 10f); list.SetListSymbol("\u2022"); // Set the bullet symbol (without this a hypen starts each list item) list.IndentationLeft = 20f; // Indent the list 20 points list.Add(new ListItem("Lift, thrust, drag, and gravity are the four forces that act on a plane.", _standardFont)); list.Add(new ListItem("A plane should be light to help fight against gravity's pull to the ground.", _standardFont)); list.Add(new ListItem("Gravity will have less effect on a plane built from the lightest materials available.", _standardFont)); list.Add(new ListItem("In order to fly well, airplanes must be stable.", _standardFont)); list.Add(new ListItem("A plane that is unstable will either pitch up into a stall, or nose-dive.", _standardFont)); doc.Add(list); // Add the list to the page // Add some white space and another heading this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_CENTER, _largeFont, new Chunk("\n\n\n")); this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_CENTER, _largeFont, new Chunk("HYPOTHESIS\n\n")); // Add some final text to the page this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_LEFT, _standardFont, new Chunk("Given five paper airplanes made out of newspaper, printer paper, construction paper, paper towel, and posterboard, the airplane made out of printer paper will fly the furthest.")); }
/// <summary> /// Add a page that contains embedded hyperlinks to external resources /// </summary> /// <param name="doc"></param> private void AddPageWithExternalLinks(Document doc) { // Generate external links to be embedded in the page iTextSharp.text.Anchor bibliographyAnchor1 = new Anchor("http://teacher.scholastic.com/paperairplane/airplane.htm", _standardFont); bibliographyAnchor1.Reference = "http://teacher.scholastic.com/paperairplane/airplane.htm"; Anchor bibliographyAnchor2 = new Anchor("http://www.eecs.berkeley.edu/Programs/doublex/spring02/paperairplane.html", _standardFont); bibliographyAnchor1.Reference = "http://www.eecs.berkeley.edu/Programs/doublex/spring02/paperairplane.html"; Anchor bibliographyAnchor3 = new Anchor("http://www.exo.net/~pauld/activities/flying/PaperAirplaneScience.html", _standardFont); bibliographyAnchor1.Reference = "http://www.exo.net/~pauld/activities/flying/PaperAirplaneScience.html"; Anchor bibliographyAnchor4 = new Anchor("http://www.littletoyairplanes.com/theoryofflight/02whyplanes.html", _standardFont); bibliographyAnchor4.Reference = "http://www.littletoyairplanes.com/theoryofflight/02whyplanes.html"; // The header at the top of the page is an anchor linked to by the table of contents. iTextSharp.text.Anchor contentsAnchor = new iTextSharp.text.Anchor("RESULTS\n\n", _largeFont); contentsAnchor.Name = "results"; // Add a new page to the document doc.NewPage(); // Add text to the page this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_CENTER, _largeFont, contentsAnchor); this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_LEFT, _standardFont, new Chunk("My hypothesis was incorrect. The paper airplane made out of construction paper flew the furthest.")); this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_CENTER, _largeFont, new Chunk("\n\n\n")); this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_CENTER, _largeFont, new Chunk("BIBLIOGRAPHY\n\n")); // Add the links to the page this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_LEFT, _standardFont, bibliographyAnchor1); this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_LEFT, _standardFont, bibliographyAnchor2); this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_LEFT, _standardFont, bibliographyAnchor3); this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_LEFT, _standardFont, bibliographyAnchor4); }
// тестовая функции для создания файла PDF public static void Test() { var doc = new Document(); const string pdfTicketFileName = "bender.pdf"; var fileStream = new FileStream(DataPathGetter.GetTempDir() + "\\" + pdfTicketFileName, FileMode.Create); try { PdfWriter.GetInstance(doc, fileStream); doc.Open(); //Init fonts //Очень важно указывать шрифт вручную, иначе кирилица не будет отображатся в Pdf документе BaseFont customfont = BaseFont.CreateFont(DataPathGetter.GetFontsDir() + "arial.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); var defaultFont = new Font(customfont, 10, Font.NORMAL, BaseColor.BLACK); var italicFont = new Font(customfont, 10, Font.ITALIC, BaseColor.BLACK); var titleFont = new Font(customfont, 15, Font.NORMAL, BaseColor.BLACK); //Init main table var mainTable = new PdfPTable(2); mainTable.SetWidths(new[] { 2, 4 }); mainTable.DefaultCell.BorderWidth = 2; mainTable.TotalWidth = 500f; mainTable.LockedWidth = true; mainTable.DefaultCell.BorderColor = BaseColor.LIGHT_GRAY; mainTable.DefaultCell.Padding = 5f; Image photo = Image.GetInstance(DataPathGetter.GetImagesDir() + "\\" + "Readme.png"); mainTable.AddCell(photo); var infoTable = new PdfPTable(1); infoTable.DefaultCell.BorderWidth = 0; infoTable.AddCell(new Phrase("Бендер Сгибальщик Родригес\n \n", titleFont)); infoTable.AddCell(new Phrase("Бендер — комический герой (а если совсем точнее, антигерой), " + " сквернослов, алкоголик(алкоголь является топливом, а также нужен для " + " смазки, иначе голова Бендера ржавеет в виде характерной ржавой щетины) " + " и заядлый курильщик сигар, почитатель порнографии для роботов (в виде электрических схем), " + " клептоман, повар (его еда в большинстве случаев по меньшей мере несъедобна, часто опасна " + " для жизни). В критической ситуации зачастую единственный, кто впадает в панику.\n \n", defaultFont)); var anchor = new Anchor("Взято с Википедии", italicFont); anchor.Reference = "http://ru.wikipedia.org/"; infoTable.AddCell(anchor); mainTable.AddCell(infoTable); doc.Add(new Phrase("Визитка Бендера\n", titleFont)); doc.Add(mainTable); } catch (DocumentException dex) { throw (dex); } catch (IOException ioex) { throw (ioex); } finally { doc.Close(); } }
private void WriteSignature(VisaLetter visaLetter, PdfPTable table, Document doc) { string url; Image img; var user = _repository.OfType<vUser>().Queryable.FirstOrDefault(a => a.LoginId == visaLetter.ApprovedBy); Check.Require(user != null, "Approval User is required"); var cell = InitializeCell("Should you need more information, please contact me at ", halignment: Element.ALIGN_LEFT, bottomBorder: false); var anchor = new Anchor(user.Email, _linkFont); anchor.Reference = string.Format("mailto:{0}", user.Email); cell.Phrase.Add(anchor); table.AddCell(cell); doc.Add(table); table = InitializeTable(2); table.SetWidths(new float[]{40,60}); table.AddCell(InitializeCell("", halignment: Element.ALIGN_LEFT, bottomBorder: false, overridePaddingTop: 20)); table.AddCell(InitializeCell("Kind regards.", halignment: Element.ALIGN_LEFT, bottomBorder: false, padding: false, overridePaddingTop: 20)); url = HttpContext.Current.Server.MapPath(string.Format("~/Images/vl_{0}_signature.png", user.LoginId.ToLower().Trim())); if (File.Exists(url)) { img = Image.GetInstance(new Uri(url)); img.ScaleToFit(140f, 40f); } else { throw new Exception("Image not found " + url); } var imageCell = new PdfPCell(img); imageCell.BorderWidthLeft = 0; imageCell.BorderWidthRight = 0; imageCell.BorderWidthTop = 0; imageCell.BorderWidthBottom = 0; imageCell.HorizontalAlignment = Element.ALIGN_LEFT; table.AddCell(InitializeCell("", halignment: Element.ALIGN_LEFT, bottomBorder: false, padding: false)); table.AddCell(imageCell); // (InitializeCell(img, halignment: Element.ALIGN_RIGHT, bottomBorder: false)); table.AddCell(InitializeCell("", halignment: Element.ALIGN_LEFT, bottomBorder: false, padding: false)); table.AddCell(InitializeCell(user.FullName, halignment: Element.ALIGN_LEFT, bottomBorder: false, padding: false)); table.AddCell(InitializeCell("", halignment: Element.ALIGN_LEFT, bottomBorder: false, padding: false, overridePaddingTop: 0)); table.AddCell(InitializeCell("Commencement Coordinator", halignment: Element.ALIGN_LEFT, bottomBorder: false, padding: false, overridePaddingTop: 0)); table.AddCell(InitializeCell("", halignment: Element.ALIGN_LEFT, bottomBorder: false, padding: false, overridePaddingTop: 0)); table.AddCell(InitializeCell("UC Davis", halignment: Element.ALIGN_LEFT, bottomBorder: false, padding: false, overridePaddingTop: 0)); table.AddCell(InitializeCell("", halignment: Element.ALIGN_LEFT, bottomBorder: false, padding: false, overridePaddingTop: 0)); table.AddCell(InitializeCell(user.Phone, halignment: Element.ALIGN_LEFT, bottomBorder: false, padding: false, overridePaddingTop: 0)); doc.Add(table); }
/// <summary> /// Add a blank page to the document. /// </summary> /// <param name="doc"></param> private void AddPageWithInternalLinks(iTextSharp.text.Document doc) { // Generate links to be embedded in the page Anchor researchAnchor = new Anchor("Research & Hypothesis\n\n", _standardFont); researchAnchor.Reference = "#research"; // this link references a named anchor within the document Anchor graphAnchor = new Anchor("Graph\n\n", _standardFont); graphAnchor.Reference = "#graph"; Anchor resultsAnchor = new Anchor("Results & Bibliography", _standardFont); resultsAnchor.Reference = "#results"; // Add a new page to the document doc.NewPage(); // Add heading text to the page this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_CENTER, _largeFont, new iTextSharp.text.Chunk("TABLE OF CONTENTS\n\n\n\n\n")); // Add the links to the page this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_CENTER, _standardFont, researchAnchor); this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_CENTER, _standardFont, graphAnchor); this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_CENTER, _standardFont, resultsAnchor); }
private PdfPCell GenerateProviderIndexLink(PrintableProviderDto provider) { Anchor click = new Anchor(provider.Name, fonts["h4_link"]); click.Reference = "#" + provider.Name; Paragraph p1 = new Paragraph(); p1.Add(click); var cell = new PdfPCell(p1); cell.Border = 0; cell.PaddingBottom += 5; return cell; }
private void GenerateSpecialitySection(Document doc, IGrouping<string, PrintableProviderDto> grouping) { Anchor specialityHeader = new Anchor(grouping.Key, fonts["h1"]); specialityHeader.Name = grouping.Key; Paragraph specialityHeaderParagraph = new Paragraph(); specialityHeaderParagraph.SpacingAfter += 10; specialityHeaderParagraph.Add(specialityHeader); doc.Add(specialityHeaderParagraph); var specialityProvidersTable = new PdfPTable(2); specialityProvidersTable.WidthPercentage = 100; var cellAddCount = 0; foreach (var provider in grouping) { PdfPCell cell = GenerateProviderInformationWidget(provider); specialityProvidersTable.AddCell(cell); cellAddCount++; } /* iTextSharp eats incomplete rows. couldn't find a workaround in the api */ if (cellAddCount % 2 != 0) { specialityProvidersTable.AddCell(new PdfPCell() { Border = 0 }); } doc.Add(specialityProvidersTable); }
static void MainExample() { var doc = new Document (); PdfWriter.GetInstance(doc, new FileStream(@"Document.pdf", FileMode.Create)); doc.Open(); //Normal text string text = "Normal Text. "; Paragraph par = new Paragraph (); par.FirstLineIndent = firstLineIndent; par.SpacingAfter = spacingAfter; for (int i = 0; i < 15; i++) { par.Add (text); } doc.Add (par); //Bold text text = "Bold Text. "; BaseFont baseFont = BaseFont.CreateFont (BaseFont.HELVETICA_BOLD, BaseFont.CP1257, false); iTextSharp.text.Font font = new iTextSharp.text.Font (baseFont, textFontSize); Chunk chunk = new Chunk (text, font); par = new Paragraph (); par.FirstLineIndent = firstLineIndent; par.SpacingAfter = spacingAfter; for (int i = 0; i < 15; i++) { par.Add (chunk); } doc.Add (par); //Italic Text text = "Italic Text. "; baseFont = BaseFont.CreateFont (BaseFont.TIMES_ITALIC, BaseFont.CP1257, false); font = new iTextSharp.text.Font (baseFont, textFontSize); chunk = new Chunk (text, font); par = new Paragraph (); par.FirstLineIndent = firstLineIndent; par.SpacingAfter = spacingAfter; for (int i = 0; i < 15; i++) { par.Add (chunk); } doc.Add (par); //Underline text text = "Underline Text. "; baseFont = BaseFont.CreateFont (BaseFont.HELVETICA, BaseFont.CP1257, false); font = new iTextSharp.text.Font (baseFont, textFontSize, iTextSharp.text.Font.UNDERLINE); chunk = new Chunk (text, font); par = new Paragraph (); par.FirstLineIndent = firstLineIndent; par.SpacingAfter = spacingAfter; for (int i = 0; i < 15; i++) { par.Add (chunk); } doc.Add (par); //Strikethrough text text = "Strikethrough Text. "; baseFont = BaseFont.CreateFont (BaseFont.HELVETICA, BaseFont.CP1257, false); font = new iTextSharp.text.Font (baseFont, textFontSize, iTextSharp.text.Font.STRIKETHRU); chunk = new Chunk (text, font); par = new Paragraph (); par.FirstLineIndent = firstLineIndent; par.SpacingAfter = spacingAfter; for (int i = 0; i < 15; i++) { par.Add (chunk); } doc.Add (par); //Hyperlink text text = "Hyperlink Text. "; baseFont = BaseFont.CreateFont (BaseFont.HELVETICA, BaseFont.CP1257, false); //font = new iTextSharp.text.Font (baseFont, textFontSize, iTextSharp.text.Font.UNDERLINE); font = FontFactory.GetFont("Arial", textFontSize, iTextSharp.text.Font.UNDERLINE, new iTextSharp.text.BaseColor(0, 0, 255)); Anchor link = new Anchor (text, font); link.Reference = "http://google.com"; par = new Paragraph (); par.FirstLineIndent = firstLineIndent; par.SpacingAfter = spacingAfter; for (int i = 0; i < 15; i++) { par.Add (link); } doc.Add (par); //Russian Text //Warning text = "Русский Текст. "; font = FontFactory.GetFont(GetFontByName("Arial"), BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); chunk = new Chunk (text, font); par = new Paragraph (); par.FirstLineIndent = firstLineIndent; par.SpacingAfter = spacingAfter; for (int i = 0; i < 15; i++) { par.Add (chunk); } doc.Add (par); //Bold & Italic & Underline & Hyperlink Text text = "Bold & Italic & Underline & Hyperlink Text. "; font = FontFactory.GetFont( GetFontByName("Times New Roman"), textFontSize, iTextSharp.text.Font.UNDERLINE | iTextSharp.text.Font.BOLD | iTextSharp.text.Font.ITALIC, new iTextSharp.text.BaseColor(0, 0, 255) ); link = new Anchor (text, font); link.Reference = "http://google.com"; par = new Paragraph (); par.FirstLineIndent = firstLineIndent; par.SpacingAfter = spacingAfter; for (int i = 0; i < 7; i++) { par.Add (link); } doc.Add (par); //Before (After) line break text="Before line break. "; par = new Paragraph (); par.FirstLineIndent = firstLineIndent; par.SpacingAfter = spacingAfter; for (int i = 0; i < 13; i++) { par.Add (text); } par.Add (Chunk.NEWLINE); par.Add ("After line break."); doc.Add (par); //Span text text="Span text. "; par = new Paragraph (); par.FirstLineIndent = firstLineIndent; par.SpacingAfter = spacingAfter; Font font1 = FontFactory.GetFont (GetFontByName ("Arial")); Font font2 = FontFactory.GetFont (GetFontByName ("Arial"), textFontSize, Font.BOLD); Font font3 = FontFactory.GetFont (GetFontByName ("Arial"), textFontSize, Font.ITALIC); Font font4 = FontFactory.GetFont (GetFontByName ("Arial"), textFontSize, Font.UNDERLINE); Font font5 = FontFactory.GetFont (GetFontByName ("Arial"), textFontSize, Font.UNDERLINE, new BaseColor(0, 0, 255)); link = new Anchor (text, font5); link.Reference = "http://google.com"; par.Add (new Chunk (text, font1)); par.Add (new Chunk (text, font2)); par.Add (new Chunk (text, font3)); par.Add (new Chunk (text, font4)); par.Add (" "); par.Add (link); doc.Add (par); //Image par = new Paragraph (); par.SpacingAfter = spacingAfter; Image jpg1 = Image.GetInstance ("images.jpg"); Image jpg2 = Image.GetInstance ("images.jpg"); Image jpg3 = Image.GetInstance ("images.jpg"); Image jpg4 = Image.GetInstance ("images.jpg"); jpg1.ScalePercent (scalePercent); jpg1.RotationDegrees = 0; jpg2.ScalePercent (scalePercent); jpg2.RotationDegrees = -90; jpg3.ScalePercent (scalePercent); jpg3.RotationDegrees = -180; jpg4.ScalePercent (scalePercent); jpg4.RotationDegrees = -270; par.Add (new Chunk (jpg1, 0, 0, true)); par.Add (new Chunk (jpg2, 0, 0, true)); par.Add (new Chunk (jpg3, 0, 0, true)); par.Add (new Chunk (jpg4, 0, 0, true)); doc.Add (par); //Page break doc.Add (new Paragraph("Before page break.")); doc.Add (Chunk.NEXTPAGE); doc.Add (new Paragraph("After page break.")); //List with 'None' marker style: par = new Paragraph(); par.SpacingBefore = spacingAfter; par.Add ("List with 'None' marker style:"); doc.Add(par); List list = new List (List.UNORDERED, symbolIndent); list.SetListSymbol (""); list.IndentationLeft = indentationLeft; list.Add ("Item1"); list.Add ("Item2"); list.Add ("Item3"); doc.Add (list); //List with 'Disc' marker style: par = new Paragraph(); par.SpacingBefore = spacingAfter; par.Add ("List with 'Disc' marker style:"); doc.Add(par); list = new List (List.UNORDERED, symbolIndent); list.SetListSymbol (symbolDisk); list.IndentationLeft = indentationLeft; list.Add ("Item1"); list.Add ("Item2"); list.Add ("Item3"); doc.Add (list); //List with 'Box' marker style: //Not working... par = new Paragraph(); par.SpacingBefore = spacingAfter; par.Add ("List with 'Box' marker style:"); doc.Add(par); list = new List (List.UNORDERED, symbolIndent); list.SetListSymbol (symbolBox); list.IndentationLeft = indentationLeft; list.Add ("Item1"); list.Add ("Item2"); list.Add ("Item3"); doc.Add (list); //List with 'LowerRoman' marker style: //Warning par = new Paragraph(); par.SpacingBefore = spacingAfter; par.Add ("List with 'LowerRoman' marker style:"); doc.Add(par); RomanList romanList = new RomanList (true, symbolIndent); //true == Roman Lower romanList.IndentationLeft = indentationLeft; romanList.Add ("Item1"); romanList.Add ("Item2"); romanList.Add ("Item3"); doc.Add (romanList); //List with 'UpperRoman' marker style: //Warning par = new Paragraph(); par.SpacingBefore = spacingAfter; par.Add ("List with 'UpperRoman' marker style:"); doc.Add(par); romanList = new RomanList (false, symbolIndent); //true == Roman Lower romanList.IndentationLeft = indentationLeft; romanList.Add ("Item1"); romanList.Add ("Item2"); romanList.Add ("Item3"); romanList.Add ("Item4"); romanList.Add ("Item5"); romanList.Add ("Item6"); doc.Add (romanList); //Table //http://www.mikesdotnetting.com/Article/86/itextsharp-introducing-tables par = new Paragraph(); par.SpacingBefore = spacingAfter; par.Add ("Table:"); doc.Add(par); PdfPTable table = new PdfPTable (5); //5 Columns table.TotalWidth = doc.PageSize.Width - doc.LeftMargin - doc.RightMargin; table.LockedWidth = true; float columt1Width = 50f; float columt2Width = 80f; float delta = (table.TotalWidth - columt1Width - columt2Width) / 3; float[] widths = { columt1Width, columt2Width, delta, delta, delta }; table.SetWidths (widths); table.SpacingBefore = spacingAfter; PdfPCell cell = new PdfPCell(new Phrase("Colspan = Rowspan = 2")); cell.Colspan = 2; cell.Rowspan = 2; table.AddCell (cell); cell = new PdfPCell (new Phrase("Rowspan = 4")); cell.Rowspan = 4; table.AddCell (cell); cell = new PdfPCell (new Phrase("Colspan = 2")); cell.Colspan = 2; table.AddCell (cell); for (int i = 0; i < 20; i++) table.AddCell ("Text " + (i + 1).ToString ()); doc.Add (table); //Before (After) line //Warning par = new Paragraph("Before line"); par.SpacingBefore = spacingAfter; doc.Add (par); cell = new PdfPCell(); cell.BorderWidth = 0f; cell.BorderWidthBottom = 0.5f; table = new PdfPTable (1); table.AddCell (cell); table.TotalWidth = doc.PageSize.Width - doc.LeftMargin - doc.RightMargin; table.LockedWidth = true; table.SpacingBefore = spacingAfter; doc.Add (table); par = new Paragraph("After line"); doc.Add (par); //Fonts (Arial) par = new Paragraph(); par.SpacingBefore = spacingAfter; text="Arial 10pt. "; font = FontFactory.GetFont (GetFontByName ("Arial"), 10); par.Add (new Chunk (text, font)); text="Arial 15pt. "; font = FontFactory.GetFont (GetFontByName ("Arial"), 15); par.Add (new Chunk (text, font)); text="Arial 20pt. "; font = FontFactory.GetFont (GetFontByName ("Arial"), 20); par.Add (new Chunk (text, font)); doc.Add (par); //Fonts (Tahoma) par = new Paragraph(); par.SpacingBefore = spacingAfter; text="Tahoma 10pt. "; font = FontFactory.GetFont (GetFontByName ("Tahoma"), 10); par.Add (new Chunk (text, font)); text="Tahoma 15pt. "; font = FontFactory.GetFont (GetFontByName ("Tahoma"), 15); par.Add (new Chunk (text, font)); text="Tahoma 20pt. "; font = FontFactory.GetFont (GetFontByName ("Tahoma"), 20); par.Add (new Chunk (text, font)); doc.Add (par); //Fonts (Courier New) par = new Paragraph(); par.SpacingBefore = spacingAfter; text="Courier New 10pt. "; font = FontFactory.GetFont (GetFontByName ("Courier New"), 10); par.Add (new Chunk (text, font)); text="Courier New 15pt. "; font = FontFactory.GetFont (GetFontByName ("Courier New"), 15); par.Add (new Chunk (text, font)); text="Courier New 20pt. "; font = FontFactory.GetFont (FontFactory.COURIER, 20); //GetFontByName ("Courier New") == FontFactory.COURIER par.Add (new Chunk (text, font)); doc.Add (par); //Normal, Italic, Oblique //Not Finished par = new Paragraph(); par.SpacingBefore = spacingAfter; par.SpacingAfter = spacingAfter; text = "Normal. "; font = FontFactory.GetFont (GetFontByName ("Arial"), textFontSize, Font.NORMAL); par.Add (new Chunk (text, font)); text = "Italic. "; font = FontFactory.GetFont (GetFontByName ("Arial"), textFontSize, Font.ITALIC); par.Add (new Chunk (text, font)); text = "Oblique. (Not Working)"; font = FontFactory.GetFont (GetFontByName ("Arial"), textFontSize); par.Add (new Chunk (text, font)); doc.Add (par); //Normal. Subscript. Superscript. //H 2 O doc.Add(new Paragraph("Normal. Subscript. Superscript.")); par = new Paragraph (); par.SpacingBefore = spacingAfter; chunk = new Chunk ("H", FontFactory.GetFont (GetFontByName ("Arial"))); par.Add (chunk); chunk = new Chunk ("2", FontFactory.GetFont (GetFontByName ("Arial"))); chunk.SetTextRise (-5f); par.Add (chunk); chunk = new Chunk ("O", FontFactory.GetFont (GetFontByName ("Arial"))); par.Add (chunk); doc.Add (par); //C 2 H 5 OH par = new Paragraph (); par.SpacingBefore = spacingAfter; chunk = new Chunk ("C", FontFactory.GetFont (GetFontByName ("Arial"))); par.Add (chunk); chunk = new Chunk ("2", FontFactory.GetFont (GetFontByName ("Arial"))); chunk.SetTextRise (-5f); par.Add (chunk); chunk = new Chunk ("H", FontFactory.GetFont (GetFontByName ("Arial"))); par.Add (chunk); chunk = new Chunk ("5", FontFactory.GetFont (GetFontByName ("Arial"))); chunk.SetTextRise (-5f); par.Add (chunk); chunk = new Chunk ("OH", FontFactory.GetFont (GetFontByName ("Arial"))); par.Add (chunk); doc.Add (par); //a^2+b^2=c^2 par = new Paragraph (); par.SpacingBefore = spacingAfter; chunk = new Chunk ("a", FontFactory.GetFont (GetFontByName ("Arial"))); par.Add (chunk); chunk = new Chunk ("2", FontFactory.GetFont (GetFontByName ("Arial"))); chunk.SetTextRise (5f); par.Add (chunk); chunk = new Chunk (" + b", FontFactory.GetFont (GetFontByName ("Arial"))); par.Add (chunk); chunk = new Chunk ("2", FontFactory.GetFont (GetFontByName ("Arial"))); chunk.SetTextRise (5f); par.Add (chunk); chunk = new Chunk (" = c", FontFactory.GetFont (GetFontByName ("Arial"))); par.Add (chunk); chunk = new Chunk ("2", FontFactory.GetFont (GetFontByName ("Arial"))); chunk.SetTextRise (5f); par.Add (chunk); doc.Add (par); //Foreground and Background (text color and cell backgroudcolor) (table) //Warning table=new PdfPTable(3); chunk = new Chunk ("Green foreground", FontFactory.GetFont (GetFontByName ("Arial"), textFontSize, new BaseColor (0, 200, 0))); cell = new PdfPCell (new Phrase (chunk)); cell.BorderWidth = 0f; table.AddCell (cell); cell = new PdfPCell (new Phrase ("Red Background")); cell.BackgroundColor = new BaseColor (255, 0, 0); cell.BorderWidth = 0f; table.AddCell (cell); chunk = new Chunk ("Green foreground & Red background", FontFactory.GetFont (GetFontByName ("Arial"), textFontSize, new BaseColor (0, 200, 0))); cell = new PdfPCell (new Phrase (chunk)); cell.BackgroundColor = new BaseColor (255, 0, 0); cell.BorderWidth = 0f; table.AddCell (cell); table.TotalWidth = doc.PageSize.Width - doc.LeftMargin - doc.RightMargin; table.LockedWidth = true; table.SpacingBefore = spacingAfter; doc.Add (table); //Left text par = new Paragraph(); par.SpacingBefore = spacingAfter; par.FirstLineIndent = firstLineIndent; for (int i = 0; i < 15; i++) par.Add ("Left text. "); par.Alignment = Element.ALIGN_LEFT; doc.Add (par); //Rigth text par = new Paragraph(); par.SpacingBefore = spacingAfter; par.FirstLineIndent = firstLineIndent; for (int i = 0; i < 15; i++) par.Add ("Rigth text. "); par.Alignment = Element.ALIGN_RIGHT; doc.Add (par); //Center text par = new Paragraph(); par.SpacingBefore = spacingAfter; for (int i = 0; i < 15; i++) par.Add ("Center text. "); par.Alignment = Element.ALIGN_CENTER; doc.Add (par); //Justify text par = new Paragraph(); par.SpacingBefore = spacingAfter; par.FirstLineIndent = firstLineIndent; for (int i = 0; i < 15; i++) par.Add ("Justify text. "); par.Alignment = Element.ALIGN_JUSTIFIED_ALL; doc.Add (par); //Boxes //Warning PdfPTable box1 = new PdfPTable (1); PdfPTable box2 = new PdfPTable (1); PdfPCell addCellInBox2 = new PdfPCell (new Phrase ("Section(table) & !Margin & Padding & Border & Background")); addCellInBox2.Padding = 20f; addCellInBox2.BackgroundColor = new BaseColor (255, 255, 0); addCellInBox2.BorderWidth = 4f; addCellInBox2.BorderColor = new BaseColor (0, 0, 255); box2.AddCell (addCellInBox2); PdfPCell addCellinBox1 = new PdfPCell (box2); addCellinBox1.Padding = 20f; addCellinBox1.BackgroundColor = new BaseColor (0, 200, 0); addCellinBox1.BorderWidth = 4f; addCellinBox1.BorderColor = new BaseColor (255, 0, 0); box1.AddCell (addCellinBox1); box1.SpacingBefore = spacingAfter; box1.TotalWidth = doc.PageSize.Width - doc.LeftMargin - doc.RightMargin; box1.LockedWidth = true; doc.Add (box1); doc.Close (); System.Diagnostics.Process.Start ("Document.pdf"); }
private void GenerateSpecialityTableOfContents(Document doc, IEnumerable<IGrouping<string, PrintableProviderDto>> providersBySpeciality) { var specialitiesHeader = new Paragraph("Physician Specialities", fonts["h1"]); specialitiesHeader.SpacingAfter += 10; doc.Add(specialitiesHeader); var table = new PdfPTable(1); table.WidthPercentage = 100; for (var i = 0; i < providersBySpeciality.Count(); i++) { var specialityName = providersBySpeciality.ElementAt(i).Key; Anchor click = new Anchor(specialityName, fonts["h2_link"]); click.Reference = "#" + specialityName; Paragraph p1 = new Paragraph(); p1.Add(click); var cell = new PdfPCell(p1); cell.BackgroundColor = i % 2 == 0 ? colors["row"] : colors["altrow"]; cell.Border = 0; cell.PaddingBottom += 5; table.AddCell(cell); } doc.Add(table); }
/// <summary> /// Print orders to PDF /// </summary> /// <param name="stream">Stream</param> /// <param name="orders">Orders</param> /// <param name="languageId">Language identifier; 0 to use a language used when placing an order</param> public virtual void PrintOrdersToPdf(Stream stream, IList<Order> orders, int languageId = 0) { if (stream == null) throw new ArgumentNullException("stream"); if (orders == null) throw new ArgumentNullException("orders"); var pageSize = PageSize.A4; if (_pdfSettings.LetterPageSizeEnabled) { pageSize = PageSize.LETTER; } var doc = new Document(pageSize); var pdfWriter = PdfWriter.GetInstance(doc, stream); doc.Open(); //fonts var titleFont = GetFont(); titleFont.SetStyle(Font.BOLD); titleFont.Color = BaseColor.BLACK; var font = GetFont(); var attributesFont = GetFont(); attributesFont.SetStyle(Font.ITALIC); int ordCount = orders.Count; int ordNum = 0; foreach (var order in orders) { //by default _pdfSettings contains settings for the current active store //and we need PdfSettings for the store which was used to place an order //so let's load it based on a store of the current order var pdfSettingsByStore = _settingContext.LoadSetting<PdfSettings>(order.StoreId); var lang = _languageService.GetLanguageById(languageId == 0 ? order.CustomerLanguageId : languageId); if (lang == null || !lang.Published) lang = _workContext.WorkingLanguage; #region Header //logo var logoPicture = _pictureService.GetPictureById(pdfSettingsByStore.LogoPictureId); var logoExists = logoPicture != null; //header var headerTable = new PdfPTable(logoExists ? 2 : 1); headerTable.RunDirection = GetDirection(lang); headerTable.DefaultCell.Border = Rectangle.NO_BORDER; //store info var store = _storeService.GetStoreById(order.StoreId) ?? _storeContext.CurrentStore; var anchor = new Anchor(store.Url.Trim(new [] { '/' }), font); anchor.Reference = store.Url; var cellHeader = new PdfPCell(new Phrase(String.Format(_localizationService.GetResource("PDFInvoice.Order#", lang.Id), order.Id), titleFont)); cellHeader.Phrase.Add(new Phrase(Environment.NewLine)); cellHeader.Phrase.Add(new Phrase(anchor)); cellHeader.Phrase.Add(new Phrase(Environment.NewLine)); cellHeader.Phrase.Add(new Phrase(String.Format(_localizationService.GetResource("PDFInvoice.OrderDate", lang.Id), _dateTimeHelper.ConvertToUserTime(order.CreatedOnUtc, DateTimeKind.Utc).ToString("D", new CultureInfo(lang.LanguageCulture))), font)); cellHeader.Phrase.Add(new Phrase(Environment.NewLine)); cellHeader.Phrase.Add(new Phrase(Environment.NewLine)); cellHeader.HorizontalAlignment = Element.ALIGN_LEFT; cellHeader.Border = Rectangle.NO_BORDER; headerTable.AddCell(cellHeader); if (logoExists) if (lang.Rtl) headerTable.SetWidths(new[] { 0.2f, 0.8f }); else headerTable.SetWidths(new[] { 0.8f, 0.2f }); headerTable.WidthPercentage = 100f; //logo if (logoExists) { var logoFilePath = _pictureService.GetThumbLocalPath(logoPicture, 0, false); var logo = Image.GetInstance(logoFilePath); logo.Alignment = GetAlignment(lang, true); logo.ScaleToFit(65f, 65f); var cellLogo = new PdfPCell(); cellLogo.Border = Rectangle.NO_BORDER; cellLogo.AddElement(logo); headerTable.AddCell(cellLogo); } doc.Add(headerTable); #endregion #region Addresses var addressTable = new PdfPTable(2); addressTable.RunDirection = GetDirection(lang); addressTable.DefaultCell.Border = Rectangle.NO_BORDER; addressTable.WidthPercentage = 100f; addressTable.SetWidths(new[] { 50, 50 }); //billing info var billingAddress = new PdfPTable(1); billingAddress.DefaultCell.Border = Rectangle.NO_BORDER; billingAddress.RunDirection = GetDirection(lang); billingAddress.AddCell(new Paragraph(_localizationService.GetResource("PDFInvoice.BillingInformation", lang.Id), titleFont)); if (_addressSettings.CompanyEnabled && !String.IsNullOrEmpty(order.BillingAddress.Company)) billingAddress.AddCell(new Paragraph(" " + String.Format(_localizationService.GetResource("PDFInvoice.Company", lang.Id), order.BillingAddress.Company), font)); billingAddress.AddCell(new Paragraph(" " + String.Format(_localizationService.GetResource("PDFInvoice.Name", lang.Id), order.BillingAddress.FirstName + " " + order.BillingAddress.LastName), font)); if (_addressSettings.PhoneEnabled) billingAddress.AddCell(new Paragraph(" " + String.Format(_localizationService.GetResource("PDFInvoice.Phone", lang.Id), order.BillingAddress.PhoneNumber), font)); if (_addressSettings.FaxEnabled && !String.IsNullOrEmpty(order.BillingAddress.FaxNumber)) billingAddress.AddCell(new Paragraph(" " + String.Format(_localizationService.GetResource("PDFInvoice.Fax", lang.Id), order.BillingAddress.FaxNumber), font)); if (_addressSettings.StreetAddressEnabled) billingAddress.AddCell(new Paragraph(" " + String.Format(_localizationService.GetResource("PDFInvoice.Address", lang.Id), order.BillingAddress.Address1), font)); if (_addressSettings.StreetAddress2Enabled && !String.IsNullOrEmpty(order.BillingAddress.Address2)) billingAddress.AddCell(new Paragraph(" " + String.Format(_localizationService.GetResource("PDFInvoice.Address2", lang.Id), order.BillingAddress.Address2), font)); if (_addressSettings.CityEnabled || _addressSettings.StateProvinceEnabled || _addressSettings.ZipPostalCodeEnabled) billingAddress.AddCell(new Paragraph(" " + String.Format("{0}, {1} {2}", order.BillingAddress.City, order.BillingAddress.StateProvince != null ? order.BillingAddress.StateProvince.GetLocalized(x => x.Name, lang.Id) : "", order.BillingAddress.ZipPostalCode), font)); if (_addressSettings.CountryEnabled && order.BillingAddress.Country != null) billingAddress.AddCell(new Paragraph(" " + String.Format("{0}", order.BillingAddress.Country != null ? order.BillingAddress.Country.GetLocalized(x => x.Name, lang.Id) : ""), font)); //VAT number if (!String.IsNullOrEmpty(order.VatNumber)) billingAddress.AddCell(new Paragraph(" " + String.Format(_localizationService.GetResource("PDFInvoice.VATNumber", lang.Id), order.VatNumber), font)); //custom attributes var customBillingAddressAttributes = _addressAttributeFormatter.FormatAttributes( order.BillingAddress.CustomAttributes); if (!String.IsNullOrEmpty(customBillingAddressAttributes)) { //TODO: we should add padding to each line (in case if we have sevaral custom address attributes) billingAddress.AddCell(new Paragraph(" " + HtmlHelper.ConvertHtmlToPlainText(customBillingAddressAttributes, true, true), font)); } //payment method var paymentMethod = _paymentService.LoadPaymentMethodBySystemName(order.PaymentMethodSystemName); string paymentMethodStr = paymentMethod != null ? paymentMethod.GetLocalizedFriendlyName(_localizationService, lang.Id) : order.PaymentMethodSystemName; if (!String.IsNullOrEmpty(paymentMethodStr)) { billingAddress.AddCell(new Paragraph(" ")); billingAddress.AddCell(new Paragraph(" " + String.Format(_localizationService.GetResource("PDFInvoice.PaymentMethod", lang.Id), paymentMethodStr), font)); billingAddress.AddCell(new Paragraph()); } //custom values var customValues = order.DeserializeCustomValues(); if (customValues != null) { foreach (var item in customValues) { billingAddress.AddCell(new Paragraph(" ")); billingAddress.AddCell(new Paragraph(" " + item.Key + ": " + item.Value, font)); billingAddress.AddCell(new Paragraph()); } } addressTable.AddCell(billingAddress); //shipping info var shippingAddress = new PdfPTable(1); shippingAddress.DefaultCell.Border = Rectangle.NO_BORDER; shippingAddress.RunDirection = GetDirection(lang); if (order.ShippingStatus != ShippingStatus.ShippingNotRequired) { //cell = new PdfPCell(); //cell.Border = Rectangle.NO_BORDER; if (!order.PickUpInStore) { if (order.ShippingAddress == null) throw new NopException(string.Format("Shipping is required, but address is not available. Order ID = {0}", order.Id)); shippingAddress.AddCell(new Paragraph(_localizationService.GetResource("PDFInvoice.ShippingInformation", lang.Id), titleFont)); if (!String.IsNullOrEmpty(order.ShippingAddress.Company)) shippingAddress.AddCell(new Paragraph(" " + String.Format(_localizationService.GetResource("PDFInvoice.Company", lang.Id), order.ShippingAddress.Company), font)); shippingAddress.AddCell(new Paragraph(" " + String.Format(_localizationService.GetResource("PDFInvoice.Name", lang.Id), order.ShippingAddress.FirstName + " " + order.ShippingAddress.LastName), font)); if (_addressSettings.PhoneEnabled) shippingAddress.AddCell(new Paragraph(" " + String.Format(_localizationService.GetResource("PDFInvoice.Phone", lang.Id), order.ShippingAddress.PhoneNumber), font)); if (_addressSettings.FaxEnabled && !String.IsNullOrEmpty(order.ShippingAddress.FaxNumber)) shippingAddress.AddCell(new Paragraph(" " + String.Format(_localizationService.GetResource("PDFInvoice.Fax", lang.Id), order.ShippingAddress.FaxNumber), font)); if (_addressSettings.StreetAddressEnabled) shippingAddress.AddCell(new Paragraph(" " + String.Format(_localizationService.GetResource("PDFInvoice.Address", lang.Id), order.ShippingAddress.Address1), font)); if (_addressSettings.StreetAddress2Enabled && !String.IsNullOrEmpty(order.ShippingAddress.Address2)) shippingAddress.AddCell(new Paragraph(" " + String.Format(_localizationService.GetResource("PDFInvoice.Address2", lang.Id), order.ShippingAddress.Address2), font)); if (_addressSettings.CityEnabled || _addressSettings.StateProvinceEnabled || _addressSettings.ZipPostalCodeEnabled) shippingAddress.AddCell(new Paragraph(" " + String.Format("{0}, {1} {2}", order.ShippingAddress.City, order.ShippingAddress.StateProvince != null ? order.ShippingAddress.StateProvince.GetLocalized(x => x.Name, lang.Id) : "", order.ShippingAddress.ZipPostalCode), font)); if (_addressSettings.CountryEnabled && order.ShippingAddress.Country != null) shippingAddress.AddCell(new Paragraph(" " + String.Format("{0}", order.ShippingAddress.Country != null ? order.ShippingAddress.Country.GetLocalized(x => x.Name, lang.Id) : ""), font)); //custom attributes var customShippingAddressAttributes = _addressAttributeFormatter.FormatAttributes(order.ShippingAddress.CustomAttributes); if (!String.IsNullOrEmpty(customShippingAddressAttributes)) { //TODO: we should add padding to each line (in case if we have sevaral custom address attributes) shippingAddress.AddCell(new Paragraph(" " + HtmlHelper.ConvertHtmlToPlainText(customShippingAddressAttributes, true, true), font)); } shippingAddress.AddCell(new Paragraph(" ")); } shippingAddress.AddCell(new Paragraph(" " + String.Format(_localizationService.GetResource("PDFInvoice.ShippingMethod", lang.Id), order.ShippingMethod), font)); shippingAddress.AddCell(new Paragraph()); addressTable.AddCell(shippingAddress); } else { shippingAddress.AddCell(new Paragraph()); addressTable.AddCell(shippingAddress); } doc.Add(addressTable); doc.Add(new Paragraph(" ")); #endregion #region Products //products var productsHeader = new PdfPTable(1); productsHeader.RunDirection = GetDirection(lang); productsHeader.WidthPercentage = 100f; var cellProducts = new PdfPCell(new Phrase(_localizationService.GetResource("PDFInvoice.Product(s)", lang.Id), titleFont)); cellProducts.Border = Rectangle.NO_BORDER; productsHeader.AddCell(cellProducts); doc.Add(productsHeader); doc.Add(new Paragraph(" ")); var orderItems = _orderService.GetAllOrderItems(order.Id, null, null, null, null, null, null); var productsTable = new PdfPTable(_catalogSettings.ShowProductSku ? 5 : 4); productsTable.RunDirection = GetDirection(lang); productsTable.WidthPercentage = 100f; if (lang.Rtl) { productsTable.SetWidths(_catalogSettings.ShowProductSku ? new[] {15, 10, 15, 15, 45} : new[] {20, 10, 20, 50}); } else { productsTable.SetWidths(_catalogSettings.ShowProductSku ? new[] {45, 15, 15, 10, 15} : new[] {50, 20, 10, 20}); } //product name var cellProductItem = new PdfPCell(new Phrase(_localizationService.GetResource("PDFInvoice.ProductName", lang.Id), font)); cellProductItem.BackgroundColor = BaseColor.LIGHT_GRAY; cellProductItem.HorizontalAlignment = Element.ALIGN_CENTER; productsTable.AddCell(cellProductItem); //SKU if (_catalogSettings.ShowProductSku) { cellProductItem = new PdfPCell(new Phrase(_localizationService.GetResource("PDFInvoice.SKU", lang.Id), font)); cellProductItem.BackgroundColor = BaseColor.LIGHT_GRAY; cellProductItem.HorizontalAlignment = Element.ALIGN_CENTER; productsTable.AddCell(cellProductItem); } //price cellProductItem = new PdfPCell(new Phrase(_localizationService.GetResource("PDFInvoice.ProductPrice", lang.Id), font)); cellProductItem.BackgroundColor = BaseColor.LIGHT_GRAY; cellProductItem.HorizontalAlignment = Element.ALIGN_CENTER; productsTable.AddCell(cellProductItem); //qty cellProductItem = new PdfPCell(new Phrase(_localizationService.GetResource("PDFInvoice.ProductQuantity", lang.Id), font)); cellProductItem.BackgroundColor = BaseColor.LIGHT_GRAY; cellProductItem.HorizontalAlignment = Element.ALIGN_CENTER; productsTable.AddCell(cellProductItem); //total cellProductItem = new PdfPCell(new Phrase(_localizationService.GetResource("PDFInvoice.ProductTotal", lang.Id), font)); cellProductItem.BackgroundColor = BaseColor.LIGHT_GRAY; cellProductItem.HorizontalAlignment = Element.ALIGN_CENTER; productsTable.AddCell(cellProductItem); foreach (var orderItem in orderItems) { var pAttribTable = new PdfPTable(1); pAttribTable.RunDirection = GetDirection(lang); pAttribTable.DefaultCell.Border = Rectangle.NO_BORDER; var p = orderItem.Product; //product name string name = p.GetLocalized(x => x.Name, lang.Id); pAttribTable.AddCell(new Paragraph(name, font)); cellProductItem.AddElement(new Paragraph(name, font)); //attributes if (!String.IsNullOrEmpty(orderItem.AttributeDescription)) { var attributesParagraph = new Paragraph(HtmlHelper.ConvertHtmlToPlainText(orderItem.AttributeDescription, true, true), attributesFont); pAttribTable.AddCell(attributesParagraph); } //rental info if (orderItem.Product.IsRental) { var rentalStartDate = orderItem.RentalStartDateUtc.HasValue ? orderItem.Product.FormatRentalDate(orderItem.RentalStartDateUtc.Value) : ""; var rentalEndDate = orderItem.RentalEndDateUtc.HasValue ? orderItem.Product.FormatRentalDate(orderItem.RentalEndDateUtc.Value) : ""; var rentalInfo = string.Format(_localizationService.GetResource("Order.Rental.FormattedDate"), rentalStartDate, rentalEndDate); var rentalInfoParagraph = new Paragraph(rentalInfo, attributesFont); pAttribTable.AddCell(rentalInfoParagraph); } productsTable.AddCell(pAttribTable); //SKU if (_catalogSettings.ShowProductSku) { var sku = p.FormatSku(orderItem.AttributesXml, _productAttributeParser); cellProductItem = new PdfPCell(new Phrase(sku ?? String.Empty, font)); cellProductItem.HorizontalAlignment = Element.ALIGN_CENTER; productsTable.AddCell(cellProductItem); } //price string unitPrice; if (order.CustomerTaxDisplayType == TaxDisplayType.IncludingTax) { //including tax var unitPriceInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(orderItem.UnitPriceInclTax, order.CurrencyRate); unitPrice = _priceFormatter.FormatPrice(unitPriceInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, lang, true); } else { //excluding tax var unitPriceExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(orderItem.UnitPriceExclTax, order.CurrencyRate); unitPrice = _priceFormatter.FormatPrice(unitPriceExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, lang, false); } cellProductItem = new PdfPCell(new Phrase(unitPrice, font)); cellProductItem.HorizontalAlignment = Element.ALIGN_LEFT; productsTable.AddCell(cellProductItem); //qty cellProductItem = new PdfPCell(new Phrase(orderItem.Quantity.ToString(), font)); cellProductItem.HorizontalAlignment = Element.ALIGN_LEFT; productsTable.AddCell(cellProductItem); //total string subTotal; if (order.CustomerTaxDisplayType == TaxDisplayType.IncludingTax) { //including tax var priceInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(orderItem.PriceInclTax, order.CurrencyRate); subTotal = _priceFormatter.FormatPrice(priceInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, lang, true); } else { //excluding tax var priceExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(orderItem.PriceExclTax, order.CurrencyRate); subTotal = _priceFormatter.FormatPrice(priceExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, lang, false); } cellProductItem = new PdfPCell(new Phrase(subTotal, font)); cellProductItem.HorizontalAlignment = Element.ALIGN_LEFT; productsTable.AddCell(cellProductItem); } doc.Add(productsTable); #endregion #region Checkout attributes if (!String.IsNullOrEmpty(order.CheckoutAttributeDescription)) { doc.Add(new Paragraph(" ")); var attribTable = new PdfPTable(1); attribTable.RunDirection = GetDirection(lang); attribTable.WidthPercentage = 100f; string attributes = HtmlHelper.ConvertHtmlToPlainText(order.CheckoutAttributeDescription, true, true); var cCheckoutAttributes = new PdfPCell(new Phrase(attributes, font)); cCheckoutAttributes.Border = Rectangle.NO_BORDER; cCheckoutAttributes.HorizontalAlignment = Element.ALIGN_RIGHT; attribTable.AddCell(cCheckoutAttributes); doc.Add(attribTable); } #endregion #region Totals //subtotal var totalsTable = new PdfPTable(1); totalsTable.RunDirection = GetDirection(lang); totalsTable.DefaultCell.Border = Rectangle.NO_BORDER; totalsTable.WidthPercentage = 100f; //order subtotal if (order.CustomerTaxDisplayType == TaxDisplayType.IncludingTax && !_taxSettings.ForceTaxExclusionFromOrderSubtotal) { //including tax var orderSubtotalInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderSubtotalInclTax, order.CurrencyRate); string orderSubtotalInclTaxStr = _priceFormatter.FormatPrice(orderSubtotalInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, lang, true); var p = new PdfPCell(new Paragraph(String.Format("{0} {1}", _localizationService.GetResource("PDFInvoice.Sub-Total", lang.Id), orderSubtotalInclTaxStr), font)); p.HorizontalAlignment = Element.ALIGN_RIGHT; p.Border = Rectangle.NO_BORDER; totalsTable.AddCell(p); } else { //excluding tax var orderSubtotalExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderSubtotalExclTax, order.CurrencyRate); string orderSubtotalExclTaxStr = _priceFormatter.FormatPrice(orderSubtotalExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, lang, false); var p = new PdfPCell(new Paragraph(String.Format("{0} {1}", _localizationService.GetResource("PDFInvoice.Sub-Total", lang.Id), orderSubtotalExclTaxStr), font)); p.HorizontalAlignment = Element.ALIGN_RIGHT; p.Border = Rectangle.NO_BORDER; totalsTable.AddCell(p); } //discount (applied to order subtotal) if (order.OrderSubTotalDiscountExclTax > decimal.Zero) { //order subtotal if (order.CustomerTaxDisplayType == TaxDisplayType.IncludingTax && !_taxSettings.ForceTaxExclusionFromOrderSubtotal) { //including tax var orderSubTotalDiscountInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderSubTotalDiscountInclTax, order.CurrencyRate); string orderSubTotalDiscountInCustomerCurrencyStr = _priceFormatter.FormatPrice(-orderSubTotalDiscountInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, lang, true); var p = new PdfPCell(new Paragraph(String.Format("{0} {1}", _localizationService.GetResource("PDFInvoice.Discount", lang.Id), orderSubTotalDiscountInCustomerCurrencyStr), font)); p.HorizontalAlignment = Element.ALIGN_RIGHT; p.Border = Rectangle.NO_BORDER; totalsTable.AddCell(p); } else { //excluding tax var orderSubTotalDiscountExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderSubTotalDiscountExclTax, order.CurrencyRate); string orderSubTotalDiscountInCustomerCurrencyStr = _priceFormatter.FormatPrice(-orderSubTotalDiscountExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, lang, false); var p = new PdfPCell(new Paragraph(String.Format("{0} {1}", _localizationService.GetResource("PDFInvoice.Discount", lang.Id), orderSubTotalDiscountInCustomerCurrencyStr), font)); p.HorizontalAlignment = Element.ALIGN_RIGHT; p.Border = Rectangle.NO_BORDER; totalsTable.AddCell(p); } } //shipping if (order.ShippingStatus != ShippingStatus.ShippingNotRequired) { if (order.CustomerTaxDisplayType == TaxDisplayType.IncludingTax) { //including tax var orderShippingInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderShippingInclTax, order.CurrencyRate); string orderShippingInclTaxStr = _priceFormatter.FormatShippingPrice(orderShippingInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, lang, true); var p = new PdfPCell(new Paragraph(String.Format("{0} {1}", _localizationService.GetResource("PDFInvoice.Shipping", lang.Id), orderShippingInclTaxStr), font)); p.HorizontalAlignment = Element.ALIGN_RIGHT; p.Border = Rectangle.NO_BORDER; totalsTable.AddCell(p); } else { //excluding tax var orderShippingExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderShippingExclTax, order.CurrencyRate); string orderShippingExclTaxStr = _priceFormatter.FormatShippingPrice(orderShippingExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, lang, false); var p = new PdfPCell(new Paragraph(String.Format("{0} {1}", _localizationService.GetResource("PDFInvoice.Shipping", lang.Id), orderShippingExclTaxStr), font)); p.HorizontalAlignment = Element.ALIGN_RIGHT; p.Border = Rectangle.NO_BORDER; totalsTable.AddCell(p); } } //payment fee if (order.PaymentMethodAdditionalFeeExclTax > decimal.Zero) { if (order.CustomerTaxDisplayType == TaxDisplayType.IncludingTax) { //including tax var paymentMethodAdditionalFeeInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.PaymentMethodAdditionalFeeInclTax, order.CurrencyRate); string paymentMethodAdditionalFeeInclTaxStr = _priceFormatter.FormatPaymentMethodAdditionalFee(paymentMethodAdditionalFeeInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, lang, true); var p = new PdfPCell(new Paragraph(String.Format("{0} {1}", _localizationService.GetResource("PDFInvoice.PaymentMethodAdditionalFee", lang.Id), paymentMethodAdditionalFeeInclTaxStr), font)); p.HorizontalAlignment = Element.ALIGN_RIGHT; p.Border = Rectangle.NO_BORDER; totalsTable.AddCell(p); } else { //excluding tax var paymentMethodAdditionalFeeExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.PaymentMethodAdditionalFeeExclTax, order.CurrencyRate); string paymentMethodAdditionalFeeExclTaxStr = _priceFormatter.FormatPaymentMethodAdditionalFee(paymentMethodAdditionalFeeExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, lang, false); var p = new PdfPCell(new Paragraph(String.Format("{0} {1}", _localizationService.GetResource("PDFInvoice.PaymentMethodAdditionalFee", lang.Id), paymentMethodAdditionalFeeExclTaxStr), font)); p.HorizontalAlignment = Element.ALIGN_RIGHT; p.Border = Rectangle.NO_BORDER; totalsTable.AddCell(p); } } //tax string taxStr = string.Empty; var taxRates = new SortedDictionary<decimal, decimal>(); bool displayTax = true; bool displayTaxRates = true; if (_taxSettings.HideTaxInOrderSummary && order.CustomerTaxDisplayType == TaxDisplayType.IncludingTax) { displayTax = false; } else { if (order.OrderTax == 0 && _taxSettings.HideZeroTax) { displayTax = false; displayTaxRates = false; } else { taxRates = order.TaxRatesDictionary; displayTaxRates = _taxSettings.DisplayTaxRates && taxRates.Count > 0; displayTax = !displayTaxRates; var orderTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderTax, order.CurrencyRate); taxStr = _priceFormatter.FormatPrice(orderTaxInCustomerCurrency, true, order.CustomerCurrencyCode, false, lang); } } if (displayTax) { var p = new PdfPCell(new Paragraph(String.Format("{0} {1}", _localizationService.GetResource("PDFInvoice.Tax", lang.Id), taxStr), font)); p.HorizontalAlignment = Element.ALIGN_RIGHT; p.Border = Rectangle.NO_BORDER; totalsTable.AddCell(p); } if (displayTaxRates) { foreach (var item in taxRates) { string taxRate = String.Format(_localizationService.GetResource("PDFInvoice.TaxRate", lang.Id), _priceFormatter.FormatTaxRate(item.Key)); string taxValue = _priceFormatter.FormatPrice(_currencyService.ConvertCurrency(item.Value, order.CurrencyRate), true, order.CustomerCurrencyCode, false, lang); var p = new PdfPCell(new Paragraph(String.Format("{0} {1}", taxRate, taxValue), font)); p.HorizontalAlignment = Element.ALIGN_RIGHT; p.Border = Rectangle.NO_BORDER; totalsTable.AddCell(p); } } //discount (applied to order total) if (order.OrderDiscount > decimal.Zero) { var orderDiscountInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderDiscount, order.CurrencyRate); string orderDiscountInCustomerCurrencyStr = _priceFormatter.FormatPrice(-orderDiscountInCustomerCurrency, true, order.CustomerCurrencyCode, false, lang); var p = new PdfPCell(new Paragraph(String.Format("{0} {1}", _localizationService.GetResource("PDFInvoice.Discount", lang.Id), orderDiscountInCustomerCurrencyStr), font)); p.HorizontalAlignment = Element.ALIGN_RIGHT; p.Border = Rectangle.NO_BORDER; totalsTable.AddCell(p); } //gift cards foreach (var gcuh in order.GiftCardUsageHistory) { string gcTitle = string.Format(_localizationService.GetResource("PDFInvoice.GiftCardInfo", lang.Id), gcuh.GiftCard.GiftCardCouponCode); string gcAmountStr = _priceFormatter.FormatPrice(-(_currencyService.ConvertCurrency(gcuh.UsedValue, order.CurrencyRate)), true, order.CustomerCurrencyCode, false, lang); var p = new PdfPCell(new Paragraph(String.Format("{0} {1}", gcTitle, gcAmountStr), font)); p.HorizontalAlignment = Element.ALIGN_RIGHT; p.Border = Rectangle.NO_BORDER; totalsTable.AddCell(p); } //reward points if (order.RedeemedRewardPointsEntry != null) { string rpTitle = string.Format(_localizationService.GetResource("PDFInvoice.RewardPoints", lang.Id), -order.RedeemedRewardPointsEntry.Points); string rpAmount = _priceFormatter.FormatPrice(-(_currencyService.ConvertCurrency(order.RedeemedRewardPointsEntry.UsedAmount, order.CurrencyRate)), true, order.CustomerCurrencyCode, false, lang); var p = new PdfPCell(new Paragraph(String.Format("{0} {1}", rpTitle, rpAmount), font)); p.HorizontalAlignment = Element.ALIGN_RIGHT; p.Border = Rectangle.NO_BORDER; totalsTable.AddCell(p); } //order total var orderTotalInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderTotal, order.CurrencyRate); string orderTotalStr = _priceFormatter.FormatPrice(orderTotalInCustomerCurrency, true, order.CustomerCurrencyCode, false, lang); var pTotal = new PdfPCell(new Paragraph(String.Format("{0} {1}", _localizationService.GetResource("PDFInvoice.OrderTotal", lang.Id), orderTotalStr), titleFont)); pTotal.HorizontalAlignment = Element.ALIGN_RIGHT; pTotal.Border = Rectangle.NO_BORDER; totalsTable.AddCell(pTotal); doc.Add(totalsTable); #endregion #region Order notes if (pdfSettingsByStore.RenderOrderNotes) { var orderNotes = order.OrderNotes .Where(on => on.DisplayToCustomer) .OrderByDescending(on => on.CreatedOnUtc) .ToList(); if (orderNotes.Count > 0) { var notesHeader = new PdfPTable(1); notesHeader.RunDirection = GetDirection(lang); notesHeader.WidthPercentage = 100f; var cellOrderNote = new PdfPCell(new Phrase(_localizationService.GetResource("PDFInvoice.OrderNotes", lang.Id), titleFont)); cellOrderNote.Border = Rectangle.NO_BORDER; notesHeader.AddCell(cellOrderNote); doc.Add(notesHeader); doc.Add(new Paragraph(" ")); var notesTable = new PdfPTable(2); notesTable.RunDirection = GetDirection(lang); if (lang.Rtl) { notesTable.SetWidths(new[] {70, 30}); } else { notesTable.SetWidths(new[] {30, 70}); } notesTable.WidthPercentage = 100f; //created on cellOrderNote = new PdfPCell(new Phrase(_localizationService.GetResource("PDFInvoice.OrderNotes.CreatedOn", lang.Id), font)); cellOrderNote.BackgroundColor = BaseColor.LIGHT_GRAY; cellOrderNote.HorizontalAlignment = Element.ALIGN_CENTER; notesTable.AddCell(cellOrderNote); //note cellOrderNote = new PdfPCell(new Phrase(_localizationService.GetResource("PDFInvoice.OrderNotes.Note", lang.Id), font)); cellOrderNote.BackgroundColor = BaseColor.LIGHT_GRAY; cellOrderNote.HorizontalAlignment = Element.ALIGN_CENTER; notesTable.AddCell(cellOrderNote); foreach (var orderNote in orderNotes) { cellOrderNote = new PdfPCell(new Phrase(_dateTimeHelper.ConvertToUserTime(orderNote.CreatedOnUtc, DateTimeKind.Utc).ToString(), font)); cellOrderNote.HorizontalAlignment = Element.ALIGN_LEFT; notesTable.AddCell(cellOrderNote); cellOrderNote = new PdfPCell(new Phrase(HtmlHelper.ConvertHtmlToPlainText(orderNote.FormatOrderNoteText(), true, true), font)); cellOrderNote.HorizontalAlignment = Element.ALIGN_LEFT; notesTable.AddCell(cellOrderNote); //should we display a link to downloadable files here? //I think, no. Onyway, PDFs are printable documents and links (files) are useful here } doc.Add(notesTable); } } #endregion #region Footer if (!String.IsNullOrEmpty(pdfSettingsByStore.InvoiceFooterTextColumn1) || !String.IsNullOrEmpty(pdfSettingsByStore.InvoiceFooterTextColumn2)) { var column1Lines = String.IsNullOrEmpty(pdfSettingsByStore.InvoiceFooterTextColumn1) ? new List<string>() : pdfSettingsByStore.InvoiceFooterTextColumn1 .Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries) .ToList(); var column2Lines = String.IsNullOrEmpty(pdfSettingsByStore.InvoiceFooterTextColumn2) ? new List<string>() : pdfSettingsByStore.InvoiceFooterTextColumn2 .Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries) .ToList(); if (column1Lines.Count > 0 || column2Lines.Count > 0) { var totalLines = Math.Max(column1Lines.Count, column2Lines.Count); const float margin = 43; //if you have really a lot of lines in the footer, then replace 9 with 10 or 11 int footerHeight = totalLines * 9; var directContent = pdfWriter.DirectContent; directContent.MoveTo(pageSize.GetLeft(margin), pageSize.GetBottom(margin) + footerHeight); directContent.LineTo(pageSize.GetRight(margin), pageSize.GetBottom(margin) + footerHeight); directContent.Stroke(); var footerTable = new PdfPTable(2); footerTable.WidthPercentage = 100f; footerTable.SetTotalWidth(new float[] { 250, 250 }); footerTable.RunDirection = GetDirection(lang); //column 1 if (column1Lines.Count > 0) { var column1 = new PdfPCell(new Phrase()); column1.Border = Rectangle.NO_BORDER; column1.HorizontalAlignment = Element.ALIGN_LEFT; foreach (var footerLine in column1Lines) { column1.Phrase.Add(new Phrase(footerLine, font)); column1.Phrase.Add(new Phrase(Environment.NewLine)); } footerTable.AddCell(column1); } else { var column = new PdfPCell(new Phrase(" ")); column.Border = Rectangle.NO_BORDER; footerTable.AddCell(column); } //column 2 if (column2Lines.Count > 0) { var column2 = new PdfPCell(new Phrase()); column2.Border = Rectangle.NO_BORDER; column2.HorizontalAlignment = Element.ALIGN_LEFT; foreach (var footerLine in column2Lines) { column2.Phrase.Add(new Phrase(footerLine, font)); column2.Phrase.Add(new Phrase(Environment.NewLine)); } footerTable.AddCell(column2); } else { var column = new PdfPCell(new Phrase(" ")); column.Border = Rectangle.NO_BORDER; footerTable.AddCell(column); } footerTable.WriteSelectedRows(0, totalLines, pageSize.GetLeft(margin), pageSize.GetBottom(margin) + footerHeight, directContent); } } #endregion ordNum++; if (ordNum < ordCount) { doc.NewPage(); } } doc.Close(); }
/** * Write an <code>Anchor</code>. Anchors are treated like Phrases. * * @param anchor The <code>Chunk</code> item to be written * @param outp The <code>MemoryStream</code> to write to * * @throws IOException */ private void WriteAnchor(Anchor anchor, MemoryStream outp) { if (anchor.Url != null) { outp.WriteByte(openGroup); outp.WriteByte(escape); outp.Write(field, 0, field.Length); outp.WriteByte(openGroup); outp.Write(extendedEscape, 0, extendedEscape.Length); outp.Write(fieldContent, 0, fieldContent.Length); outp.WriteByte(openGroup); outp.Write(fieldHyperlink, 0, fieldHyperlink.Length); outp.WriteByte(delimiter); byte[] t = DocWriter.GetISOBytes(anchor.Url.ToString()); outp.Write(t, 0, t.Length); outp.WriteByte(closeGroup); outp.WriteByte(closeGroup); outp.WriteByte(openGroup); outp.WriteByte(escape); outp.Write(fieldDisplay, 0, fieldDisplay.Length); outp.WriteByte(delimiter); WritePhrase(anchor, outp); outp.WriteByte(closeGroup); outp.WriteByte(closeGroup); } else { WritePhrase(anchor, outp); } }