// --------------------------------------------------------------------------- // replace ContentParser.endElement() from Java example public void EndElement(string name) { if ("chapter".Equals(name)) { return; } String s = buf.ToString().Trim(); buf = new StringBuilder(); if (s.Length > 0) { Paragraph p = new Paragraph(s, font); p.Alignment = Element.ALIGN_JUSTIFIED; column.AddElement(p); int status = column.Go(); while (ColumnText.HasMoreText(status)) { canvas.EndMarkedContentSequence(); document.NewPage(); canvas.BeginMarkedContentSequence(current); column.SetSimpleColumn(36, 36, 384, 569); status = column.Go(); } } canvas.EndMarkedContentSequence(); }
// --------------------------------------------------------------------------- /** * Manipulates a PDF file src * @param src the original PDF * @param stationery the resulting PDF */ public byte[] ManipulatePdf(byte[] src, byte[] stationery) { ColumnText ct = new ColumnText(null); string SQL = @"SELECT country, id FROM film_country ORDER BY country "; 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()) { ct.AddElement(new Paragraph( 24, new Chunk(r["country"].ToString()) )); } } } } // Create a reader for the original document and for the stationery PdfReader reader = new PdfReader(src); PdfReader rStationery = new PdfReader(stationery); using (MemoryStream ms = new MemoryStream()) { // Create a stamper using (PdfStamper stamper = new PdfStamper(reader, ms)) { // Create an imported page for the stationery PdfImportedPage page = stamper.GetImportedPage(rStationery, 1); int i = 0; // Add the content of the ColumnText object while (true) { // Add a new page stamper.InsertPage(++i, reader.GetPageSize(1)); // Add the stationary to the new page stamper.GetUnderContent(i).AddTemplate(page, 0, 0); // Add as much content of the column as possible ct.Canvas = stamper.GetOverContent(i); ct.SetSimpleColumn(36, 36, 559, 770); if (!ColumnText.HasMoreText(ct.Go())) { break; } } } return(ms.ToArray()); } }
private void WriteToColumns() { float gutter = -20f; float colwidth = (doc.Right - doc.Left - gutter) / 2; int status = 0; int i = 0; int count = 0; bool newPage = false; //Checks the value of status to determine if there is more text //If there is, status is 2, which is the value of NO_MORE_COLUMN while (ColumnText.HasMoreText(status)) { if (i == 0) { //Writing the first column ct.SetSimpleColumn(doc.Left, doc.Bottom, doc.Right - colwidth, doc.Top); i++; } else { //write the second column ct.SetSimpleColumn(doc.Left + colwidth, doc.Bottom, doc.Right, doc.Top); } //Needs to be here to prevent app from hanging if (!newPage) { ct.YLine = doc.Top - 90f; } else { ct.YLine = doc.Top - 30f; } //Commit the content of the ColumnText to the document //ColumnText.Go() returns NO_MORE_TEXT (1) and/or NO_MORE_COLUMN (2) //In other words, it fills the column until it has either run out of column, or text, or both status = ct.Go(); if (++count > 1) { count = 0; if (ColumnText.HasMoreText(status)) { doc.NewPage(); newPage = true; } i = 0; } } }
// =========================================================================== public void Write(Stream stream) { // step 1 using (Document document = new Document(PageSize.A4.Rotate())) { // step 2 PdfWriter writer = PdfWriter.GetInstance(document, stream); // step 3 document.Open(); // step 4 ColumnText column = new ColumnText(writer.DirectContent); List <string> days = PojoFactory.GetDays(); // COlumn definition float[][] x = { new float[] { document.Left, document.Left + 380 }, new float[] { document.Right - 380, document.Right } }; // Loop over the festival days foreach (string day in days) { // add content to the column column.AddElement(GetTable(day)); int count = 0; float height = 0; // iText-ONLY, 'Initial value of the status' => 0 // iTextSharp **DOES NOT** include this member variable // int status = ColumnText.START_COLUMN; int status = 0; // render the column as long as it has content while (ColumnText.HasMoreText(status)) { // add the top-level header to each new page if (count == 0) { height = AddHeaderTable(document, day, writer.PageNumber); } // set the dimensions of the current column column.SetSimpleColumn( x[count][0], document.Bottom, x[count][1], document.Top - height - 10 ); // render as much content as possible status = column.Go(); // go to a new page if you've reached the last column if (++count > 1) { count = 0; document.NewPage(); } } document.NewPage(); } } }
public bool AddParagraph(Paragraph p, PdfContentByte canvas, AcroFields.FieldPosition f, bool simulate) { ColumnText ct = new ColumnText(canvas); ct.SetSimpleColumn( f.position.Left, f.position.GetBottom(2), f.position.GetRight(2), f.position.Top ); ct.AddElement(p); return(ColumnText.HasMoreText(ct.Go(simulate))); }
// =========================================================================== public override void Write(Stream stream) { // step 1 using (Document document = new Document()) { // step 2 PdfWriter writer = PdfWriter.GetInstance(document, stream); // step 3 document.Open(); // step 4 PdfContentByte canvas = writer.DirectContent; DrawRectangles(canvas); ColumnText ct = new ColumnText(canvas); ct.Alignment = Element.ALIGN_JUSTIFIED; ct.Leading = 14; int column = 0; ct.SetColumns( new float[] { 36, 806, 36, 670, 108, 670, 108, 596, 36, 596, 36, 36 }, new float[] { 296, 806, 296, 484, 259, 484, 259, 410, 296, 410, 296, 36 } ); ct.SetColumns(LEFT[column], RIGHT[column]); // ct.SetColumns(LEFT[column], RIGHT[column]); // iText-ONLY, 'Initial value of the status' => 0 // iTextSharp **DOES NOT** include this member variable // int status = ColumnText.START_COLUMN; int status = 0; Phrase p; float y; IEnumerable <Movie> movies = PojoFactory.GetMovies(); foreach (Movie movie in movies) { y = ct.YLine; p = CreateMovieInformation(movie); ct.AddText(p); status = ct.Go(true); if (ColumnText.HasMoreText(status)) { column = Math.Abs(column - 1); if (column == 0) { document.NewPage(); DrawRectangles(canvas); } ct.SetColumns(LEFT[column], RIGHT[column]); y = 806; } ct.YLine = y; ct.SetText(p); status = ct.Go(); } } }
// --------------------------------------------------------------------------- public void Write(Stream stream) { // step 1 using (Document document = new Document(PageSize.A4.Rotate())) { // step 2 PdfWriter writer = PdfWriter.GetInstance(document, stream); // step 3 document.Open(); // step 4 ColumnText ct = new ColumnText(writer.DirectContent); int column = 0; ct.SetSimpleColumn( COLUMNS[column, 0], COLUMNS[column, 1], COLUMNS[column, 2], COLUMNS[column, 3] ); // iText-ONLY, 'Initial value of the status' => 0 // iTextSharp **DOES NOT** include this member variable // int status = ColumnText.START_COLUMN; int status = 0; float y; Image img; IEnumerable <Movie> movies = PojoFactory.GetMovies(); foreach (Movie movie in movies) { y = ct.YLine; img = Image.GetInstance( Path.Combine(RESOURCE, movie.Imdb + ".jpg") ); img.ScaleToFit(80, 1000); AddContent(ct, movie, img); status = ct.Go(true); if (ColumnText.HasMoreText(status)) { column = (column + 1) % 4; if (column == 0) { document.NewPage(); } ct.SetSimpleColumn( COLUMNS[column, 0], COLUMNS[column, 1], COLUMNS[column, 2], COLUMNS[column, 3] ); y = COLUMNS[column, 3]; } ct.YLine = y; ct.SetText(null); AddContent(ct, movie, img); status = ct.Go(); } } }
// =========================================================================== public override void Write(Stream stream) { // step 1 using (Document document = new Document()) { // step 2 PdfWriter writer = PdfWriter.GetInstance(document, stream); // step 3 document.Open(); // step 4 ColumnText ct = new ColumnText(writer.DirectContent) { Alignment = Element.ALIGN_JUSTIFIED, ExtraParagraphSpace = 6, Leading = 14, Indent = 10, RightIndent = 3, SpaceCharRatio = PdfWriter.NO_SPACE_CHAR_RATIO }; int column = 0; // iText-ONLY, 'Initial value of the status' => 0 // iTextSharp **DOES NOT** include this member variable // int status = ColumnText.START_COLUMN; int status = 0; ct.SetSimpleColumn( COLUMNS[column][0], COLUMNS[column][1], COLUMNS[column][2], COLUMNS[column][3] ); IEnumerable <Movie> movies = PojoFactory.GetMovies(); foreach (Movie movie in movies) { ct.AddText(CreateMovieInformation(movie)); status = ct.Go(); if (ColumnText.HasMoreText(status)) { column = Math.Abs(column - 1); if (column == 0) { document.NewPage(); } ct.SetSimpleColumn( COLUMNS[column][0], COLUMNS[column][1], COLUMNS[column][2], COLUMNS[column][3] ); ct.YLine = COLUMNS[column][3]; status = ct.Go(); } } } }
private static bool WriteNonWrappingTextInRectangle(PdfContentByte canvas, string text, Font font, Rectangle rectangle, int alignment, bool simulation = false) { var phrase = new Phrase(text, font); var columnText = new ColumnText(canvas) { Alignment = alignment }; columnText.SetSimpleColumn(phrase, rectangle.Left, rectangle.Bottom, rectangle.Right, rectangle.Top, font.Size, alignment); var result = columnText.Go(simulation); return(!ColumnText.HasMoreText(result)); }
public virtual void NestedTableTest() { Document doc = new Document(PageSize.A4); String file = "nestedtabletest.pdf"; PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(OUTPUT_FOLDER + file, FileMode.Create)); doc.Open(); ColumnText col = new ColumnText(writer.DirectContent); col.SetSimpleColumn( Utilities.MillimetersToPoints(25), Utilities.MillimetersToPoints(25), PageSize.A4.Right - Utilities.MillimetersToPoints(25), PageSize.A4.Top - Utilities.MillimetersToPoints(25)); PdfPTable table = new PdfPTable(3); table.HeaderRows = 1; table.AddCell("H1"); table.AddCell("H2"); table.AddCell("H3"); for (int i = 0; i < 15; i++) { PdfPCell cell = new PdfPCell(createNestedTable()); cell.Rowspan = 3; cell.Colspan = 3; table.AddCell(cell); } col.AddElement(table); while (ColumnText.HasMoreText(col.Go())) { doc.NewPage(); col.YLine = PageSize.A4.Top - Utilities.MillimetersToPoints(25); } doc.Close(); // compare CompareTool compareTool = new CompareTool(OUTPUT_FOLDER + file, CMP_FOLDER + file); String errorMessage = compareTool.Compare(OUTPUT_FOLDER, "diff"); if (errorMessage != null) { Assert.Fail(errorMessage); } }
public static bool WriteWrappingTextInRectangle(PdfContentByte canvas, string text, Font font, Rectangle rectangle, int alignment, bool simulation = false) { var phrase = new Phrase(text, font); var columnText = new ColumnText(canvas) { Alignment = alignment }; columnText.SetSimpleColumn(rectangle); columnText.AddElement(phrase); var result = columnText.Go(simulation); return(!ColumnText.HasMoreText(result)); }
public void ManipulatePdf(String src, String dest, IDictionary <string, string> pdfParams) { PdfReader reader = new PdfReader(src); Rectangle pagesize = reader.GetPageSize(1); PdfStamper stamper = new PdfStamper(reader, new FileStream(dest, FileMode.Create)); AcroFields form = stamper.AcroFields; byte[] fontBinary; using (var client = new WebClient()) fontBinary = client.DownloadData("http://beta.adahi.linkdev.com/Style%20Library/Adahi/fonts/Tahoma.ttf"); var arialBaseFont = BaseFont.CreateFont("Tahoma.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, false, fontBinary, null); form.GenerateAppearances = true; form.AddSubstitutionFont(arialBaseFont); foreach (var param in pdfParams) { form.SetField(param.Key, param.Value); } PdfPTable table = new PdfPTable(2); table.AddCell("#"); table.AddCell("description"); table.HeaderRows = 1; table.SetWidths(new int[] { 1, 15 }); for (int i = 1; i <= 150; i++) { table.AddCell(i.ToString()); table.AddCell("test " + i); } ColumnText column = new ColumnText(stamper.GetOverContent(1)); Rectangle rectPage1 = new Rectangle(36, 36, 559, 540); column.SetSimpleColumn(rectPage1); column.AddElement(table); int pagecount = 1; Rectangle rectPage2 = new Rectangle(36, 36, 559, 806); int status = column.Go(); while (ColumnText.HasMoreText(status)) { status = TriggerNewPage(stamper, pagesize, column, rectPage2, ++pagecount); } stamper.FormFlattening = false; stamper.Close(); reader.Close(); }
// =========================================================================== public override void Write(Stream stream) { // step 1 using (Document document = new Document()) { // step 2 PdfWriter writer = PdfWriter.GetInstance(document, stream); // step 3 document.Open(); // step 4 ColumnText ct = new ColumnText(writer.DirectContent); int column = 0; ct.SetSimpleColumn( COLUMNS[column][0], COLUMNS[column][1], COLUMNS[column][2], COLUMNS[column][3] ); // iText-ONLY, 'Initial value of the status' => 0 // iTextSharp **DOES NOT** include this member variable // int status = ColumnText.START_COLUMN; int status = 0; Phrase p; float y; IEnumerable <Movie> movies = PojoFactory.GetMovies(); foreach (Movie movie in movies) { y = ct.YLine; p = CreateMovieInformation(movie); ct.AddText(p); status = ct.Go(true); if (ColumnText.HasMoreText(status)) { column = Math.Abs(column - 1); if (column == 0) { document.NewPage(); } ct.SetSimpleColumn( COLUMNS[column][0], COLUMNS[column][1], COLUMNS[column][2], COLUMNS[column][3] ); y = COLUMNS[column][3]; } ct.YLine = y; ct.SetText(p); status = ct.Go(false); } } }
// =========================================================================== public virtual void Write(Stream stream) { // step 1 using (Document document = new Document()) { // step 2 PdfWriter writer = PdfWriter.GetInstance(document, stream); // step 3 document.Open(); // step 4 IEnumerable <Movie> movies = PojoFactory.GetMovies(); ColumnText ct = new ColumnText(writer.DirectContent); foreach (Movie movie in movies) { ct.AddText(CreateMovieInformation(movie)); ct.AddText(Chunk.NEWLINE); } ct.Alignment = Element.ALIGN_JUSTIFIED; ct.ExtraParagraphSpace = 6; ct.SetLeading(0, 1.2f); ct.FollowingIndent = 27; int linesWritten = 0; int column = 0; // iText-ONLY, 'Initial value of the status' => 0 // iTextSharp **DOES NOT** include this member variable // int status = ColumnText.START_COLUMN; int status = 0; while (ColumnText.HasMoreText(status)) { ct.SetSimpleColumn( COLUMNS[column][0], COLUMNS[column][1], COLUMNS[column][2], COLUMNS[column][3] ); ct.YLine = COLUMNS[column][3]; status = ct.Go(); linesWritten += ct.LinesWritten; column = Math.Abs(column - 1); if (column == 0) { document.NewPage(); } } ct.AddText(new Phrase("Lines written: " + linesWritten)); ct.Go(); } }
public static void AddTableNoSplit(Document document, ICustomPageEvent pgEvent, PdfPTable table) { int goStatus = 0; float pos = 0; ColumnText ct = pgEvent.GetColumnObject(); pos = ct.YLine; ct.AddElement(table); goStatus = ct.Go(true); if (ColumnText.HasMoreText(goStatus)) { document.NewPage(); ct = pgEvent.GetColumnObject(); ct.AddElement(table); ct.Go(false); } else { ct.AddElement(table); ct.YLine = pos; ct.Go(false); } }
public void Run(Stream stream, CMSDataContext Db, IEnumerable <ContributorInfo> q, int set = 0) { pageEvents.set = set; 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; int prevfid = 0; var runningtotals = Db.ContributionsRuns.OrderByDescending(mm => mm.Id).FirstOrDefault(); 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; } doc.NewPage(); if (prevfid != ci.FamilyId) { prevfid = ci.FamilyId; pageEvents.EndPageSet(); } 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(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(); }
public void Go() { // GetClassOutputPath() implementation left out for brevity var outputFile = Helpers.IO.GetClassOutputPath(this); using (FileStream stream = new FileStream( outputFile, FileMode.Create, FileAccess.Write)) { using (Document doc = new Document()) { var writer = PdfWriter.GetInstance(doc, stream); doc.Open(); Font font = FontFactory.GetFont("Arial", 20); string word = "word word word word"; StringBuilder sb = new StringBuilder(); PdfContentByte cb = writer.DirectContent; ColumnText ct = new ColumnText(cb); ct.Alignment = Element.ALIGN_JUSTIFIED; Paragraph hazardTitle = new Paragraph("Hazards", font); hazardTitle.Alignment = Element.ALIGN_CENTER; var pos = writer.GetVerticalPosition(false) - 40; float gutter = 15f; float colwidth = (doc.Right - doc.Left - gutter) / 2; float col0right = doc.Left + colwidth; float col1left = col0right + gutter; float col1right = col1left + colwidth; float[][] COLUMNS = { new float[] { doc.Left, doc.Bottom, col0right, pos }, new float[] { col1left, doc.Bottom, col1right, pos } }; for (int i = 1; i <= 40; ++i) { ct.AddText(new Phrase(string.Format( "- [{0}] {1}", i, sb.Append(word).ToString() ))); ct.AddText(Chunk.NEWLINE); } int status = 0; int column = 0; while (ColumnText.HasMoreText(status)) { ct.SetSimpleColumn( COLUMNS[column][0], COLUMNS[column][1], COLUMNS[column][2], COLUMNS[column][3] ); status = ct.Go(); column = Math.Abs(column - 1); if (column == 0) { doc.Add(hazardTitle); doc.NewPage(); } } // add last title if column 1 stll has space if (column != 0) { doc.Add(hazardTitle); } } } }
public void Verify_MultiColumn_Report_CanBe_Processed() { var pdfFilePath = TestUtils.GetOutputFileName(); var fileStream = new FileStream(pdfFilePath, FileMode.Create); var pdfDoc = new Document(PageSize.A4); var pdfWriter = PdfWriter.GetInstance(pdfDoc, fileStream); pdfDoc.AddAuthor(TestUtils.Author); pdfDoc.Open(); var table1 = new PdfPTable(1) { WidthPercentage = 100f, HeaderRows = 3, FooterRows = 1 }; //header row var headerCell1 = new PdfPCell(new Phrase("header row-1")); table1.AddCell(headerCell1); var headerCell2 = new PdfPCell(new Phrase("header row-2")); table1.AddCell(headerCell2); //footer row var footerCell = new PdfPCell(new Phrase(" footer ")); table1.AddCell(footerCell); //adding some rows for (var i = 0; i < 400; i++) { var rowCell = new PdfPCell(new Phrase(i.ToString())); table1.AddCell(rowCell); } table1.SkipFirstHeader = true; // wrapping table1 in multiple columns var ct = new ColumnText(pdfWriter.DirectContent) { RunDirection = PdfWriter.RUN_DIRECTION_RTL }; ct.AddElement(table1); var status = 0; var count = 0; var l = 0; var columnsWidth = 100; var columnsMargin = 7; var columnsPerPage = 4; var r = columnsWidth; var isRtl = true; // render the column as long as it has content while (ColumnText.HasMoreText(status)) { if (isRtl) { ct.SetSimpleColumn( pdfDoc.Right - l, pdfDoc.Bottom, pdfDoc.Right - r, pdfDoc.Top ); } else { ct.SetSimpleColumn( pdfDoc.Left + l, pdfDoc.Bottom, pdfDoc.Left + r, pdfDoc.Top ); } var delta = columnsWidth + columnsMargin; l += delta; r += delta; // render as much content as possible status = ct.Go(); // go to a new page if you've reached the last column if (++count > columnsPerPage) { count = 0; l = 0; r = columnsWidth; pdfDoc.NewPage(); } } pdfDoc.Close(); fileStream.Dispose(); TestUtils.VerifyPdfFileIsReadable(pdfFilePath); }
public override void ExecuteResult(ControllerContext context) { var Response = context.HttpContext.Response; if (MeetingId.HasValue) { meeting = DbUtil.Db.Meetings.Single(mt => mt.MeetingId == MeetingId); Debug.Assert(meeting.MeetingDate != null, "meeting.MeetingDate != null"); NewMeetingInfo = new NewMeetingInfo { MeetingDate = meeting.MeetingDate.Value }; } var list1 = NewMeetingInfo.ByGroup ? ReportList2().ToList() : ReportList().ToList(); if (!list1.Any()) { Response.Write("no data found"); return; } Response.ContentType = "application/pdf"; Response.AddHeader("content-disposition", "filename=foo.pdf"); doc = new Document(PageSize.LETTER.Rotate(), 36, 36, 64, 64); var w = PdfWriter.GetInstance(doc, Response.OutputStream); w.PageEvent = pageEvents; doc.Open(); dc = w.DirectContent; box = new PdfPCell(); box.Border = Rectangle.NO_BORDER; box.CellEvent = new CellEvent(); OrgInfo lasto = null; foreach (var o in list1) { lasto = o; var table = new PdfPTable(1); table.DefaultCell.Border = Rectangle.NO_BORDER; table.DefaultCell.Padding = 0; table.WidthPercentage = 100; if (meeting != null) { var q = from at in meeting.Attends where at.AttendanceFlag || AttendCommitmentCode.committed.Contains(at.Commitment ?? 0) orderby at.Person.LastName, at.Person.FamilyId, at.Person.Name2 select new { at.MemberType.Code, Name2 = NewMeetingInfo.UseAltNames && at.Person.AltName.HasValue() ? at.Person.AltName : at.Person.Name2, at.PeopleId, at.Person.DOB }; if (q.Any()) { StartPageSet(o); } foreach (var a in q) { table.AddCell(AddRow(a.Code, a.Name2, a.PeopleId, a.DOB, "", font)); } } else if (OrgSearchModel != null) { var q = from om in DbUtil.Db.OrganizationMembers where om.OrganizationId == o.OrgId join m in DbUtil.Db.OrgPeople(o.OrgId, o.Groups) on om.PeopleId equals m.PeopleId where om.EnrollmentDate <= Util.Now orderby om.Person.LastName, om.Person.FamilyId, om.Person.Name2 let p = om.Person let ch = NewMeetingInfo.UseAltNames && p.AltName != null && p.AltName.Length > 0 select new { p.PeopleId, Name2 = ch ? p.AltName : p.Name2, BirthDate = Person.FormatBirthday( p.BirthYr, p.BirthMonth, p.BirthDay, p.PeopleId), MemberTypeCode = om.MemberType.Code, ch, highlight = om.OrgMemMemTags.Any(mm => mm.MemberTag.Name == NewMeetingInfo.HighlightGroup) ? NewMeetingInfo.HighlightGroup : "" }; if (q.Any()) { StartPageSet(o); } foreach (var m in q) { table.AddCell(AddRow(m.MemberTypeCode, m.Name2, m.PeopleId, m.BirthDate, m.highlight, m.ch ? china ?? font : font)); } } else if (Filter?.GroupSelect == GroupSelectCode.Member) { var q = from om in DbUtil.Db.OrganizationMembers where om.OrganizationId == Filter.Id join m in DbUtil.Db.OrgFilterPeople(QueryId, null) on om.PeopleId equals m.PeopleId where om.EnrollmentDate <= Util.Now where NewMeetingInfo.ByGroup == false || m.Groups.Contains((char)10 + o.Groups + (char)10) orderby om.Person.LastName, om.Person.FamilyId, om.Person.Name2 let p = om.Person let ch = NewMeetingInfo.UseAltNames && p.AltName != null && p.AltName.Length > 0 select new { p.PeopleId, Name2 = ch ? p.AltName : p.Name2, BirthDate = Person.FormatBirthday( p.BirthYr, p.BirthMonth, p.BirthDay, p.PeopleId), MemberTypeCode = om.MemberType.Code, ch, highlight = om.OrgMemMemTags.Any(mm => mm.MemberTag.Name == NewMeetingInfo.HighlightGroup) ? NewMeetingInfo.HighlightGroup : "" }; if (q.Any()) { StartPageSet(o); } foreach (var m in q) { table.AddCell(AddRow(m.MemberTypeCode, m.Name2, m.PeopleId, m.BirthDate, m.highlight, m.ch ? china ?? font : font)); } } else { var q = from m in DbUtil.Db.OrgFilterPeople(QueryId, null) orderby m.Name2 let p = DbUtil.Db.People.Single(pp => pp.PeopleId == m.PeopleId) let om = p.OrganizationMembers.SingleOrDefault(mm => mm.OrganizationId == Filter.Id) let ch = NewMeetingInfo.UseAltNames && p.AltName != null && p.AltName.Length > 0 select new { p.PeopleId, Name2 = ch ? p.AltName : p.Name2, BirthDate = Person.FormatBirthday( p.BirthYr, p.BirthMonth, p.BirthDay, p.PeopleId), MemberTypeCode = om == null ? "Guest" : om.MemberType.Code, ch, highlight = om.OrgMemMemTags.Any(mm => mm.MemberTag.Name == NewMeetingInfo.HighlightGroup) ? NewMeetingInfo.HighlightGroup : "" }; if (q.Any()) { StartPageSet(o); } foreach (var m in q) { table.AddCell(AddRow(m.MemberTypeCode, m.Name2, m.PeopleId, m.BirthDate, m.highlight, m.ch ? china ?? font : font)); } } if ((OrgSearchModel != null && NewMeetingInfo.ByGroup == false) || (Filter != null && Filter.GroupSelect == GroupSelectCode.Member && meeting == null && !Filter.SgFilter.HasValue() && !Filter.NameFilter.HasValue() && !Filter.FilterIndividuals == true && !Filter.FilterTag == true && NewMeetingInfo.ByGroup == false)) { foreach (var m in RollsheetModel.FetchVisitors(o.OrgId, NewMeetingInfo.MeetingDate, true, NewMeetingInfo.UseAltNames)) { if (table.Rows.Count == 0) { StartPageSet(o); } table.AddCell(AddRow(m.VisitorType, m.Name2, m.PeopleId, m.BirthDate, "", boldfont)); } } if (!pageSetStarted) { continue; } var col = 0; var gutter = 20f; var colwidth = (doc.Right - doc.Left - gutter) / 2; var ct = new ColumnText(w.DirectContent); ct.AddElement(table); var status = 0; while (ColumnText.HasMoreText(status)) { if (col == 0) { ct.SetSimpleColumn(doc.Left, doc.Bottom, doc.Left + colwidth, doc.Top); } else { ct.SetSimpleColumn(doc.Right - colwidth, doc.Bottom, doc.Right, doc.Top); } status = ct.Go(); ++col; if (col > 1) { col = 0; doc.NewPage(); } } } if (!hasRows) { if (!pageSetStarted) { StartPageSet(lasto); } doc.Add(new Paragraph("no members as of this meeting date and time to show on rollsheet")); } doc.Close(); }
// Public Methods (1) /// <summary> /// Wrapping an element in multiple columns per page. /// </summary> /// <param name="element">The element to wrap</param> public void Wrap(IElement element) { var count = 0; float l = 0; var columnsWidth = PageSetup.MultipleColumnsPerPage.ColumnsWidth; var columnsMargin = PageSetup.MultipleColumnsPerPage.ColumnsGap; var columnsPerPage = PageSetup.MultipleColumnsPerPage.ColumnsPerPage - 1; var r = columnsWidth; var isRtl = PageSetup.MultipleColumnsPerPage.IsRightToLeft; var startNewPage = false; if (PageSetup.PagePreferences.RunDirection == null) { PageSetup.PagePreferences.RunDirection = PdfRunDirection.LeftToRight; } var ct = new ColumnText(PdfWriter.DirectContent) { RunDirection = (int)PageSetup.PagePreferences.RunDirection }; ct.AddElement(element); var top = PdfDoc.Top - CurrentRowInfoData.HeaderHeight - PageSetup.MultipleColumnsPerPage.TopMargin; var status = 0; // render the column as long as it has content while (ColumnText.HasMoreText(status)) { if (startNewPage) { PdfDoc.NewPage(); } if (isRtl) { ct.SetSimpleColumn( PdfDoc.Right - l, PdfDoc.Bottom, PdfDoc.Right - r, top ); } else { ct.SetSimpleColumn( PdfDoc.Left + l, PdfDoc.Bottom, PdfDoc.Left + r, top ); } l += columnsWidth + columnsMargin; r += columnsWidth + columnsMargin; // render as much content as possible status = ct.Go(); // go to a new page if you've reached the last column if (++count > columnsPerPage) { count = 0; l = 0; r = columnsWidth; startNewPage = true; } else { startNewPage = false; } } }
public Stream GetPdf() { var document = CreateDefaultDocument(); var tocDocument = CreateDefaultDocument(); var stream = new MemoryStream(); _pdfWriter = PdfWriter.GetInstance(document, stream); _pdfWriter.SetLinearPageMode(); var tocStream = new MemoryStream(); var tocWriter = PdfWriter.GetInstance(tocDocument, tocStream); tocWriter.SetLinearPageMode(); var tocEvent = new PdfEvents(tocDocument, RootDirectory); _pdfWriter.PageEvent = tocEvent; _pdfWriter.StrictImageSequence = true; document.Open(); tocDocument.Open(); AddMetaData(document); AddChapters(document); document.Close(); var fontFooter = PdfFonts.Small; var footer = new Phrase(string.Format("{0}: {1}", Documentation.Project.ProjectNumber, Documentation.Name), fontFooter); var pdfReader = new PdfReader(stream.ToArray()); stream = new MemoryStream(); var stamper = new PdfStamper(pdfReader, stream); var tableOfContents = GenerateTableOfContents(tocEvent, stamper, 0); tocDocument.Add(tableOfContents); tocDocument.Close(); var tocReader = new PdfReader(tocStream.ToArray()); var tocSize = tocReader.NumberOfPages; var toc = new ColumnText(null); var frontPage = new ColumnText(null); var hasFrontPage = Documentation.DocumentationChapters.Any(dc => dc.Chapter is GeneratedChapter && dc.Chapter.Name == "Forside"); tableOfContents = GenerateTableOfContents(tocEvent, stamper, tocSize + (hasFrontPage ? 2 : 0)); toc.AddElement(tableOfContents); var page = stamper.GetImportedPage(pdfReader, 1); int currentPage = 0; while (true) { stamper.InsertPage(++currentPage, pdfReader.GetPageSize(1)); stamper.GetUnderContent(currentPage).AddTemplate(page, 0, 0); toc.Canvas = stamper.GetOverContent(currentPage); toc.SetSimpleColumn(60, 72, PageSize.A4.Width - 60, PageSize.A4.Height - 72); if (!ColumnText.HasMoreText(toc.Go())) { break; } } if (hasFrontPage) { frontPage.AddElement(new FrontPageBuilder(Documentation, RootDirectory).GetContent()); page = stamper.GetImportedPage(pdfReader, 1); currentPage = 0; while (true) { stamper.InsertPage(++currentPage, pdfReader.GetPageSize(1)); stamper.GetUnderContent(currentPage).AddTemplate(page, 0, 0); frontPage.Canvas = stamper.GetOverContent(currentPage); frontPage.SetSimpleColumn(60, 72, PageSize.A4.Width - 60, PageSize.A4.Height - 72); if (!ColumnText.HasMoreText(frontPage.Go())) { break; } } stamper.InsertPage(++currentPage, pdfReader.GetPageSize(1)); stamper.GetUnderContent(currentPage).AddTemplate(page, 0, 0); } int totalPages = pdfReader.NumberOfPages; for (int i = 3; i <= totalPages; ++i) { var canvas = stamper.GetOverContent(i); var table = new PdfPTable(2); var rotation = stamper.Reader.GetPageRotation(i); table.SetWidths(new[] { 10, 1 }); table.TotalWidth = (rotation == 0 ? PageSize.A4.Width : PageSize.A4.Height) - 130; table.DefaultCell.Border = Rectangle.NO_BORDER; table.DefaultCell.FixedHeight = 20; table.DefaultCell.HorizontalAlignment = Element.ALIGN_LEFT; table.AddCell(footer); table.DefaultCell.HorizontalAlignment = Element.ALIGN_RIGHT; table.AddCell(new Phrase(i.ToString(CultureInfo.InvariantCulture), fontFooter)); table.WriteSelectedRows(0, -1, 0, -1, 60, 40, canvas); } stamper.Close(); var outStream = new MemoryStream(stream.ToArray()); return(outStream); }
public static string CreatePDF2(DatosComprobante dt, Comprobante comprobante, string rutaPDF, string nombrePDF) { //*** Copia el recurso embebido en un directorio temporal , cuando se le envíe la plantilla del pdf en la dll // ContentLoading.GetPDFEmbedded(); //*** Esto hay que activar cuando el pdf esté compilado en la librería try { var boldTableFont = FontFactory.GetFont("Arial", 9, iTextSharp.text.Font.BOLD); var bodyFont = FontFactory.GetFont("Arial", 10, iTextSharp.text.Font.NORMAL); //*** Configuración de directorios para los diferentes formatos string carpetaPrincipal = Properties.Settings.Default.PathDefecto; string carpetaFormatosFacturas = Properties.Settings.Default.DeFacturas; string formatoPDFCabecera = Properties.Settings.Default.EsteFormatoFacturaCabecera; string formatoPDFDetalles = Properties.Settings.Default.EsteFormatoFacturaDetalles; string formatoPDFTotales = Properties.Settings.Default.EsteFormatoFacturaTotales; string carpetaGeneradasFacturas = Properties.Settings.Default.FacturasGeneradas; string rutaCompleta = carpetaPrincipal + carpetaFormatosFacturas + @"\" + formatoPDFCabecera; string rutaCompleta_1 = carpetaPrincipal + carpetaFormatosFacturas + @"\" + formatoPDFDetalles; string rutaCompleta_2 = carpetaPrincipal + carpetaFormatosFacturas + @"\" + formatoPDFTotales; string nombreFacturaGenerada = Properties.Settings.Default.ArchivoTemporal; string nuevaFacturaCompleta = carpetaPrincipal + carpetaGeneradasFacturas + @"\" + nombreFacturaGenerada; // estos dos archivos, se eliminan al terminar el proceso string detalletemporal = carpetaPrincipal + carpetaGeneradasFacturas + @"\detalle_temporal.pdf"; string totalestemporal = carpetaPrincipal + carpetaGeneradasFacturas + @"\totales_temporal.pdf"; //*** Esto se activa cuando el pdf está dentro de la librería //string fileNameExisting = ContentLoading.CrearCarpetaTemporal("modelo_facturaFinal.pdf"); //*** Va junto con la opción de arriba string fileNameExisting = rutaCompleta; string fileNameExisting_1 = rutaCompleta_1; string fileNameExisting_2 = rutaCompleta_2; //*** Archivo resultante temporal string fileNameNew = nuevaFacturaCompleta; //*** estos dos archivos, se eliminan al terminar el proceso string fileNameNew_1 = detalletemporal; string fileNameNew_2 = totalestemporal; //*** Proceso de estampado de la cabecera del documento using (var existingFileStream = new FileStream(fileNameExisting, FileMode.Open)) using (var newFileStream = new FileStream(fileNameNew, FileMode.Create)) { // Open existing PDF PdfReader pdfReader = new PdfReader(existingFileStream); Rectangle pagesize = pdfReader.GetPageSize(1); // PdfStamper, which will create PdfStamper stamper = new PdfStamper(pdfReader, newFileStream); var form = stamper.AcroFields; //var fieldKeys = form.Fields.Keys; var imagepath = comprobante.archivo; using (FileStream fs = new FileStream(imagepath, FileMode.Open)) { var png = iTextSharp.text.Image.GetInstance(System.Drawing.Image.FromStream(fs), System.Drawing.Imaging.ImageFormat.Png); png.Alignment = iTextSharp.text.Image.ALIGN_RIGHT; png.SetAbsolutePosition(41, 1010); png.ScaleAbsoluteHeight(100); png.ScaleAbsoluteWidth(365); PdfContentByte over = null; over = stamper.GetOverContent(1); // 1 = página over.AddImage(png); } //*** mapeo de datos de la factura ESTAMPADO DE LOS DATOS EN LA PLANTILLA //*** TECNOLOGÍA ACROFIELDS form.SetField("RUC", dt.Ruc); form.SetField("NROFACTURA", comprobante.codDoc); form.SetField("NROAUTORIZACION", dt.numeroAutorizacion); form.SetField("AMBIENTE", dt.ambiente); form.SetField("EMISION", dt.estado); form.SetField("CLAVEACCESONUMEROS", dt.numeroAutorizacion); //***mapeo de datos de la empresa form.SetField("NOMBREEMPRESA", "ComputerEC"); form.SetField("DIRECCION1EMPRESA", "Calle Homero Salas OE5-148 y Altar"); form.SetField("DIRECCION2EMPRESA", "Sector del Antiguo Aeropuerto"); form.SetField("DESCRIPCION1EMPRESA", "Teléfonos: 0983833901 0991324900"); form.SetField("DESCRIPCION2EMPRESA", "Horarios: Lun-Vie 08:00 a 18:00"); //***mapeo de los datos del cliente //***ESTOS DATOS //form.SetField("RazonSocial", comprobante.Comprobante.razonSocial); //form.SetField("FechaEmision", comprobante.Comprobante.fechaEmision); //form.SetField("Identificacion", comprobante.Comprobante.ruc); #region Detalles PdfPTable itemTable = new PdfPTable(9); itemTable.HorizontalAlignment = 0; itemTable.WidthPercentage = 146; itemTable.SpacingBefore = 10f; itemTable.SpacingAfter = 10f; itemTable.SetWidths(new float[] { 3f, /*3f,*/ 2f, 6f, 4f, 4f, 4f, 3f, 3f, 3f }); // then set the column's __relative__ widths itemTable.DefaultCell.Border = Rectangle.BOX; // VALIDACION DE LOS CAMPOS QUE SE GENERAN EN EL PDF PdfPCell cell1 = new PdfPCell(new Phrase(new Chunk("Cod.Principal", boldTableFont))); cell1.HorizontalAlignment = 1; itemTable.AddCell(cell1); //PdfPCell cell2 = new PdfPCell(new Phrase(new Chunk("Cod.Auxiliar", boldTableFont))); //cell2.HorizontalAlignment = 1; //itemTable.AddCell(cell2); PdfPCell cell3 = new PdfPCell(new Phrase(new Chunk("Cantidad", boldTableFont))); cell3.HorizontalAlignment = 1; itemTable.AddCell(cell3); PdfPCell cell4 = new PdfPCell(new Phrase(new Chunk("Descripcion", boldTableFont))); cell4.HorizontalAlignment = 1; itemTable.AddCell(cell4); PdfPCell cell5 = new PdfPCell(new Phrase(new Chunk("Det.Adicional1", boldTableFont))); cell5.HorizontalAlignment = 1; itemTable.AddCell(cell5); PdfPCell cell6 = new PdfPCell(new Phrase(new Chunk("Det.Adicional2", boldTableFont))); cell6.HorizontalAlignment = 1; itemTable.AddCell(cell6); PdfPCell cell7 = new PdfPCell(new Phrase(new Chunk("Det.Adicional3", boldTableFont))); cell7.HorizontalAlignment = 1; itemTable.AddCell(cell7); PdfPCell cell8 = new PdfPCell(new Phrase(new Chunk("ValorUnit", boldTableFont))); cell8.HorizontalAlignment = 1; itemTable.AddCell(cell8); PdfPCell cell9 = new PdfPCell(new Phrase(new Chunk("Descuento", boldTableFont))); cell9.HorizontalAlignment = 1; itemTable.AddCell(cell9); PdfPCell cell10 = new PdfPCell(new Phrase(new Chunk("PrecioTotal", boldTableFont))); cell10.HorizontalAlignment = 1; itemTable.AddCell(cell10); itemTable.HeaderRows = 1; foreach (DetalleComprobante fila in comprobante.detalles) { itemTable.AddCell(fila.codigoPrincipal.ToString()); //itemTable.AddCell(fila.codigoAuxiliar.ToString()); itemTable.AddCell(fila.cantidad.ToString()); itemTable.AddCell(fila.descripcion.ToString()); itemTable.AddCell(fila.detalleadicional1.ToString()); itemTable.AddCell(fila.detalleadicional2.ToString()); itemTable.AddCell(fila.detalleadicional3.ToString()); itemTable.AddCell(fila.precioUnitario.ToString()); itemTable.AddCell(fila.descuento.ToString()); itemTable.AddCell(fila.totalSinImpueto.ToString()); } ColumnText column = new ColumnText(stamper.GetOverContent(1)); Rectangle rectPage1 = new Rectangle(43, 36, 559, 856); // POSICIÓN DONDE INICIA LA TABLA column.SetSimpleColumn(rectPage1); column.AddElement(itemTable); int pagecount = 1; Rectangle rectPage2 = new Rectangle(43, 36, 559, 1000); // 1000 = POSICIÓN DEL TITULO DE LA TABLA EN CADA PÁGINA int status = column.Go(); while (ColumnText.HasMoreText(status)) { status = triggerNewPage(stamper, pagesize, column, rectPage2, ++pagecount); } #endregion itemTable.SpacingBefore = 20; altotal = itemTable.TotalHeight; stamper.FormFlattening = true; //stamper.FreeTextFlattening = true; stamper.Close(); pdfReader.Close(); } //*** Proceso de estampado de los totales del documento en otro PDF using (var existingFileStream = new FileStream(fileNameExisting_2, FileMode.Open)) using (var newFileStream = new FileStream(fileNameNew_2, FileMode.Create)) { // Open existing PDF PdfReader pdfReader = new PdfReader(existingFileStream); // PdfStamper, which will create PdfStamper stamper = new PdfStamper(pdfReader, newFileStream); var form = stamper.AcroFields; var fieldKeys = form.Fields.Keys; //*** mapeo de datos de la factura form.SetField("SUBTOTAL12", comprobante.totalConImpuestos.ToString()); form.SetField("SUBTOTALCERO", ""); form.SetField("SUBTOTALNOIVA", ""); form.SetField("SUBTOTALEXCENTO", ""); form.SetField("SUBTOTALSINIMPUESTOS", comprobante.totalSinImpuetos.ToString()); form.SetField("TOTALDESCUENTO", comprobante.totalDescuento.ToString()); form.SetField("ICE", ""); form.SetField("VALORIVA", ""); form.SetField("IRBPNR", ""); form.SetField("PROPINA", comprobante.propina.ToString()); form.SetField("VALORTOTAL", comprobante.importeTotal.ToString()); stamper.FormFlattening = true; //stamper.FreeTextFlattening = true; stamper.Close(); pdfReader.Close(); } // SE ACTIVA CUANDO SE REQUIERA HACER EL PROCESO EN MEMORIA //List<byte[]> fbytes = new List<byte[]>(); //MemoryStream ms = GenerarRIDE.CreatePDF1Stream(fileNameNew); //ms.Position = 0; //fbytes.Add(ms.ToArray()); //ms = GenerarRIDE.CreatePDF1Stream(fileNameNew_1); //ms.Position = 0; //fbytes.Add(ms.ToArray()); //ms = GenerarRIDE.CreatePDF1Stream(fileNameNew_2); //ms.Position = 0; //fbytes.Add(ms.ToArray()); //MemoryStream PDFData = new MemoryStream(); ////*** Se guarda el archivo generado ////string fileNameNew = nuevaFacturaCompleta; //PDFData = new MemoryStream(concatAndAddContent(fbytes)); // une los 3 archivos //PDFData.Position = 0; ////MemoryStream ms1 = GenerarRIDE.CreatePDF1Stream(final3); ////ms1.Position = 0; //SavePDFFile(final3, PDFData); // Merge de archivos #region MergePDF //altotal 856 float y = -altotal - 250; // obteniendo las rutas string src = rutaPDF + "archivotemporal.pdf"; string src1 = rutaPDF + "totales_temporal.pdf"; string final = rutaPDF + nombrePDF; PdfReader reader = new PdfReader(src); PdfStamper stamper1 = new PdfStamper(reader, new FileStream(final, FileMode.Create)); PdfContentByte canvas = stamper1.GetUnderContent(1); PdfReader r; PdfImportedPage page; PdfReader s_reader = new PdfReader(src1); Rectangle pageSize = reader.GetPageSize(1); int n = reader.NumberOfPages; for (int i = 1; i <= n; i++) { r = new PdfReader(src1); page = stamper1.GetImportedPage(r, 1); canvas.AddTemplate(page, 0, y); //float x float y stamper1.Writer.FreeReader(r); r.Close(); } stamper1.Close(); s_reader.Close(); reader.Close(); return("True"); #endregion } catch (Exception e0) { return("No se generó el PDF : " + e0.Message); } }
public void TestSplitLateAndSplitRow1() { String filename = "testSplitLateAndSplitRow1.pdf"; Document doc = new Document(PageSize.LETTER, 72f, 72f, 72f, 72f); PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(outFolder + filename, FileMode.Create)); doc.Open(); PdfContentByte canvas = writer.DirectContent; ColumnText ct = new ColumnText(canvas); StringBuilder text = new StringBuilder(); for (int i = 0; i < 21; ++i) { text.Append(i).Append("\n"); } // Add a table with a single row and column that doesn't fit on one page PdfPTable t = new PdfPTable(1); t.SplitLate = true; t.SplitRows = true; t.WidthPercentage = 100f; ct.AddElement( new Paragraph( "Pushing table down\ndown\ndown\ndown\ndown\ndown\ndown\ndown\ndown\ndown\ndown\ndown\ndown\ndown\ndown\ndown\ndown\ndown\ndown\ndown\n")); PdfPCell c = new PdfPCell(); c.HorizontalAlignment = Element.ALIGN_LEFT; c.VerticalAlignment = Element.ALIGN_TOP; c.Border = Rectangle.NO_BORDER; c.BorderWidth = 0; c.Padding = 0; c.AddElement(new Paragraph(text.ToString())); t.AddCell(c); ct.AddElement(t); int status = 0; while (ColumnText.HasMoreText(status)) { ct.SetSimpleColumn(doc.Left, doc.Bottom, doc.Right, doc.Top); status = ct.Go(); if (ColumnText.HasMoreText(status)) { doc.NewPage(); } } doc.Close(); String errorMessage = new CompareTool().CompareByContent(outFolder + filename, cmpFolder + filename, outFolder, "diff"); if (errorMessage != null) { Assert.Fail(errorMessage); } }
public static bool CreatePdf(Stream output, Config config) { using (MemoryStream ms = new MemoryStream()) { using (Document document = new Document(PageSize.LETTER)) using (PdfWriter writer = PdfWriter.GetInstance(document, ms)) { document.AddTitle($"{config.website} - {config.title}"); document.AddAuthor($"{config.website}"); document.AddSubject(config.title); document.AddKeywords($"{config.keywords}"); document.AddCreator($"{config.creator}"); document.AddCreationDate(); document.AddLanguage("en"); document.Open(); document.SetPageSize(PageSize.LETTER); float w = document.PageSize.Width - document.LeftMargin - document.RightMargin; float h = document.PageSize.Height - document.TopMargin - document.BottomMargin; float headerInfoHeight = 68; float headerHeight = h / 16; float headerImageHeight = headerHeight + document.TopMargin + headerInfoHeight; float headerImageWidth = (headerImageHeight * 640.0f) / 480.0f; float headerWidth = w - headerImageWidth; float headerTitleHeight = headerImageHeight - headerInfoHeight; Rectangle[] bodyLayoutRects = new Rectangle[] { // // Page 1 // new Rectangle(0, 0, 0, 0), new Rectangle(0, 0, 0, 0), // // Page 2+ // new Rectangle(0, 0, 0, 0), new Rectangle(0, 0, 0, 0), // // Footer // new Rectangle(0, 0, 0, 0), }; Font fontTitle = new Font(Font.FontFamily.HELVETICA, 16, Font.BOLD, BaseColor.DARK_GRAY); Font fontPrimaryInfo = new Font(Font.FontFamily.HELVETICA, 8, Font.BOLD, BaseColor.DARK_GRAY); Font fontSecondaryInfo = new Font(Font.FontFamily.HELVETICA, 8, Font.NORMAL, BaseColor.DARK_GRAY); Font fontFooter = new Font(Font.FontFamily.HELVETICA, 6, Font.NORMAL, BaseColor.GRAY); Font fontBodyNormal = new Font(Font.FontFamily.HELVETICA, 8, Font.NORMAL, BaseColor.BLACK); Font fontBodyHeader = new Font(Font.FontFamily.HELVETICA, 12, Font.BOLD, BaseColor.DARK_GRAY); Font fontBodyHeaderMinor = new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD, BaseColor.DARK_GRAY); bodyLayoutRects[2].Left = bodyLayoutRects[0].Left = document.LeftMargin; bodyLayoutRects[1].Top = bodyLayoutRects[0].Top = document.TopMargin; bodyLayoutRects[2].Right = bodyLayoutRects[0].Right = bodyLayoutRects[0].Left + ((w / 2) - (document.LeftMargin / 2)); bodyLayoutRects[1].Bottom = bodyLayoutRects[0].Bottom = bodyLayoutRects[0].Top + (h - (headerImageHeight - document.TopMargin / 2.0f)); bodyLayoutRects[3].Left = bodyLayoutRects[1].Left = document.LeftMargin + (w / 2) + (document.LeftMargin / 2); bodyLayoutRects[3].Right = bodyLayoutRects[1].Right = bodyLayoutRects[1].Left + ((w / 2) - (document.LeftMargin)); bodyLayoutRects[3].Top = bodyLayoutRects[2].Top = document.TopMargin; bodyLayoutRects[3].Bottom = bodyLayoutRects[2].Bottom = bodyLayoutRects[2].Top + (h - (document.TopMargin / 2.0f)); bodyLayoutRects[4].Left = document.LeftMargin; bodyLayoutRects[4].Right = w; bodyLayoutRects[4].Top = 0; bodyLayoutRects[4].Bottom = document.TopMargin / 2; Rectangle[] headerLayoutRects = new Rectangle[] { // // Title // new Rectangle(0, 0, 0, 0), // // Info // new Rectangle(0, 0, 0, 0), }; headerLayoutRects[0].Left = document.LeftMargin; headerLayoutRects[0].Top = document.PageSize.Height - (headerTitleHeight + document.TopMargin / 2); headerLayoutRects[0].Right = headerLayoutRects[0].Left + headerWidth; headerLayoutRects[0].Bottom = headerLayoutRects[0].Top + headerTitleHeight; headerLayoutRects[1].Left = document.LeftMargin; headerLayoutRects[1].Top = document.PageSize.Height - headerImageHeight + 4; headerLayoutRects[1].Right = headerLayoutRects[1].Left + headerWidth; headerLayoutRects[1].Bottom = headerLayoutRects[1].Top + headerInfoHeight; // // Cover Image // System.Drawing.Image sysCoverImage = CreateCoverImage(config.imageUrl, config.overlayUrl, headerImageWidth * 4, headerImageHeight * 4); if (sysCoverImage != null) { iTextSharp.text.Image coverImage = iTextSharp.text.Image.GetInstance(sysCoverImage, System.Drawing.Imaging.ImageFormat.Jpeg); if (coverImage != null) { coverImage.SetAbsolutePosition(document.PageSize.Width - headerImageWidth, document.PageSize.Height - headerImageHeight); coverImage.ScaleToFit(headerImageWidth, headerImageHeight); document.Add(coverImage); } } ColumnText ct = new ColumnText(writer.DirectContent); // // Title // { Paragraph p = new Paragraph(); p.Alignment = Element.ALIGN_CENTER; p.Font = fontTitle; p.Add(config.title); ct.AddElement(p); p = new Paragraph(); p.Alignment = Element.ALIGN_CENTER; p.Font = fontPrimaryInfo; p.Add(config.subHeader1); ct.AddElement(p); ct.SetSimpleColumn(headerLayoutRects[0]); ct.Go(); } // // Info // { Paragraph p = new Paragraph(); p.Alignment = Element.ALIGN_CENTER; p.Font = fontSecondaryInfo; Html2PdfContext ctxSubHeader = new Html2PdfContext() { defaultFontSize = fontSecondaryInfo.Size, defaultAlignment = Element.ALIGN_CENTER, bodyFont = fontSecondaryInfo, bodyFontHeader = fontSecondaryInfo, bodyFontHeaderMinor = fontSecondaryInfo, }; List <IElement> elementsNutrition = ParseHTML(config.subHeader2, ctxSubHeader); foreach (IElement el in elementsNutrition) { if (el is Paragraph) { ((Paragraph)el).Alignment = Element.ALIGN_CENTER; } ct.AddElement(el); } ct.SetSimpleColumn(headerLayoutRects[1]); ct.Alignment = Element.ALIGN_CENTER; ct.Go(); } Html2PdfContext ctx = new Html2PdfContext() { defaultFontSize = fontBodyNormal.Size, bodyFont = fontBodyNormal, bodyFontHeader = fontBodyHeader, bodyFontHeaderMinor = fontBodyHeaderMinor, }; List <IElement> elements = ParseHTML(config.body, ctx); foreach (IElement el in elements) { ct.AddElement(el); } int c = 0; int status = 0; while (ColumnText.HasMoreText(status)) { ct.SetSimpleColumn(bodyLayoutRects[c]); status = ct.Go(); ++c; if (c == 2) { ColumnText.ShowTextAligned(writer.DirectContentUnder, Element.ALIGN_CENTER, new Phrase(config.footer, fontFooter), (bodyLayoutRects[4].Left + bodyLayoutRects[4].Right) / 2, bodyLayoutRects[4].Bottom - (fontFooter.Size / 2), 0); document.NewPage(); } else if (c == 4) { ColumnText.ShowTextAligned(writer.DirectContentUnder, Element.ALIGN_CENTER, new Phrase(config.footer, fontFooter), (bodyLayoutRects[4].Left + bodyLayoutRects[4].Right) / 2, bodyLayoutRects[4].Bottom - (fontFooter.Size / 2), 0); document.NewPage(); c = 2; } } // // needed to ensure we dont access the stream // document.Close(); } MemoryStream msReadFrom = new MemoryStream(ms.GetBuffer()); EncryptPdf(msReadFrom, output); } return(true); }
private void DrawOverlayText(PdfContentByte canvas, IList <Rectangle> textRectangles, PdfString overlayText, PdfString otDA, PdfNumber otQ, PdfBoolean otRepeat) { ColumnText ct = new ColumnText(canvas); ct.SetLeading(0, 1.2F); ct.UseAscender = true; String otStr = overlayText.ToUnicodeString(); canvas.SaveState(); IDictionary <string, IList <object> > parsedDA = ParseDAParam(otDA); Font font = null; if (parsedDA.ContainsKey(STROKE_COLOR)) { IList <object> strokeColorArgs = parsedDA[STROKE_COLOR]; SetStrokeColor(canvas, strokeColorArgs); } if (parsedDA.ContainsKey(FILL_COLOR)) { IList <object> fillColorArgs = parsedDA[FILL_COLOR]; SetFillColor(canvas, fillColorArgs); } if (parsedDA.ContainsKey("Tf")) { IList <object> tfArgs = parsedDA["Tf"]; font = RetrieveFontFromAcroForm((PdfName)tfArgs[0], (PdfNumber)tfArgs[1]); } foreach (Rectangle textRect in textRectangles) { ct.SetSimpleColumn(textRect); if (otQ != null) { ct.Alignment = otQ.IntValue; } Phrase otPhrase; if (font != null) { otPhrase = new Phrase(otStr, font); } else { otPhrase = new Phrase(otStr); } float y = ct.YLine; if (otRepeat != null && otRepeat.BooleanValue) { int status = ct.Go(true); while (!ColumnText.HasMoreText(status)) { otPhrase.Add(otStr); ct.SetText(otPhrase); ct.YLine = y; status = ct.Go(true); } } ct.SetText(otPhrase); ct.YLine = y; ct.Go(); } canvas.RestoreState(); }
public void StandardMethod(Stream stream, CMSDataContext db, IEnumerable <ContributorInfo> q, StatementSpecification cs, int set = 0) { pageEvents.set = set; pageEvents.PeopleId = 0; var contributors = q; var toDate = ToDate.Date.AddHours(24).AddSeconds(-1); 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(); var dc = w.DirectContent; var prevfid = 0; var runningtotals = UUId.HasValue ? db.ContributionsRuns.Where(mm => mm.UUId == UUId).SingleOrDefault() : null; if (runningtotals != null) { 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, cs.Funds).ToList(); var pledges = APIContribution.Pledges(db, ci, toDate, cs.Funds).ToList(); var giftsinkind = APIContribution.GiftsInKind(db, ci, FromDate, toDate, cs.Funds).ToList(); var nontaxitems = db.Setting("DisplayNonTaxOnStatement", "false").ToBool() ? APIContribution.NonTaxItems(db, ci, FromDate, toDate, cs.Funds).ToList() : new List <NonTaxContribution>(); if ((contributions.Count + pledges.Count + giftsinkind.Count + nontaxitems.Count) == 0) { if (runningtotals != null) { 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) { TotalWidth = 72f * 5f }; t1.DefaultCell.Border = Rectangle.NO_BORDER; string nameOfChurch = db.Setting("NameOfChurch", "Name of Church"); string startAddress = db.Setting("StartAddress", "Start Address"); string churchPhone = db.Setting("ChurchPhone", "(000) 000-0000"); var html1 = cs.Header ?? db.ContentHtml("StatementHeader", string.Format(Resource1.ContributionStatementHeader, nameOfChurch, startAddress, churchPhone)); var html2 = cs.Notice ?? db.ContentHtml("StatementNotice", string.Format(Resource1.ContributionStatementNotice, nameOfChurch)); 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); } } t1.AddCell(cell); t1.AddCell("\n"); var t1a = new PdfPTable(1) { 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 }; ae.AddCell(cell); cell = new PdfPCell(t1a.DefaultCell); cell.AddElement(ae); t1a.AddCell(ae); //-----Notice var t2 = new PdfPTable(1) { TotalWidth = 72f * 3f }; t2.DefaultCell.Border = Rectangle.NO_BORDER; var envno = ""; if (db.Setting("PrintEnvelopeNumberOnStatement")) { var ev = Person.GetExtraValue(db, ci.PeopleId, "EnvelopeNumber"); var s = Util.PickFirst(ev.Data, ev.IntValue.ToString(), ev.StrValue); if (s.HasValue()) { envno = $"env: {s}"; } } t2.AddCell(db.Setting("NoPrintDateOnStatement") ? new Phrase($"\nid:{ci.PeopleId}{envno} {ci.CampusId}", font) : new Phrase($"\nprinted: {DateTime.Now:d} id:{ci.PeopleId}{envno} {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); var gutter = 20f; if (NumberOfColumns == 1) { gutter = 0; } var colwidth = (doc.Right - doc.Left - gutter) / NumberOfColumns; var t = (NumberOfColumns == 2) ? new PdfPTable(new[] { 18f, 24f, 15f }) : new PdfPTable(new[] { 18f, 25f, 15f, 15f, 30f }) { WidthPercentage = 100 }; t.DefaultCell.Border = Rectangle.NO_BORDER; t.HeaderRows = 2; cell = new PdfPCell(t.DefaultCell) { Colspan = (NumberOfColumns == 2) ? 3 : 5, 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) { HorizontalAlignment = Element.ALIGN_RIGHT, Phrase = new Phrase("Amount", boldfont) }; t.AddCell(cell); if (NumberOfColumns == 1) { cell = new PdfPCell(t.DefaultCell) { HorizontalAlignment = Element.ALIGN_CENTER, Phrase = ShowCheckNo ? new Phrase("Check No", boldfont) : new Phrase("", boldfont) }; t.AddCell(cell); t.AddCell(ShowNotes ? new Phrase("Notes", boldfont) : new Phrase("", boldfont)); } t.DefaultCell.Border = Rectangle.NO_BORDER; var total = 0m; foreach (var c in contributions) { t.AddCell(new Phrase(c.ContributionDate.ToString2("d"), font)); t.AddCell(new Phrase(GetFundDisplayText(db, () => c.FundName, () => c.FundDescription), font)); cell = new PdfPCell(t.DefaultCell) { HorizontalAlignment = Element.ALIGN_RIGHT, Phrase = new Phrase(c.ContributionAmount.ToString2("N2"), font) }; t.AddCell(cell); if (NumberOfColumns == 1) { cell = new PdfPCell(t.DefaultCell) { HorizontalAlignment = Element.ALIGN_CENTER, Phrase = ShowCheckNo ? new Phrase(c.CheckNo, font) : new Phrase("", font) }; t.AddCell(cell); t.AddCell(ShowNotes ? new Phrase(c.Description?.Trim() ?? "", font) : new Phrase("", font)); } total += (c.ContributionAmount ?? 0); } t.DefaultCell.Border = Rectangle.TOP_BORDER; cell = new PdfPCell(t.DefaultCell) { Colspan = 2, Phrase = new Phrase("Total Contributions for period", boldfont) }; t.AddCell(cell); cell = new PdfPCell(t.DefaultCell) { HorizontalAlignment = Element.ALIGN_RIGHT, Phrase = new Phrase(total.ToString("N2"), font) }; t.AddCell(cell); if (NumberOfColumns == 1) { cell = new PdfPCell(t.DefaultCell) { Colspan = 2, Phrase = new Phrase("") }; t.AddCell(cell); } ct.AddElement(t); //------Pledges if (pledges.Count > 0) { t = new PdfPTable((NumberOfColumns == 1) ? new[] { 25f, 15f, 15f, 15f, 30f } : new[] { 16f, 12f, 12f }) { WidthPercentage = 100, HeaderRows = 2, }; t.DefaultCell.Border = Rectangle.NO_BORDER; cell = new PdfPCell(t.DefaultCell) { Colspan = (NumberOfColumns == 1) ? 5 : 3, 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) { HorizontalAlignment = Element.ALIGN_RIGHT, Phrase = new Phrase("Pledge", boldfont) }; t.AddCell(cell); cell = new PdfPCell(t.DefaultCell) { HorizontalAlignment = Element.ALIGN_RIGHT, Phrase = new Phrase("Given", boldfont) }; t.AddCell(cell); t.DefaultCell.Border = Rectangle.NO_BORDER; if (NumberOfColumns == 1) { t.AddCell(new Phrase("", boldfont)); t.AddCell(new Phrase("", boldfont)); } foreach (var c in pledges) { t.AddCell(new Phrase(GetFundDisplayText(db, () => c.FundName, () => c.FundDescription), font)); cell = new PdfPCell(t.DefaultCell) { HorizontalAlignment = Element.ALIGN_RIGHT, Phrase = new Phrase(c.Pledged.ToString2("N2"), font) }; t.AddCell(cell); cell = new PdfPCell(t.DefaultCell) { HorizontalAlignment = Element.ALIGN_RIGHT, Phrase = new Phrase(c.Given.ToString2("N2"), font) }; t.AddCell(cell); if (NumberOfColumns == 1) { t.AddCell(new Phrase("", boldfont)); t.AddCell(new Phrase("", boldfont)); } } ct.AddElement(t); } //------Gifts In Kind if (giftsinkind.Count > 0) { t = new PdfPTable((NumberOfColumns == 1) ? new[] { 18f, 25f, 15f, 15f, 30f } : new[] { 12f, 18f, 20f }); t.WidthPercentage = 100; t.DefaultCell.Border = Rectangle.NO_BORDER; t.HeaderRows = 2; // Headers cell = new PdfPCell(t.DefaultCell) { Colspan = (NumberOfColumns == 1) ? 5 : 3, 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) { Phrase = new Phrase("Fund", boldfont) }; t.AddCell(cell); cell = new PdfPCell(t.DefaultCell) { Phrase = new Phrase("Description", boldfont) }; t.AddCell(cell); if (NumberOfColumns == 1) { t.AddCell(new Phrase("", boldfont)); t.AddCell(new Phrase("", boldfont)); } t.DefaultCell.Border = Rectangle.NO_BORDER; foreach (var c in giftsinkind) { t.AddCell(new Phrase(c.ContributionDate.ToString2("d"), font)); cell = new PdfPCell(t.DefaultCell) { Phrase = new Phrase(GetFundDisplayText(db, () => c.FundName, () => c.FundDescription), font) }; t.AddCell(cell); cell = new PdfPCell(t.DefaultCell) { Colspan = (NumberOfColumns == 1) ? 3 : 1, Phrase = new Phrase(c.Description, font) }; t.AddCell(cell); } ct.AddElement(t); } //-----Summary t = new PdfPTable((NumberOfColumns == 1) ? new[] { 40f, 15f, 45f } : new[] { 29f, 9f }); t.WidthPercentage = 100; t.DefaultCell.Border = Rectangle.NO_BORDER; t.HeaderRows = 2; cell = new PdfPCell(t.DefaultCell) { Colspan = (NumberOfColumns == 1) ? 3 : 2, 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) { HorizontalAlignment = Element.ALIGN_RIGHT, Phrase = new Phrase("Amount", boldfont) }; t.AddCell(cell); t.DefaultCell.Border = Rectangle.NO_BORDER; if (NumberOfColumns == 1) { t.AddCell(new Phrase("", boldfont)); } foreach (var c in APIContribution.GiftSummary(db, ci, FromDate, toDate, cs.Funds)) { t.AddCell(new Phrase(GetFundDisplayText(db, () => c.FundName, () => c.FundDescription), font)); cell = new PdfPCell(t.DefaultCell) { HorizontalAlignment = Element.ALIGN_RIGHT, Phrase = new Phrase(c.Total.ToString2("N2"), font) }; t.AddCell(cell); if (NumberOfColumns == 1) { t.AddCell(new Phrase("", boldfont)); } } t.DefaultCell.Border = Rectangle.TOP_BORDER; t.AddCell(new Phrase("Total contributions for period", boldfont)); cell = new PdfPCell(t.DefaultCell) { HorizontalAlignment = Element.ALIGN_RIGHT, Phrase = new Phrase(total.ToString("N2"), font) }; t.AddCell(cell); if (NumberOfColumns == 1) { cell = new PdfPCell(t.DefaultCell) { Phrase = new Phrase("") }; t.AddCell(cell); } ct.AddElement(t); //------NonTax if (nontaxitems.Count > 0) { t = new PdfPTable((NumberOfColumns == 1) ? new[] { 18f, 25f, 15f, 15f, 30f } : new[] { 18f, 24f, 15f }); t.WidthPercentage = 100; t.DefaultCell.Border = Rectangle.NO_BORDER; t.HeaderRows = 2; cell = new PdfPCell(t.DefaultCell) { Colspan = (NumberOfColumns == 1) ? 5 : 3, 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) { HorizontalAlignment = Element.ALIGN_RIGHT, Phrase = new Phrase("Amount", boldfont) }; t.AddCell(cell); if (NumberOfColumns == 1) { t.AddCell(new Phrase("", boldfont)); t.AddCell(new Phrase("", boldfont)); } t.DefaultCell.Border = Rectangle.NO_BORDER; var ntotal = 0m; foreach (var c in nontaxitems) { t.AddCell(new Phrase(c.ContributionDate.ToString2("d"), font)); t.AddCell(new Phrase(GetFundDisplayText(db, () => c.FundName, () => c.FundDescription), font)); cell = new PdfPCell(t.DefaultCell) { HorizontalAlignment = Element.ALIGN_RIGHT, Phrase = new Phrase(c.ContributionAmount.ToString2("N2"), font) }; t.AddCell(cell); if (NumberOfColumns == 1) { t.AddCell(new Phrase("", boldfont)); t.AddCell(ShowNotes ? new Phrase(c.Description, font) : new Phrase("", font)); } ntotal += (c.ContributionAmount ?? 0); } t.DefaultCell.Border = Rectangle.TOP_BORDER; cell = new PdfPCell(t.DefaultCell) { Colspan = 2, Phrase = new Phrase("Total Non Tax-Deductible Items for period", boldfont) }; t.AddCell(cell); cell = new PdfPCell(t.DefaultCell) { HorizontalAlignment = Element.ALIGN_RIGHT, Phrase = new Phrase(ntotal.ToString("N2"), font) }; t.AddCell(cell); if (NumberOfColumns == 1) { t.AddCell(new Phrase("", boldfont)); t.AddCell(new Phrase("", boldfont)); } ct.AddElement(t); } var col = 0; var status = 0; while (ColumnText.HasMoreText(status)) { switch (col) { case 0: ct.SetSimpleColumn(doc.Left, doc.Bottom, doc.Left + colwidth, pos); break; case 1: ct.SetSimpleColumn(doc.Right - colwidth, doc.Bottom, doc.Right, pos); break; } status = ct.Go(); if (NumberOfColumns == 2) { ++col; if (col <= 1) { continue; } col = 0; } pos = doc.Top; doc.NewPage(); } if (runningtotals != null) { 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 = "https://docs.touchpointsoftware.com/Finance/ContributionStatements.html#troubleshooting" }; doc.Add(a); } doc.Close(); if (set == LastSet() && runningtotals != null) { runningtotals.Completed = DateTime.Now; } db.SubmitChanges(); }
public void Run(Stream stream, CMSDataContext db, IEnumerable <ContributorInfo> q, ContributionStatements.StatementSpecification cs, int set = 0) { pageEvents.set = set; pageEvents.PeopleId = 0; var contributors = q; 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).FirstOrDefault(); 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, cs.Funds).ToList(); var pledges = APIContribution.Pledges(db, ci, ToDate, cs.Funds).ToList(); var giftsinkind = APIContribution.GiftsInKind(db, ci, FromDate, ToDate, cs.Funds).ToList(); var nontaxitems = db.Setting("DisplayNonTaxOnStatement", "false").ToBool() ? APIContribution.NonTaxItems(db, ci, FromDate, ToDate, cs.Funds).ToList() : new List <NonTaxContribution>(); 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; var mh = new MyHandler(); using (var sr = new StringReader(css + cs.Header)) 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; var envno = ""; if (db.Setting("PrintEnvelopeNumberOnStatement")) { var ev = Person.GetExtraValue(db, ci.PeopleId, "EnvelopeNumber"); var s = Util.PickFirst(ev.Data, ev.IntValue.ToString(), ev.StrValue); if (s.HasValue()) { envno = $" env: {Util.PickFirst(ev.Data, ev.IntValue.ToString(), ev.StrValue)}"; } } t2.AddCell(db.Setting("NoPrintDateOnStatement") ? new Phrase($"\nid:{ci.PeopleId}{envno} {ci.CampusId}", font) : new Phrase($"\nprinted: {DateTime.Now:d} id:{ci.PeopleId}{envno} {ci.CampusId}", font)); t2.AddCell(""); var mh2 = new MyHandler(); using (var sr = new StringReader(css + cs.Notice)) 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); var colwidth = (doc.Right - doc.Left); var t = new PdfPTable(new[] { 15f, 25f, 15f, 15f, 30f }); t.WidthPercentage = 100; t.DefaultCell.Border = Rectangle.NO_BORDER; t.HeaderRows = 2; cell = new PdfPCell(t.DefaultCell); cell.Colspan = 5; 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); cell = new PdfPCell(t.DefaultCell); cell.HorizontalAlignment = Element.ALIGN_CENTER; if (ShowCheckNo) { cell.Phrase = new Phrase("Check No", boldfont); } else { cell.Phrase = new Phrase("", boldfont); } t.AddCell(cell); if (ShowNotes) { t.AddCell(new Phrase("Notes", boldfont)); } else { t.AddCell(new Phrase("", boldfont)); } t.DefaultCell.Border = Rectangle.NO_BORDER; var total = 0m; foreach (var c in contributions) { t.AddCell(new Phrase(c.ContributionDate.ToString2("d"), font)); t.AddCell(new Phrase(c.FundName, font)); cell = new PdfPCell(t.DefaultCell); cell.HorizontalAlignment = Element.ALIGN_RIGHT; cell.Phrase = new Phrase(c.ContributionAmount.ToString2("N2"), font); t.AddCell(cell); cell = new PdfPCell(t.DefaultCell); cell.HorizontalAlignment = Element.ALIGN_CENTER; if (ShowCheckNo) { cell.Phrase = new Phrase(c.CheckNo, font); } else { cell.Phrase = new Phrase("", font); } t.AddCell(cell); if (ShowNotes) { t.AddCell(new Phrase(c.Description.trim(), font)); } else { t.AddCell(new Phrase("", font)); } total += (c.ContributionAmount ?? 0); } 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); cell = new PdfPCell(t.DefaultCell); cell.Colspan = 2; cell.Phrase = new Phrase(""); t.AddCell(cell); ct.AddElement(t); //------Pledges if (pledges.Count > 0) { t = new PdfPTable(new[] { 25f, 15f, 15f, 15f, 30f }); t.WidthPercentage = 100; t.DefaultCell.Border = Rectangle.NO_BORDER; t.HeaderRows = 2; cell = new PdfPCell(t.DefaultCell); cell.Colspan = 5; 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; t.AddCell(new Phrase("", boldfont)); t.AddCell(new Phrase("", boldfont)); foreach (var c in pledges) { t.AddCell(new Phrase(c.FundName, font)); cell = new PdfPCell(t.DefaultCell); cell.HorizontalAlignment = Element.ALIGN_RIGHT; cell.Phrase = new Phrase(c.Pledged.ToString2("N2"), font); t.AddCell(cell); cell = new PdfPCell(t.DefaultCell); cell.HorizontalAlignment = Element.ALIGN_RIGHT; cell.Phrase = new Phrase(c.Given.ToString2("N2"), font); t.AddCell(cell); t.AddCell(new Phrase("", boldfont)); t.AddCell(new Phrase("", boldfont)); } ct.AddElement(t); } //------Gifts In Kind if (giftsinkind.Count > 0) { t = new PdfPTable(new[] { 15f, 25f, 15f, 15f, 30f }); t.WidthPercentage = 100; t.DefaultCell.Border = Rectangle.NO_BORDER; t.HeaderRows = 2; // Headers cell = new PdfPCell(t.DefaultCell); cell.Colspan = 5; 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.AddCell(new Phrase("", boldfont)); t.AddCell(new Phrase("", boldfont)); t.DefaultCell.Border = Rectangle.NO_BORDER; foreach (var c in giftsinkind) { t.AddCell(new Phrase(c.ContributionDate.ToString2("d"), font)); cell = new PdfPCell(t.DefaultCell); cell.Phrase = new Phrase(c.FundName, font); t.AddCell(cell); cell = new PdfPCell(t.DefaultCell); cell.Colspan = 3; cell.Phrase = new Phrase(c.Description, font); t.AddCell(cell); } ct.AddElement(t); } //-----Summary t = new PdfPTable(new[] { 40f, 15f, 45f }); 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\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; t.AddCell(new Phrase("", boldfont)); foreach (var c in APIContribution.GiftSummary(db, ci, FromDate, ToDate, cs.Funds)) { t.AddCell(new Phrase(c.FundName, font)); cell = new PdfPCell(t.DefaultCell); cell.HorizontalAlignment = Element.ALIGN_RIGHT; cell.Phrase = new Phrase(c.Total.ToString2("N2"), font); t.AddCell(cell); t.AddCell(new Phrase("", boldfont)); } t.DefaultCell.Border = Rectangle.NO_BORDER; cell = new PdfPCell(t.DefaultCell); cell.Border = Rectangle.TOP_BORDER; cell.Colspan = 1; cell.Phrase = new Phrase("Total Contributions for period", boldfont); t.AddCell(cell); cell = new PdfPCell(t.DefaultCell); cell.Border = Rectangle.TOP_BORDER; cell.HorizontalAlignment = Element.ALIGN_RIGHT; cell.Phrase = new Phrase(total.ToString("N2"), font); t.AddCell(cell); cell = new PdfPCell(t.DefaultCell); cell.Phrase = new Phrase(""); t.AddCell(cell); ct.AddElement(t); //------NonTax if (nontaxitems.Count > 0) { t = new PdfPTable(new[] { 15f, 25f, 15f, 15f, 30f }); t.WidthPercentage = 100; t.DefaultCell.Border = Rectangle.NO_BORDER; t.HeaderRows = 2; cell = new PdfPCell(t.DefaultCell); cell.Colspan = 5; 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.AddCell(new Phrase("", boldfont)); t.AddCell(new Phrase("", boldfont)); t.DefaultCell.Border = Rectangle.NO_BORDER; var ntotal = 0m; foreach (var c in nontaxitems) { t.AddCell(new Phrase(c.ContributionDate.ToString2("d"), font)); t.AddCell(new Phrase(c.FundName, font)); cell = new PdfPCell(t.DefaultCell); cell.HorizontalAlignment = Element.ALIGN_RIGHT; cell.Phrase = new Phrase(c.ContributionAmount.ToString2("N2"), font); t.AddCell(cell); t.AddCell(new Phrase("", boldfont)); if (ShowNotes) { t.AddCell(new Phrase(c.Description, font)); } else { t.AddCell(new Phrase("", font)); } ntotal += (c.ContributionAmount ?? 0); } 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); t.AddCell(new Phrase("", boldfont)); t.AddCell(new Phrase("", boldfont)); ct.AddElement(t); } var status = 0; while (ColumnText.HasMoreText(status)) { ct.SetSimpleColumn(doc.Left, doc.Bottom, doc.Left + colwidth, pos); status = ct.Go(); 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(); }
public override void ExecuteResult(ControllerContext context) { var Response = context.HttpContext.Response; CmsData.Meeting meeting = null; if (meetingid.HasValue) { meeting = DbUtil.Db.Meetings.Single(mt => mt.MeetingId == meetingid); dt = meeting.MeetingDate; orgid = meeting.OrganizationId; } var list1 = bygroup == true?ReportList2().ToList() : ReportList().ToList(); if (!list1.Any()) { Response.Write("no data found"); return; } if (!dt.HasValue) { Response.Write("bad date"); return; } Response.ContentType = "application/pdf"; Response.AddHeader("content-disposition", "filename=foo.pdf"); doc = new Document(PageSize.LETTER.Rotate(), 36, 36, 64, 64); var w = PdfWriter.GetInstance(doc, Response.OutputStream); w.PageEvent = pageEvents; doc.Open(); dc = w.DirectContent; box = new PdfPCell(); box.Border = PdfPCell.NO_BORDER; box.CellEvent = new CellEvent(); PdfPTable table = null; OrgInfo lasto = null; foreach (var o in list1) { lasto = o; table = new PdfPTable(1); table.DefaultCell.Border = PdfPCell.NO_BORDER; table.DefaultCell.Padding = 0; table.WidthPercentage = 100; if (meeting != null) { var Groups = o.Groups; if (Groups[0] == 0) { var q = from at in meeting.Attends where at.AttendanceFlag == true || at.Commitment == AttendCommitmentCode.Attending || at.Commitment == AttendCommitmentCode.Substitute orderby at.Person.LastName, at.Person.FamilyId, at.Person.Name2 select new { at.MemberType.Code, Name2 = (altnames == true && at.Person.AltName != null && at.Person.AltName.Length > 0) ? at.Person.AltName : at.Person.Name2, at.PeopleId, at.Person.DOB, }; if (q.Any()) { StartPageSet(o); } foreach (var a in q) { table.AddCell(AddRow(a.Code, a.Name2, a.PeopleId, a.DOB, "", font)); } } else { var q = from at in meeting.Attends let om = at.Organization.OrganizationMembers.SingleOrDefault(mm => mm.PeopleId == at.PeopleId) let gc = om.OrgMemMemTags.Count(mt => Groups.Contains(mt.MemberTagId)) where gc == Groups.Length || Groups[0] <= 0 where gc > 0 where !Groups.Contains(-1) || (Groups.Contains(-1) && om.OrgMemMemTags.Count() == 0) where at.AttendanceFlag == true || at.Commitment == AttendCommitmentCode.Attending || at.Commitment == AttendCommitmentCode.Substitute orderby at.Person.LastName, at.Person.FamilyId, at.Person.Name2 select new { at.MemberType.Code, Name2 = (altnames == true && at.Person.AltName != null && at.Person.AltName.Length > 0) ? at.Person.AltName : at.Person.Name2, at.PeopleId, at.Person.DOB, }; if (q.Any()) { StartPageSet(o); } foreach (var a in q) { table.AddCell(AddRow(a.Code, a.Name2, a.PeopleId, a.DOB, "", font)); } } } else { var Groups = o.Groups; if (Groups == null) { Groups = new int[] { 0 } } ; var q = from om in DbUtil.Db.OrganizationMembers where om.OrganizationId == o.OrgId let gc = om.OrgMemMemTags.Count(mt => Groups.Contains(mt.MemberTagId)) where gc == Groups.Length || Groups[0] <= 0 where !Groups.Contains(-1) || (Groups.Contains(-1) && om.OrgMemMemTags.Count() == 0) where (om.Pending ?? false) == false where om.MemberTypeId != MemberTypeCode.InActive where om.MemberTypeId != MemberTypeCode.Prospect where om.EnrollmentDate <= Util.Now orderby om.Person.LastName, om.Person.FamilyId, om.Person.Name2 let p = om.Person let ch = altnames == true && p.AltName != null && p.AltName.Length > 0 select new { PeopleId = p.PeopleId, Name2 = ch ? p.AltName : p.Name2, BirthDate = Util.FormatBirthday( p.BirthYear, p.BirthMonth, p.BirthDay), MemberTypeCode = om.MemberType.Code, ch, highlight = om.OrgMemMemTags.Any(mm => mm.MemberTag.Name == highlightsg) ? highlightsg : "" }; if (q.Any()) { StartPageSet(o); } foreach (var m in q) { table.AddCell(AddRow(m.MemberTypeCode, m.Name2, m.PeopleId, m.BirthDate, m.highlight, m.ch ? china : font)); } } if (bygroup == false && groups[0] == 0 && meeting == null) { foreach (var m in RollsheetModel.FetchVisitors(o.OrgId, dt.Value, NoCurrentMembers: true, UseAltNames: altnames == true)) { if (table.Rows.Count == 0) { StartPageSet(o); } table.AddCell(AddRow(m.VisitorType, m.Name2, m.PeopleId, m.BirthDate, "", boldfont)); } } if (!pageSetStarted) { continue; } var col = 0; float gutter = 20f; float colwidth = (doc.Right - doc.Left - gutter) / 2; var ct = new ColumnText(w.DirectContent); ct.AddElement(table); int status = 0; while (ColumnText.HasMoreText(status)) { if (col == 0) { ct.SetSimpleColumn(doc.Left, doc.Bottom, doc.Left + colwidth, doc.Top); } else { ct.SetSimpleColumn(doc.Right - colwidth, doc.Bottom, doc.Right, doc.Top); } status = ct.Go(); ++col; if (col > 1) { col = 0; doc.NewPage(); } } // foreach (var li in list) // { // y = ct.YLine; // ct.AddElement(li); // status = ct.Go(true); // if (ColumnText.HasMoreText(status)) // { // ++col; // if (col > 1) // { // col = 0; // doc.NewPage(); // } // ct.SetSimpleColumn(cols[col]); // y = doc.Top; // } // ct.YLine = y; // ct.SetText(null); // ct.AddElement(li); // status = ct.Go(); // } } if (!hasRows) { if (!pageSetStarted) { StartPageSet(lasto); } doc.Add(new Paragraph("no members as of this meeting date and time to show on rollsheet")); } doc.Close(); }