public static void exportDashboard(string project, string user, string channel, string title, HttpResponse oResponse) { Document document = new Document(new iTextSharp.text.Rectangle(1618, 1250), 80, 80, 20, 25); PdfWriter pdfDoc = PdfWriter.GetInstance(document, oResponse.OutputStream); document.Open(); /* Headers */ document.AddTitle(title); document.AddCreator("MedHealth Solutions."); document.AddKeywords("Document generated by MedHealth Solutions. online portal."); document.AddHeader("Company Name", "MedHealth Solutions."); document.AddHeader("Creation Date", DateTime.Now.ToLongDateString()); document.AddHeader("Creation Time", DateTime.Now.ToLongTimeString()); //create iTextSharp.text Image object using local image path iTextSharp.text.Image logo = iTextSharp.text.Image.GetInstance(HttpRuntime.AppDomainAppPath + "\\imgs\\pdf\\logo.png"); ////pdfDoc.Add(logo); //document.Add(logo); //////////////////////////////////////////////////////////////////////////// // Page 2 //////////////////////////////////////////////////////////////////////////// PdfPTable pdfTabHeader = new PdfPTable(2); PdfPCell pdfCellRight = new PdfPCell(new Paragraph("\n" + title, new Font(Font.FontFamily.HELVETICA, 40, 0))); PdfPCell pdfCellLeft = new PdfPCell(logo); pdfCellRight.HorizontalAlignment = Element.ALIGN_RIGHT; pdfCellLeft.HorizontalAlignment = Element.ALIGN_LEFT; pdfCellRight.Border = 0; pdfCellLeft.Border = 0; pdfTabHeader.AddCell(pdfCellLeft); pdfTabHeader.AddCell(pdfCellRight); pdfTabHeader.TotalWidth = document.PageSize.Width - 60; pdfTabHeader.WriteSelectedRows(0, -1, 30, document.PageSize.Height - 20, pdfDoc.DirectContent); PdfContentByte cb = pdfDoc.DirectContent; cb.MoveTo(1, pdfDoc.PageSize.Height - 115); cb.LineTo(pdfDoc.PageSize.Width, pdfDoc.PageSize.Height - 115); cb.Stroke(); cb.MoveTo(1, 50); cb.LineTo(pdfDoc.PageSize.Width, 50); cb.Stroke(); PdfPTable pdfTabFooter = new PdfPTable(2); PdfPCell pdfCellRightF = new PdfPCell(new Paragraph("Printed on " + DateTime.Now.ToString("MM-dd-yyyy HH:mm"), new Font(Font.FontFamily.HELVETICA, 14, 0))); PdfPCell pdfCellLeftF = new PdfPCell(new Paragraph("©" + DateTime.Now.ToString("yyyy") + " MedHealth", new Font(Font.FontFamily.HELVETICA, 14, 0))); pdfCellRightF.HorizontalAlignment = Element.ALIGN_RIGHT; pdfCellLeftF.HorizontalAlignment = Element.ALIGN_LEFT; pdfCellRightF.Border = 0; pdfCellLeftF.Border = 0; pdfTabFooter.AddCell(pdfCellLeftF); pdfTabFooter.AddCell(pdfCellRightF); pdfTabFooter.TotalWidth = document.PageSize.Width - 60; pdfTabFooter.WriteSelectedRows(0, -1, 25, 48, pdfDoc.DirectContent); document.Add(new Paragraph("\n\n\n", new Font(Font.FontFamily.HELVETICA, 25, 0))); if (File.Exists(Path.Combine(HttpRuntime.AppDomainAppPath, "charts\\RAP_" + project + "_" + user + "_" + channel + ".png"))) { document.Add(new Paragraph("Retrospective Progress", new Font(Font.FontFamily.HELVETICA, 25, 0))); iTextSharp.text.Image imRAP = iTextSharp.text.Image.GetInstance(Path.Combine(HttpRuntime.AppDomainAppPath, "charts\\RAP_" + project + "_" + user + "_" + channel + ".png")); document.Add(imRAP); } if (File.Exists(Path.Combine(HttpRuntime.AppDomainAppPath, "charts\\RSBD_" + project + "_" + user + "_" + channel + ".png"))) { document.Add(new Paragraph("Burn Down of Retrospective Pursuit", new Font(Font.FontFamily.HELVETICA, 25, 0))); iTextSharp.text.Image imRSBD = iTextSharp.text.Image.GetInstance(Path.Combine(HttpRuntime.AppDomainAppPath, "charts\\RSBD_" + project + "_" + user + "_" + channel + ".png")); document.Add(imRSBD); } if (File.Exists(Path.Combine(HttpRuntime.AppDomainAppPath, "charts\\OSCS_" + project + "_" + user + "_" + channel + ".png"))) { document.Add(new Paragraph("Office Schedule and Contact Status", new Font(Font.FontFamily.HELVETICA, 25, 0))); document.Add(new Paragraph(" ", new Font(Font.FontFamily.HELVETICA, 10, 0))); PdfPTable pdfOSCS = new PdfPTable(3); iTextSharp.text.Image imOSCS1 = iTextSharp.text.Image.GetInstance(Path.Combine(HttpRuntime.AppDomainAppPath, "charts\\OSCS_" + project + "_" + user + "_" + channel + ".png")); PdfPCell pdfOSCS1 = new PdfPCell(imOSCS1); pdfOSCS1.Border = 0; pdfOSCS.AddCell(pdfOSCS1); if (File.Exists(Path.Combine(HttpRuntime.AppDomainAppPath, "charts\\OSCSD1_" + project + "_" + user + "_" + channel + ".png"))) { iTextSharp.text.Image imOSCS2 = iTextSharp.text.Image.GetInstance(Path.Combine(HttpRuntime.AppDomainAppPath, "charts\\OSCSD1_" + project + "_" + user + "_" + channel + ".png")); PdfPCell pdfOSCS2 = new PdfPCell(imOSCS2); pdfOSCS2.Border = 0; pdfOSCS.AddCell(pdfOSCS2); } else { PdfPCell pdfOSCS2 = new PdfPCell(new Paragraph(" ")); pdfOSCS2.Border = 0; pdfOSCS.AddCell(pdfOSCS2); } if (File.Exists(Path.Combine(HttpRuntime.AppDomainAppPath, "charts\\OSCSD2_" + project + "_" + user + "_" + channel + ".png"))) { iTextSharp.text.Image imOSCS3 = iTextSharp.text.Image.GetInstance(Path.Combine(HttpRuntime.AppDomainAppPath, "charts\\OSCSD2_" + project + "_" + user + "_" + channel + ".png")); PdfPCell pdfOSCS3 = new PdfPCell(imOSCS3); pdfOSCS3.Border = 0; pdfOSCS.AddCell(pdfOSCS3); } else { PdfPCell pdfOSCS3 = new PdfPCell(new Paragraph(" ")); pdfOSCS3.Border = 0; pdfOSCS.AddCell(pdfOSCS3); } document.Add(pdfOSCS); } //////////////////////////////////////////////////////////////////////////// // Page 2 //////////////////////////////////////////////////////////////////////////// document.NewPage(); pdfTabHeader.WriteSelectedRows(0, -1, 30, document.PageSize.Height - 20, pdfDoc.DirectContent); cb.MoveTo(1, pdfDoc.PageSize.Height - 115); cb.LineTo(pdfDoc.PageSize.Width, pdfDoc.PageSize.Height - 115); cb.Stroke(); cb.MoveTo(1, 50); cb.LineTo(pdfDoc.PageSize.Width, 50); cb.Stroke(); pdfTabFooter.WriteSelectedRows(0, -1, 25, 48, pdfDoc.DirectContent); document.Add(new Paragraph("\n\n\n", new Font(Font.FontFamily.HELVETICA, 25, 0))); if (File.Exists(Path.Combine(HttpRuntime.AppDomainAppPath, "charts\\QA_" + project + "_" + user + "_" + channel + ".png"))) { document.Add(new Paragraph("Coding Quality Assurance (QA)", new Font(Font.FontFamily.HELVETICA, 25, 0))); document.Add(new Paragraph(" ", new Font(Font.FontFamily.HELVETICA, 10, 0))); PdfPTable pdfQA = new PdfPTable(2); iTextSharp.text.Image imQA1 = iTextSharp.text.Image.GetInstance(Path.Combine(HttpRuntime.AppDomainAppPath, "charts\\QA_" + project + "_" + user + "_" + channel + ".png")); PdfPCell pdfQA1 = new PdfPCell(imQA1); pdfQA1.Border = 0; pdfQA.AddCell(pdfQA1); if (File.Exists(Path.Combine(HttpRuntime.AppDomainAppPath, "charts\\QAD_" + project + "_" + user + "_" + channel + ".png"))) { iTextSharp.text.Image imQA2 = iTextSharp.text.Image.GetInstance(Path.Combine(HttpRuntime.AppDomainAppPath, "charts\\QAD_" + project + "_" + user + "_" + channel + ".png")); PdfPCell pdfQA2 = new PdfPCell(imQA2); pdfQA2.Border = 0; pdfQA.AddCell(pdfQA2); } document.Add(pdfQA); } if (File.Exists(Path.Combine(HttpRuntime.AppDomainAppPath, "charts\\RSVS_" + project + "_" + user + "_" + channel + ".png"))) { document.Add(new Paragraph("Validation Status", new Font(Font.FontFamily.HELVETICA, 25, 0))); document.Add(new Paragraph(" ", new Font(Font.FontFamily.HELVETICA, 10, 0))); PdfPTable pdfRSVS = new PdfPTable(2); iTextSharp.text.Image imRSVS1 = iTextSharp.text.Image.GetInstance(Path.Combine(HttpRuntime.AppDomainAppPath, "charts\\RSVS_" + project + "_" + user + "_" + channel + ".png")); PdfPCell pdfRSVS1 = new PdfPCell(imRSVS1); pdfRSVS1.Border = 0; pdfRSVS.AddCell(pdfRSVS1); //if (File.Exists(HttpRuntime.AppDomainAppPath + "charts\\RSVD_" + project + "_" + user + "_" + channel + ".png")) //{ // iTextSharp.text.Image imRSVS2 = iTextSharp.text.Image.GetInstance(HttpRuntime.AppDomainAppPath + "charts\\RSVD_" + project + "_" + user + "_" + channel + ".png"); // PdfPCell pdfRSVS2 = new PdfPCell(imRSVS2); // pdfRSVS2.Border = 0; // pdfRSVS.AddCell(pdfRSVS2); //} PdfPCell pdfRSVS2 = new PdfPCell(); for (int im = 0; im < 7; im++) { if (File.Exists(Path.Combine(HttpRuntime.AppDomainAppPath, "charts\\RSVD_" + im + "_" + project + "_" + user + "_" + channel + ".png"))) { iTextSharp.text.Image imRSVS2 = iTextSharp.text.Image.GetInstance(HttpRuntime.AppDomainAppPath + "charts\\RSVD_" + im + "_" + project + "_" + user + "_" + channel + ".png"); pdfRSVS2.AddElement(imRSVS2); } } pdfRSVS2.Border = 0; pdfRSVS.AddCell(pdfRSVS2); document.Add(pdfRSVS); } if (File.Exists(Path.Combine(HttpRuntime.AppDomainAppPath, "charts\\RS15H_" + project + "_" + user + "_" + channel + ".png"))) { document.Add(new Paragraph("Top 15 Validated HCC", new Font(Font.FontFamily.HELVETICA, 25, 0))); iTextSharp.text.Image imRS15H = iTextSharp.text.Image.GetInstance(Path.Combine(HttpRuntime.AppDomainAppPath, "charts\\RS15H_" + project + "_" + user + "_" + channel + ".png")); document.Add(imRS15H); } /* Closing and downloading the document*/ document.Close(); oResponse.ContentType = "application/pdf"; oResponse.AddHeader("content-disposition", "attachment;filename=" + title.Replace(" ", "_").Replace(",", "") + ".pdf"); oResponse.End(); }
protected string kreirajPDF(int idProjekta) { Document doc = new Document(iTextSharp.text.PageSize.LETTER, 10, 10, 42, 35); //putanja je hardkodirana PdfWriter wri = PdfWriter.GetInstance(doc, new FileStream(@"C:\Pdf\Investicijski_projekt_ALT" + idProjekta + ".pdf", FileMode.Create)); doc.Open(); FontFactory.RegisterDirectories(); Font fontBoldArial = new Font(FontFactory.GetFont("Arial", 16, Font.BOLD)); FontFactory.RegisterDirectories(); Font fontBoldArial12 = new Font(FontFactory.GetFont("Arial", 12, Font.BOLD)); //putanja je hardkodirana string imagepath = @"C:\Users\Luka\Desktop\HopSamonikBlazek\E-nabava\E-nabava\img\logo.png"; iTextSharp.text.Image slika = iTextSharp.text.Image.GetInstance(imagepath); slika.Alignment = Element.ALIGN_CENTER; doc.Add(slika); Paragraph naslov = new Paragraph("Alternativa investicijskog projekta za Metalsku industriju Varazdin d.d.\n\n", fontBoldArial); naslov.Alignment = Element.ALIGN_CENTER; doc.Add(naslov); DateTime izdavanje = DateTime.Now; Paragraph gore = new Paragraph("Podaci o izmjenjenom investicijskom projektu: \n\n", fontBoldArial12); Paragraph paragraph = new Paragraph( "Naziv projekta: " + txtNazivProjekta.Text + "\n" + "Opis projekta: " + txtOpisProjekta.Text + "\n" + "Izdao: " + Session["korIme"] + "\n" + "Datum izdavanja: " + izdavanje + "\n" + "Rok: " + txtRokProjekta.Text + "\n\n"); string stariNaziv = baza.DohvatiVrijednost("SELECT naziv FROM investicijski_projekt WHERE id_inv_projekt=" + txtIDProjekta.Text); string stariOpis = baza.DohvatiVrijednost("SELECT projekt FROM investicijski_projekt WHERE id_inv_projekt=" + txtIDProjekta.Text); string stariIzdao = baza.DohvatiVrijednost("SELECT izdao FROM investicijski_projekt WHERE id_inv_projekt=" + txtIDProjekta.Text); string stariRok = baza.DohvatiVrijednost("SELECT rok FROM investicijski_projekt WHERE id_inv_projekt=" + txtIDProjekta.Text); Paragraph gore2 = new Paragraph("Podaci o starom investicijskom projektu: \n\n", fontBoldArial12); Paragraph paragraph2 = new Paragraph( "Investicijski_projekt" + txtIDProjekta.Text + "\n" + "Naziv projekta: " + stariNaziv + "\n" + "Opis projekta: " + stariOpis + "\n" + "Izdao: " + stariIzdao + "\n" + "Rok: " + stariRok + "\n\n"); PdfPCell cell = new PdfPCell(); cell.AddElement(gore); cell.AddElement(paragraph); cell.Padding = 0; cell.Border = PdfPCell.NO_BORDER; PdfPCell cellPRazna = new PdfPCell(new Phrase("")); cellPRazna.Padding = 0; cellPRazna.Border = PdfPCell.NO_BORDER; PdfPCell cell2 = new PdfPCell(); cell2.AddElement(gore2); cell2.AddElement(paragraph2); cell2.Padding = 0; cell2.Border = PdfPCell.NO_BORDER; float[] sirine = new float[] { 3f, 1f, 3f }; PdfPTable opisi = new PdfPTable(3); opisi.SetWidths(sirine); opisi.WidthPercentage = 100; opisi.AddCell(cell); opisi.AddCell(cellPRazna); opisi.AddCell(cell2); doc.Add(opisi); Paragraph naslovStavke = new Paragraph("Stavke projekta: \n\n", fontBoldArial); naslovStavke.Alignment = Element.ALIGN_CENTER; doc.Add(naslovStavke); PdfPTable table = new PdfPTable(6); float[] widths = new float[] { 1f, 6f, 2f, 2f, 2f, 2f }; table.SetWidths(widths); table.AddCell(new Phrase("Red. br.")); table.AddCell(new Phrase("Opis stavke")); table.AddCell(new Phrase("Jed. mj.")); table.AddCell(new Phrase("Kolicina")); table.AddCell(new Phrase("Jed. cijena(kn)")); table.AddCell(new Phrase("Iznos (kn)")); table.HeaderRows = 1; table.WidthPercentage = 100; double ukupno = 0; for (int i = 0; i < gwProjekt.Rows.Count; i++) { table.AddCell(new Phrase((i + 1).ToString())); table.AddCell(new Phrase(gwProjekt.Rows[i].Cells[1].Text)); table.AddCell(new Phrase(gwProjekt.Rows[i].Cells[2].Text)); table.AddCell(new Phrase(gwProjekt.Rows[i].Cells[3].Text)); table.AddCell(new Phrase(gwProjekt.Rows[i].Cells[4].Text)); float iznos = float.Parse(gwProjekt.Rows[i].Cells[3].Text) * float.Parse(gwProjekt.Rows[i].Cells[4].Text); table.AddCell(new Phrase(iznos.ToString())); ukupno += iznos; } doc.Add(table); double pdv = ukupno * 0.25; double sveukupno = ukupno + pdv; Paragraph paragraph1 = new Paragraph( "\nUkupno: " + ukupno + " kn\n" + "PDV 25%: " + pdv + " kn\n" + "Sveukupno: " + sveukupno + " kn\n"); doc.Add(paragraph1); doc.Close(); return(@"C:\Pdf\Investicijski_projekt_ALT" + idProjekta + ".pdf"); }
public void exportPdf(DataTable income, DataTable expense, int incomeSum, int expenseSum) { int numberOfIncomeColumns = 2; if (dateCheckbox.Checked) { numberOfIncomeColumns++; } if (monthCheckbox.Checked) { numberOfIncomeColumns++; } if (receivableCheckbox.Checked) { numberOfIncomeColumns++; } int startingBal = apartment.getBalance(); string path = ""; if (saveFileDialog1.ShowDialog() == DialogResult.OK) { path = saveFileDialog1.FileName + ".pdf"; // creating a file object System.IO.FileStream fs = new System.IO.FileStream(path, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.None); Document doc = new Document(); doc.SetPageSize(iTextSharp.text.PageSize.A4); PdfWriter writer = PdfWriter.GetInstance(doc, fs); doc.Open(); // Header Paragraph headingPara = new Paragraph(); BaseFont baseFont = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED); iTextSharp.text.Font headingFont = new iTextSharp.text.Font(baseFont, 22, 1, iTextSharp.text.BaseColor.BLACK); headingPara.Alignment = Element.ALIGN_CENTER; headingPara.Add(new Chunk(this.apartment.getAppartmentName().ToUpper(), headingFont)); doc.Add(headingPara); // Separator Paragraph line = new Paragraph(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(0.0F, 100.0F, iTextSharp.text.BaseColor.BLACK, Element.ALIGN_LEFT, 0))); doc.Add(line); doc.Add(new Chunk("\n")); // INCOME TABLE // Column Heading PdfPTable incomeTable = new PdfPTable(numberOfIncomeColumns); BaseFont columnBaseFont = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED); iTextSharp.text.Font columnFont = new iTextSharp.text.Font(baseFont, 11, 1, iTextSharp.text.BaseColor.WHITE); PdfPCell HeadingCell = new PdfPCell(); HeadingCell.BackgroundColor = iTextSharp.text.BaseColor.GRAY; HeadingCell.HorizontalAlignment = 2; HeadingCell.VerticalAlignment = 2; HeadingCell.HasFixedHeight(); HeadingCell.Colspan = numberOfIncomeColumns; HeadingCell.AddElement(new Chunk("INCOME FOR " + monthBox.SelectedItem.ToString().ToUpper() + " " + yearBox.SelectedItem, columnFont)); incomeTable.AddCell(HeadingCell); for (int i = 0; i < income.Columns.Count; i++) { PdfPCell cell = new PdfPCell(); cell.BackgroundColor = iTextSharp.text.BaseColor.GRAY; cell.HorizontalAlignment = 2; cell.VerticalAlignment = 2; cell.HasFixedHeight(); if (income.Columns[i].ColumnName == "DATE PAID" && !dateCheckbox.Checked) { continue; } if (income.Columns[i].ColumnName == "FOR THE MONTH" && !monthCheckbox.Checked) { continue; } if (income.Columns[i].ColumnName == "RECEIVABLE DUES" && !receivableCheckbox.Checked) { continue; } cell.AddElement(new Chunk(income.Columns[i].ColumnName.ToUpper(), columnFont)); incomeTable.AddCell(cell); } // incomeTable.CompleteRow(); // rows for (int r = 0; r < income.Rows.Count; r++) { for (int c = 0; c < income.Columns.Count; c++) { if (income.Columns[c].ColumnName == "DATE PAID" && !dateCheckbox.Checked) { continue; } if (income.Columns[c].ColumnName == "FOR THE MONTH" && !monthCheckbox.Checked) { continue; } if (income.Columns[c].ColumnName == "RECEIVABLE DUES" && !receivableCheckbox.Checked) { continue; } incomeTable.AddCell(income.Rows[r][c].ToString()); } incomeTable.CompleteRow(); } //EXPENSE TABLE columnFont.Color = iTextSharp.text.BaseColor.WHITE; PdfPTable expenseTable = new PdfPTable(expense.Columns.Count); expenseTable.IsExtendLastRow(true); expenseTable.SetWidths(new float[] { doc.PageSize.Width * 0.2F, doc.PageSize.Width * 0.6F, doc.PageSize.Width * 0.2F }); PdfPCell HeadingCell2 = new PdfPCell(); HeadingCell2.BackgroundColor = iTextSharp.text.BaseColor.GRAY; HeadingCell2.HorizontalAlignment = 2; HeadingCell2.VerticalAlignment = 2; HeadingCell2.HasFixedHeight(); HeadingCell2.Colspan = expense.Columns.Count; HeadingCell2.AddElement(new Chunk("EXPENSES FOR " + monthBox.SelectedItem.ToString().ToUpper() + " " + yearBox.SelectedItem, columnFont)); expenseTable.AddCell(HeadingCell2); for (int i = 0; i < expense.Columns.Count; i++) { PdfPCell cell = new PdfPCell(); cell.BackgroundColor = iTextSharp.text.BaseColor.GRAY; cell.HorizontalAlignment = 2; cell.VerticalAlignment = 2; cell.HasFixedHeight(); cell.AddElement(new Chunk(expense.Columns[i].ColumnName.ToUpper(), columnFont)); expenseTable.AddCell(cell); } // incomeTable.CompleteRow(); // rows for (int r = 0; r < expense.Rows.Count; r++) { for (int c = 0; c < expense.Columns.Count; c++) { expenseTable.AddCell(expense.Rows[r][c].ToString()); } expenseTable.CompleteRow(); } PdfPCell totalExpenseCell = new PdfPCell(); columnFont.Color = iTextSharp.text.BaseColor.BLACK; totalExpenseCell.Colspan = expense.Columns.Count; totalExpenseCell.AddElement(new Chunk("TOTAL EXPENSES = " + expenseSum.ToString(), columnFont)); expenseTable.AddCell(totalExpenseCell); PdfPCell totalIncomeCell = new PdfPCell(); totalIncomeCell.Colspan = numberOfIncomeColumns; totalIncomeCell.AddElement(new Chunk("TOTAL INCOME = " + incomeSum.ToString(), columnFont)); incomeTable.AddCell(totalExpenseCell); doc.Add(incomeTable); doc.NewPage(); doc.Add(expenseTable); // Separator line = new Paragraph(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(0.0F, 100.0F, iTextSharp.text.BaseColor.BLACK, Element.ALIGN_LEFT, 0))); doc.Add(line); doc.Add(new Chunk("\n")); // Closing doc.Add(new Chunk("Starting Balance:\t" + startingBal + " Rs\n")); doc.Add(new Chunk("Total Income:\t" + incomeSum + " Rs\n")); doc.Add(new Chunk("Total Expenses:\t" + expenseSum + " Rs\n")); doc.Add(new Chunk("Closing Balance:\t" + (startingBal + incomeSum - expenseSum) + " Rs\n")); doc.Close(); writer.Close(); fs.Close(); System.Diagnostics.Process.Start(path); } }
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); } }
protected void CreartePdf(double invoiceid, double orderid) { string filname = Server.MapPath("OrderPdf/" + "TSM_Order_" + orderid + ".pdf"); if (System.IO.File.Exists(filname)) { System.IO.File.Delete(filname); } iTextSharp.text.html.simpleparser.StyleSheet styles = new iTextSharp.text.html.simpleparser.StyleSheet(); styles.LoadStyle("wdth20", "width", "30"); styles.LoadStyle("wdth80", "width", "80"); styles.LoadStyle("wdth50", "width", "50"); styles.LoadStyle("wdth140", "width", "140"); styles.LoadStyle("wdth100", "width", "100"); styles.LoadStyle("wdth200", "width", "200"); styles.LoadStyle("wdth400", "width", "400"); styles.LoadStyle("wdth51", "width", "51"); styles.LoadStyle("wdth40", "width", "40"); styles.LoadStyle("wdth60", "width", "60"); styles.LoadStyle("wdth65", "width", "65"); styles.LoadStyle("wdth55", "width", "55"); styles.LoadStyle("hght200", "height", "200"); styles.LoadStyle("border-left", "border-left-width", "1"); styles.LoadStyle("borderright", "BorderWidthRight ", "1f"); //for header StringWriter swheader = new StringWriter(); HtmlTextWriter hwheader = new HtmlTextWriter(swheader); pnlHeader.RenderControl(hwheader); StringReader srheader = new StringReader(swheader.ToString()); PdfPCell cellLeft = new PdfPCell(); StyleSheet style = new StyleSheet(); style.LoadStyle("wdth20", "width", "30"); style.LoadStyle("wdth40", "width", "40"); style.LoadStyle("wdth60", "width", "60"); style.LoadStyle("wdth80", "width", "80"); style.LoadStyle("wdth81", "width", "81"); style.LoadStyle("wdth100", "width", "100"); style.LoadStyle("wdth50", "width", "50"); style.LoadStyle("wdth51", "width", "51"); style.LoadStyle("wdth140", "width", "140"); style.LoadStyle("wdth600", "width", "552"); style.LoadStyle("wdth200", "width", "220"); style.LoadStyle("wdth400", "width", "331"); style.LoadStyle("wdth550", "width", "551"); style.LoadStyle("wdth541", "width", "551"); style.LoadStyle("wdth65", "width", "65"); style.LoadStyle("wdth55", "width", "55"); List <IElement> objects = HTMLWorker.ParseToList(new StringReader(swheader.ToString()), style); //This transforms your HTML to a list of PDF compatible objects for (int k = 0; k < objects.Count; ++k) { cellLeft.AddElement((IElement)objects[k]); //if (k == 1) //{ // cellLeft.FixedHeight = 500f; // cellLeft.GetMaxHeight();//Add these objects to cell one by one //} } //header ends //for content StringWriter sw = new StringWriter(); HtmlTextWriter hw = new HtmlTextWriter(sw); pnlMail.RenderControl(hw); StringReader sr = new StringReader(sw.ToString()); float topmrg = cellLeft.GetMaxHeight() + 22; Document pdfDoc = new Document(PageSize.A4, 22, 22, topmrg, 40); HTMLWorker htmlparser = new HTMLWorker(pdfDoc); htmlparser.SetStyleSheet(styles); PdfWriter writer = PdfWriter.GetInstance(pdfDoc, new FileStream(filname, FileMode.Create)); pdfDoc.Open(); writer.PageEvent = new HeaderFooter(cellLeft); htmlparser.Parse(sr); pdfDoc.Close(); pdfDoc.Dispose(); sr.Close(); sr.Dispose(); srheader.Close(); sr.Dispose(); writer.Close(); writer.Dispose(); Mail(orderid, filname); }
public void Run(Stream stream, CMSDataContext db, IEnumerable <ContributorInfo> q, StatementSpecification cs, 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, 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; 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; 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:M/d/yy} 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); 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.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); 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); 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.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); } 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.ToString2("d"), font)); cell = new PdfPCell(t.DefaultCell); cell.Phrase = new Phrase(c.FundName, 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.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.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.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); 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); 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 MemoryStream GeneratePdfTemplate(GarmentShippingLocalSalesContractViewModel viewModel, int timeoffset) { const int MARGIN = 20; Font header_font_bold_big = FontFactory.GetFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 12); Font header_font_bold = FontFactory.GetFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 10); Font header_font_bold_underlined = FontFactory.GetFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 12, Font.UNDERLINE); Font header_font = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 11); Font normal_font = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 10); Font normal_font_underlined = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 10, Font.UNDERLINE); Font normal_font_bold = FontFactory.GetFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 10); Document document = new Document(PageSize.A4, MARGIN, MARGIN, 120, MARGIN); MemoryStream stream = new MemoryStream(); PdfWriter writer = PdfWriter.GetInstance(document, stream); document.Open(); #region header Paragraph title = new Paragraph("SALES CONTRACT", header_font_bold_underlined); title.Alignment = Element.ALIGN_CENTER; Paragraph no = new Paragraph($"(REF : {viewModel.salesContractNo})", header_font_bold); no.Alignment = Element.ALIGN_CENTER; document.Add(title); document.Add(no); document.Add(new Paragraph("\n", normal_font)); #endregion #region title document.Add(new Paragraph("Kami, yang bertanda tangan di bawah ini : ", normal_font)); document.Add(new Paragraph("\n", normal_font)); PdfPTable tableTitle = new PdfPTable(3); tableTitle.WidthPercentage = 100; tableTitle.SetWidths(new float[] { 3f, 1f, 15f }); PdfPCell cellTitle1 = new PdfPCell() { Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT }; cellTitle1.Phrase = new Phrase("PIHAK PERTAMA ( I )", normal_font); cellTitle1.Colspan = 3; tableTitle.AddCell(cellTitle1); cellTitle1.Phrase = new Phrase("Nama", normal_font); cellTitle1.Colspan = 1; tableTitle.AddCell(cellTitle1); cellTitle1.Phrase = new Phrase(":", normal_font); tableTitle.AddCell(cellTitle1); cellTitle1.Phrase = new Phrase(viewModel.sellerName, normal_font); tableTitle.AddCell(cellTitle1); cellTitle1.Phrase = new Phrase("Jabatan", normal_font); tableTitle.AddCell(cellTitle1); cellTitle1.Phrase = new Phrase(":", normal_font); tableTitle.AddCell(cellTitle1); cellTitle1.Phrase = new Phrase(viewModel.sellerPosition, normal_font); tableTitle.AddCell(cellTitle1); cellTitle1.Phrase = new Phrase("Alamat", normal_font); tableTitle.AddCell(cellTitle1); cellTitle1.Phrase = new Phrase(":", normal_font); tableTitle.AddCell(cellTitle1); cellTitle1.Phrase = new Phrase(viewModel.sellerAddress, normal_font); tableTitle.AddCell(cellTitle1); cellTitle1.Phrase = new Phrase("NPWP", normal_font); tableTitle.AddCell(cellTitle1); cellTitle1.Phrase = new Phrase(":", normal_font); tableTitle.AddCell(cellTitle1); cellTitle1.Phrase = new Phrase(viewModel.sellerNPWP, normal_font); tableTitle.AddCell(cellTitle1); cellTitle1.Phrase = new Phrase("Dalam hal ini Pihak Pertama (I) disebut sebagai pihak PENJUAL", normal_font); cellTitle1.Colspan = 3; tableTitle.AddCell(cellTitle1); cellTitle1.Phrase = new Phrase("\n", normal_font); cellTitle1.Colspan = 3; tableTitle.AddCell(cellTitle1); cellTitle1.Phrase = new Phrase("PIHAK KEDUA ( II )", normal_font); cellTitle1.Colspan = 3; tableTitle.AddCell(cellTitle1); cellTitle1.Phrase = new Phrase("Nama", normal_font); cellTitle1.Colspan = 1; tableTitle.AddCell(cellTitle1); cellTitle1.Phrase = new Phrase(":", normal_font); tableTitle.AddCell(cellTitle1); cellTitle1.Phrase = new Phrase(viewModel.buyer.Name, normal_font); tableTitle.AddCell(cellTitle1); cellTitle1.Phrase = new Phrase("Alamat", normal_font); tableTitle.AddCell(cellTitle1); cellTitle1.Phrase = new Phrase(":", normal_font); tableTitle.AddCell(cellTitle1); cellTitle1.Phrase = new Phrase(viewModel.buyer.Address, normal_font); tableTitle.AddCell(cellTitle1); cellTitle1.Phrase = new Phrase("NPWP", normal_font); tableTitle.AddCell(cellTitle1); cellTitle1.Phrase = new Phrase(":", normal_font); tableTitle.AddCell(cellTitle1); cellTitle1.Phrase = new Phrase(viewModel.buyer.npwp, normal_font); tableTitle.AddCell(cellTitle1); cellTitle1.Phrase = new Phrase("Dalam hal ini Pihak Kedua (II) disebut sebagai PEMBELI", normal_font); cellTitle1.Colspan = 3; tableTitle.AddCell(cellTitle1); tableTitle.SpacingAfter = 10; document.Add(tableTitle); #endregion #region bodyTable document.Add(new Paragraph("Adapun kami, selaku Pihak Pertama (I) dan Pihak Kedua (II) akan melakukan kerjasama dengan ketentuan-ketentuan sebagai berikut : \n", normal_font)); PdfPTable tableBody = new PdfPTable(6); tableBody.WidthPercentage = 100; tableBody.SetWidths(new float[] { 1f, 6f, 2f, 1.5f, 2f, 2.5f }); PdfPCell cellBodyLeft = new PdfPCell() { Border = Rectangle.BOTTOM_BORDER | Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_LEFT }; PdfPCell cellBodyLeftNoBorder = new PdfPCell() { Border = Rectangle.BOTTOM_BORDER | Rectangle.TOP_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_LEFT }; PdfPCell cellBodyRight = new PdfPCell() { Border = Rectangle.BOTTOM_BORDER | Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_RIGHT }; PdfPCell cellBodyRightNoBorder = new PdfPCell() { Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_RIGHT }; PdfPCell cellBodyCenter = new PdfPCell() { Border = Rectangle.BOTTOM_BORDER | Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_CENTER }; cellBodyCenter.Phrase = new Phrase("No", normal_font); tableBody.AddCell(cellBodyCenter); cellBodyCenter.Phrase = new Phrase("Jenis Barang", normal_font); tableBody.AddCell(cellBodyCenter); cellBodyCenter.Phrase = new Phrase("Jumlah", normal_font); tableBody.AddCell(cellBodyCenter); cellBodyCenter.Phrase = new Phrase("Satuan", normal_font); tableBody.AddCell(cellBodyCenter); cellBodyCenter.Phrase = new Phrase("Harga Satuan \nRp", normal_font); tableBody.AddCell(cellBodyCenter); cellBodyCenter.Phrase = new Phrase("Harga Total \nRp", normal_font); tableBody.AddCell(cellBodyCenter); var index = 0; foreach (var item in viewModel.items) { index++; cellBodyCenter.Phrase = new Phrase(index.ToString(), normal_font); tableBody.AddCell(cellBodyCenter); cellBodyLeft.Phrase = new Phrase(item.product.name, normal_font); tableBody.AddCell(cellBodyLeft); cellBodyRight.Phrase = new Phrase(string.Format("{0:n2}", item.quantity), normal_font); tableBody.AddCell(cellBodyRight); cellBodyLeft.Phrase = new Phrase(item.uom.Unit, normal_font); tableBody.AddCell(cellBodyLeft); cellBodyRight.Phrase = new Phrase(string.Format("{0:n2}", item.price), normal_font); tableBody.AddCell(cellBodyRight); cellBodyRight.Phrase = new Phrase(string.Format("{0:n2}", item.price * item.quantity), normal_font); tableBody.AddCell(cellBodyRight); } double totalPrice = viewModel.items.Sum(a => a.quantity * a.price); double ppn = 0; if (viewModel.isUseVat) { ppn = totalPrice * 0.1; } double finalPrice = totalPrice + ppn; cellBodyRightNoBorder.Phrase = new Phrase("Sub Total", normal_font_bold); cellBodyRightNoBorder.Colspan = 5; tableBody.AddCell(cellBodyRightNoBorder); cellBodyRight.Phrase = new Phrase(string.Format("{0:n2}", totalPrice), normal_font); cellBodyRight.Colspan = 5; tableBody.AddCell(cellBodyRight); cellBodyRightNoBorder.Phrase = new Phrase("PPN 10%", normal_font); tableBody.AddCell(cellBodyRightNoBorder); cellBodyRight.Phrase = new Phrase(string.Format("{0:n2}", ppn), normal_font); tableBody.AddCell(cellBodyRight); cellBodyRightNoBorder.Phrase = new Phrase("TOTAL", normal_font); tableBody.AddCell(cellBodyRightNoBorder); cellBodyRight.Phrase = new Phrase(string.Format("{0:n2}", finalPrice), normal_font); tableBody.AddCell(cellBodyRight); tableBody.SpacingAfter = 10; tableBody.SpacingBefore = 5; document.Add(tableBody); #endregion #region sign document.Add(new Paragraph("Demikian surat perjanjian kontrak jual beli barang tersebut dibuat sebagaimana mestinya, \n", normal_font)); document.Add(new Paragraph("harap menjadi perhatian adanya. \n\n", normal_font)); document.Add(new Paragraph("Terima kasih. \n\n", normal_font)); document.Add(new Paragraph($"Sukoharjo, {viewModel.salesContractDate.GetValueOrDefault().ToOffset(new TimeSpan(timeoffset, 0, 0)).ToString("dd MMMM yyyy", new System.Globalization.CultureInfo("id-ID"))}", normal_font)); PdfPTable tableSign = new PdfPTable(2); tableSign.WidthPercentage = 100; tableSign.SetWidths(new float[] { 3f, 1f }); PdfPCell cellBodySignNoBorder = new PdfPCell() { Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT }; PdfPCell cellBodySignNoBorder2 = new PdfPCell() { Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT }; cellBodySignNoBorder.AddElement(new Phrase("Pihak Pertama (I)", normal_font)); cellBodySignNoBorder.AddElement(new Phrase("PT DANLIRIS", normal_font)); cellBodySignNoBorder.AddElement(new Phrase("\n\n\n\n", normal_font)); cellBodySignNoBorder.AddElement(new Phrase(viewModel.sellerName, normal_font_underlined)); cellBodySignNoBorder.AddElement(new Phrase(viewModel.sellerPosition, normal_font)); tableSign.AddCell(cellBodySignNoBorder); cellBodySignNoBorder2.AddElement(new Phrase("Pihak Kedua (II)", normal_font)); cellBodySignNoBorder2.AddElement(new Phrase("\n\n\n\n\n", normal_font)); cellBodySignNoBorder2.AddElement(new Phrase(viewModel.buyer.Name, normal_font_underlined)); cellBodySignNoBorder2.AddElement(new Phrase("Pembeli", normal_font)); tableSign.AddCell(cellBodySignNoBorder2); document.Add(tableSign); #endregion document.Close(); byte[] byteInfo = stream.ToArray(); stream.Write(byteInfo, 0, byteInfo.Length); stream.Position = 0; return(stream); }
public string crearPDF(CartaD v, string spr, bool aprob) { string ruta = ""; using (TruequeEntities db = new TruequeEntities()) { HeaderFooterD hfClass = new HeaderFooterD(v); DateTime fechaCreacion = DateTime.Now; string nombreArchivo = string.Format("{0}.pdf", fechaCreacion.ToString(@"yyyyMMdd") + "_" + fechaCreacion.ToString(@"HHmmss")); string rutaCompleta = HttpContext.Current.Server.MapPath("~/PdfTemp/" + nombreArchivo); FileStream fsDocumento = new FileStream(rutaCompleta, FileMode.Create); //PASO UNO DEMINIMOS EL TIPO DOCUMENTO CON LOS RESPECTIVOS MARGENES (A4,IZQ,DER,TOP,BOT) Document pdfDoc = new Document(PageSize.A4, 30f, 30f, 40f, 100f); PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDoc, fsDocumento); pdfWriter.PageEvent = new HeaderFooterD(); var text = db.TEXTOCVs.Where(x => x.SPRAS_ID == spr); try { pdfDoc.Open(); Paragraph frase1, frase2; if (v.company_x) { frase1 = new Paragraph(v.company, negritaPeque); a = 18; } else { frase1 = new Paragraph("", negritaPeque); a = 0; } if (!aprob) { float fontSize = 250; if (spr == "ES") { fontSize = 165; } float xPosition = 300; float yPosition = 400; float angle = 45; PdfContentByte under = pdfWriter.DirectContentUnder; BaseFont baseFont = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED); under.BeginText(); under.SetColorFill(BaseColor.LIGHT_GRAY); under.SetFontAndSize(baseFont, fontSize); under.ShowTextAligned(PdfContentByte.ALIGN_CENTER, text.Where(x => x.CAMPO == "agua").First().TEXTO, xPosition, yPosition, angle); under.EndText(); } frase1.Alignment = Element.ALIGN_RIGHT; pdfDoc.Add(frase1); pdfDoc.Add(new Chunk("")); if (v.taxid_x) { frase2 = new Paragraph(v.taxid, negritaPeque); b = 18; } else { frase2 = new Paragraph("", negritaPeque); b = 0; } frase2.Alignment = Element.ALIGN_RIGHT; pdfDoc.Add(frase2); r = a + b; //AQUI VA LA LINEA 2 pdfDoc.Add(new Chunk("")); PdfPTable tabColor = new PdfPTable(5); PdfPCell celdaColor = new PdfPCell(new Paragraph("")); PdfPCell celdaColor2 = new PdfPCell(new Paragraph("")); PdfPCell celdaColor3 = new PdfPCell(new Paragraph("")); PdfPCell celdaColor4 = new PdfPCell(new Paragraph("")); PdfPCell celdaColor5 = new PdfPCell(new Paragraph("")); celdaColor.BackgroundColor = new BaseColor(181, 25, 70); celdaColor2.BackgroundColor = new BaseColor(150, 23, 46); celdaColor3.BackgroundColor = new BaseColor(238, 175, 48); celdaColor4.BackgroundColor = new BaseColor(224, 0, 52); celdaColor5.BackgroundColor = new BaseColor(252, 217, 0); celdaColor.FixedHeight = 10f; tabColor.AddCell(celdaColor); tabColor.AddCell(celdaColor2); tabColor.AddCell(celdaColor3); tabColor.AddCell(celdaColor4); tabColor.AddCell(celdaColor5); tabColor.SetWidthPercentage(new float[] { 400, 50, 80, 25, 110 }, PageSize.A4); for (int i = 0; i < tabColor.Rows.Count; i++) { if (i <= 4) { hfClass.quitaBordes(i, tabColor); } } pdfDoc.Add(tabColor); //AQUI EMPIEZA APARTADO DE DATOS pdfDoc.Add(new Chunk("")); tablaDatos1.HorizontalAlignment = Element.ALIGN_LEFT; tablaDatos1.SetWidthPercentage(new float[] { 298, 298 }, PageSize.A4); if (v.concepto_x) { PdfPCell celda1 = new PdfPCell(new Paragraph(v.concepto, negritaPeque)); celda1.Border = 0; tablaDatos1.AddCell(celda1); } else { PdfPCell celda1 = new PdfPCell(new Paragraph("", negritaPeque)); celda1.Border = 0; tablaDatos1.AddCell(celda1); } if (v.folio_x) { PdfPCell celda2 = new PdfPCell(new Paragraph(text.Where(x => x.CAMPO == "folio").Select(x => x.TEXTO).First() + " " + v.folio, negritaPeque)); celda2.HorizontalAlignment = Element.ALIGN_RIGHT; celda2.Border = 0; tablaDatos1.AddCell(celda2); } else { PdfPCell celda2 = new PdfPCell(new Paragraph("", normalPeque)); celda2.HorizontalAlignment = Element.ALIGN_RIGHT; celda2.Border = 0; tablaDatos1.AddCell(celda2); } PdfPCell celdaB1 = new PdfPCell(new Paragraph("\n", negritaPeque)); celdaB1.Border = 0; tablaDatos1.AddCell(celdaB1); PdfPCell celdaB2 = new PdfPCell(new Paragraph("\n", negritaPeque)); celdaB2.Border = 0; tablaDatos1.AddCell(celdaB2); if (v.payerNom_x) { PdfPCell celda3 = new PdfPCell(new Paragraph(v.payerNom, negritaPeque)); celda3.Border = 0; tablaDatos1.AddCell(celda3); } else { PdfPCell celda3 = new PdfPCell(new Paragraph("", normalPeque)); celda3.Border = 0; tablaDatos1.AddCell(celda3); } if (v.lugarFech_x) { PdfPCell celda4 = new PdfPCell(new Paragraph(v.lugarFech, negritaPeque)); celda4.HorizontalAlignment = Element.ALIGN_RIGHT; celda4.Border = 0; tablaDatos1.AddCell(celda4); } else { PdfPCell celda4 = new PdfPCell(new Paragraph("", normalPeque)); celda4.HorizontalAlignment = Element.ALIGN_RIGHT; celda4.Border = 0; tablaDatos1.AddCell(celda4); } if (v.cliente_x) { PdfPCell celda5 = new PdfPCell(new Paragraph(v.cliente, negritaPeque)); celda5.Border = 0; tablaDatos1.AddCell(celda5); } else { PdfPCell celda5 = new PdfPCell(new Paragraph("", negritaPeque)); celda5.Border = 0; tablaDatos1.AddCell(celda5); } if (v.lugar_x) { PdfPCell celda6 = new PdfPCell(new Paragraph(v.lugar, negritaPeque)); celda6.HorizontalAlignment = Element.ALIGN_RIGHT; celda6.Border = 0; tablaDatos1.AddCell(celda6); } else { PdfPCell celda6 = new PdfPCell(new Paragraph("", negritaPeque)); celda6.HorizontalAlignment = Element.ALIGN_RIGHT; celda6.Border = 0; tablaDatos1.AddCell(celda6); } if (v.puesto_x) { PdfPCell celda7 = new PdfPCell(new Paragraph(v.puesto, normalPeque)); celda7.Border = 0; tablaDatos1.AddCell(celda7); } else { PdfPCell celda7 = new PdfPCell(new Paragraph("", normalPeque)); celda7.Border = 0; tablaDatos1.AddCell(celda7); } if (v.payerId_x) { PdfPCell celda8 = new PdfPCell(new Paragraph(text.Where(x => x.CAMPO == "control").Select(x => x.TEXTO).First(), negritaPeque)); celda8.BackgroundColor = new BaseColor(204, 204, 204); tablaDatos1.AddCell(celda8); } else { PdfPCell celda8 = new PdfPCell(new Paragraph("", negritaPeque)); celda8.Border = 0; tablaDatos1.AddCell(celda8); } if (v.direccion_x) { PdfPCell celda9 = new PdfPCell(new Paragraph(v.direccion, normalPeque)); celda9.Border = 0; tablaDatos1.AddCell(celda9); } else { PdfPCell celda9 = new PdfPCell(new Paragraph("", normalPeque)); celda9.Border = 0; tablaDatos1.AddCell(celda9); } if (v.payerId_x) { PdfPCell celda10 = new PdfPCell(new Paragraph(text.Where(x => x.CAMPO == "payer").Select(x => x.TEXTO).First() + " " + v.payerId, normalPeque)); tablaDatos1.AddCell(celda10); } else { PdfPCell celda10 = new PdfPCell(new Paragraph("", normalPeque)); celda10.Border = 0; tablaDatos1.AddCell(celda10); } pdfDoc.Add(tablaDatos1); //APARTIR DE AQUI VA EL ESTIMADO pdfDoc.Add(new Chunk("\n")); Phrase fraseEstimado = new Phrase(); if (v.estimado_x) { fraseEstimado.Add(new Paragraph(text.Where(x => x.CAMPO == "estimado").Select(x => x.TEXTO).First() + " " + v.estimado, negritaPeque)); } else { fraseEstimado.Add(""); } pdfDoc.Add(fraseEstimado); //APARTIR DE AQUI VA LA MECANICA pdfDoc.Add(new Chunk("\n")); pdfDoc.Add(new Chunk("\n")); Phrase miFrase = new Phrase(); if (v.mecanica_x) { miFrase.Add(new Paragraph(v.mecanica, normalPeque)); } else { miFrase.Add(""); } pdfDoc.Add(miFrase); //AQUI COMIENZAN LAS TABLAS //1.- TABLA DE MATERIALES int tablas = v.listaFechas.Count; //SE RECIBE LA N CANTIDAD DE TABLAS A GENERAR int cols = v.numColEncabezado.Count; // SE RECIBE LA CANTIDAD DE COLUMNAS A CONTENER LA TABLA int tamaño = 0; try //B20180720P MGC 2018.07.25 { tamaño = 600 / cols; } catch (Exception) { tamaño = 0; } for (int a = 0; a < tablas; a++) { PdfPTable tablasN = new PdfPTable(cols); if (cols == 1) { tablasN.SetWidthPercentage(new float[] { tamaño }, PageSize.A4); } else if (cols == 2) { tablasN.SetWidthPercentage(new float[] { tamaño, tamaño }, PageSize.A4); } else if (cols == 3) { tablasN.SetWidthPercentage(new float[] { tamaño, tamaño, tamaño }, PageSize.A4); } else if (cols == 4) { tablasN.SetWidthPercentage(new float[] { tamaño, tamaño, tamaño, tamaño }, PageSize.A4); } else if (cols == 5) { tablasN.SetWidthPercentage(new float[] { tamaño, tamaño, tamaño, tamaño, tamaño }, PageSize.A4); } else if (cols == 6) { tablasN.SetWidthPercentage(new float[] { tamaño, tamaño, tamaño, tamaño, tamaño, tamaño }, PageSize.A4); } else if (cols == 7) { tablasN.SetWidthPercentage(new float[] { tamaño, tamaño, tamaño, tamaño, tamaño, tamaño, tamaño }, PageSize.A4); } else if (cols == 8) { tablasN.SetWidthPercentage(new float[] { tamaño, tamaño, tamaño, tamaño, tamaño, tamaño, tamaño, tamaño }, PageSize.A4); } else if (cols == 9) { tablasN.SetWidthPercentage(new float[] { tamaño, tamaño, tamaño, tamaño, tamaño, tamaño, tamaño, tamaño, tamaño }, PageSize.A4); } else if (cols == 10) { tablasN.SetWidthPercentage(new float[] { tamaño, tamaño, tamaño, tamaño, tamaño, tamaño, tamaño, tamaño, tamaño, tamaño }, PageSize.A4); } PdfPCell rangoFecha = new PdfPCell(new Paragraph(text.Where(x => x.CAMPO == "de").Select(x => x.TEXTO).First() + " " + v.listaFechas[a].Remove(10) + " " + text.Where(x => x.CAMPO == "a").Select(x => x.TEXTO).First() + " " + (v.listaFechas[a].Remove(0, v.listaFechas[a].Length / 2)).Remove(10))); rangoFecha.Border = 0; rangoFecha.Colspan = cols; tablasN.AddCell(rangoFecha); foreach (var celCabecera in v.numColEncabezado) { PdfPCell celdaCabeza = new PdfPCell(); celdaCabeza.AddElement(new Paragraph(celCabecera, letraTabNegrita)); celdaCabeza.BackgroundColor = new BaseColor(204, 204, 204); tablasN.AddCell(celdaCabeza); } int columnas = 0; int filas = 0; columnas = cols; filas = v.numfilasTabla[a]; for (int i = 0; i < filas; i++) { for (int j = 0; j < columnas; j++) { tablasN.AddCell(new Paragraph(v.listaCuerpo[pos], letraTab)); pos++; } } pdfDoc.Add(tablasN); pdfDoc.Add(new Chunk("\n")); } //APARTIR DE AQUI VA EL MONTO miFrase.Clear(); if (v.monto_x) { miFrase.Add(new Paragraph(text.Where(x => x.CAMPO == "monto").Select(x => x.TEXTO).First() + " " + v.monto + " " + v.moneda, normalPeque)); } else { miFrase.Add(""); } pdfDoc.Add(miFrase); //APARTIR DE AQUI VA LA SEGUNDA TABLA //2.- TABLA DE RECURRENCIAS if (v.secondTab_x) { pdfDoc.Add(new Paragraph(text.Where(x => x.CAMPO == "tituloRec").Select(x => x.TEXTO).First(), negritaPeque)); pdfDoc.Add(new Chunk("\n")); int cols2 = v.numColEncabezado2.Count; int tamaño2 = 600 / cols2; PdfPTable tablasN2 = new PdfPTable(cols2); if (cols2 == 5) { tablasN2.SetWidthPercentage(new float[] { tamaño2, tamaño2, tamaño2, tamaño2, tamaño2 }, PageSize.A4); } else if (cols2 == 4) { tablasN2.SetWidthPercentage(new float[] { tamaño2, tamaño2, tamaño2, tamaño2 }, PageSize.A4); } foreach (var celCabecera2 in v.numColEncabezado2) { PdfPCell celdaCabeza2 = new PdfPCell(); celdaCabeza2.AddElement(new Paragraph(celCabecera2, letraTabNegrita)); celdaCabeza2.BackgroundColor = new BaseColor(204, 204, 204); tablasN2.AddCell(celdaCabeza2); } for (int i = 0; i < v.numfilasTabla2; i++) { for (int j = 0; j < cols2; j++) { tablasN2.AddCell(new Paragraph(v.listaCuerpoRec[pos2], letraTab)); pos2++; } } pdfDoc.Add(tablasN2); pdfDoc.Add(new Chunk("\n")); } //APARTIR DE AQUI VA LA TERCER TABLA //2.- TABLA DE OBJETIVO Q if (v.tercerTab_x) { pdfDoc.Add(new Paragraph(text.Where(x => x.CAMPO == "tituloObjQ").Select(x => x.TEXTO).First(), negritaPeque)); pdfDoc.Add(new Chunk("\n")); int cols3 = v.numColEncabezado3.Count; int tamano3 = 600 / cols3; PdfPTable tablasN3 = new PdfPTable(cols3); if (cols3 == 5) { tablasN3.SetWidthPercentage(new float[] { tamano3, tamano3, tamano3, tamano3, tamano3 }, PageSize.A4); } foreach (var celCabecera3 in v.numColEncabezado3) { PdfPCell celdaCabeza3 = new PdfPCell(); celdaCabeza3.AddElement(new Paragraph(celCabecera3, letraTabNegrita)); celdaCabeza3.BackgroundColor = new BaseColor(204, 204, 204); tablasN3.AddCell(celdaCabeza3); } for (int i = 0; i < v.numfilasTabla3; i++) { for (int j = 0; j < cols3; j++) { tablasN3.AddCell(new Paragraph(v.listaCuerpoObjQ[pos3], letraTab)); pos3++; } } pdfDoc.Add(tablasN3); pdfDoc.Add(new Chunk("\n")); } //APARTIR DE AQUI VAN LAS FIRMAS //LINEAS PARA LA FIRMA EN UNA TABLA PdfPCell celFirma1 = new PdfPCell(); PdfPCell celFirma2 = new PdfPCell(); PdfPTable tabFirma1 = new PdfPTable(1); PdfPCell celFirmita1 = new PdfPCell(); if (v.nombreE_x || v.puestoE_x || v.companyC_x) { celFirmita1.AddElement(new Paragraph("\n", normalPeque)); celFirmita1.Border = 2; } else { celFirmita1.AddElement(new Paragraph("", normalPeque)); celFirmita1.Border = 0; } tabFirma1.AddCell(celFirmita1); tabFirma1.SetWidthPercentage(new float[] { 450 }, PageSize.A4); PdfPTable tabFirma2 = new PdfPTable(1); PdfPCell celFirmita2 = new PdfPCell(); if (v.nombreC_x || v.puestoC_x || v.companyCC_x) { celFirmita2.AddElement(new Paragraph("\n", normalPeque)); celFirmita2.Border = 2; } else { celFirmita2.AddElement(new Paragraph("", normalPeque)); celFirmita2.Border = 0; } tabFirma2.AddCell(celFirmita2); tabFirma2.SetWidthPercentage(new float[] { 450 }, PageSize.A4); celFirma1.AddElement(tabFirma1); celFirma1.Border = 0; celFirma2.AddElement(tabFirma2); celFirma2.Border = 0; tablaDatos2.AddCell(celFirma1); tablaDatos2.AddCell(celFirma2); tablaDatos2.SetWidthPercentage(new float[] { 300, 300 }, PageSize.A4); pdfDoc.Add(tablaDatos2); //DATOS PARA LAS FIRMAS tablaDatos3.HorizontalAlignment = Element.ALIGN_LEFT; tablaDatos3.SetWidthPercentage(new float[] { 298, 298 }, PageSize.A4); if (v.nombreE_x) { PdfPCell celda1Dat3 = new PdfPCell(new Paragraph(v.nombreE, negritaPeque)); celda1Dat3.HorizontalAlignment = Element.ALIGN_CENTER; tablaDatos3.AddCell(celda1Dat3); } else { PdfPCell celda1Dat3 = new PdfPCell(new Paragraph("", negritaPeque)); celda1Dat3.HorizontalAlignment = Element.ALIGN_CENTER; tablaDatos3.AddCell(celda1Dat3); } if (v.nombreC_x) { PdfPCell celda2Dat3 = new PdfPCell(new Paragraph(v.nombreC, negritaPeque)); celda2Dat3.HorizontalAlignment = Element.ALIGN_CENTER; tablaDatos3.AddCell(celda2Dat3); } else { PdfPCell celda2Dat3 = new PdfPCell(new Paragraph("", negritaPeque)); celda2Dat3.HorizontalAlignment = Element.ALIGN_CENTER; tablaDatos3.AddCell(celda2Dat3); } if (v.puestoE_x) { PdfPCell celda3Dat3 = new PdfPCell(new Paragraph(v.puestoE, normalPeque)); celda3Dat3.HorizontalAlignment = Element.ALIGN_CENTER; tablaDatos3.AddCell(celda3Dat3); } else { PdfPCell celda3Dat3 = new PdfPCell(new Paragraph("", normalPeque)); celda3Dat3.HorizontalAlignment = Element.ALIGN_CENTER; tablaDatos3.AddCell(celda3Dat3); } if (v.puestoC_x) { PdfPCell celda4Dat3 = new PdfPCell(new Paragraph(v.puestoC, normalPeque)); celda4Dat3.HorizontalAlignment = Element.ALIGN_CENTER; tablaDatos3.AddCell(celda4Dat3); } else { PdfPCell celda4Dat3 = new PdfPCell(new Paragraph("", normalPeque)); celda4Dat3.HorizontalAlignment = Element.ALIGN_CENTER; tablaDatos3.AddCell(celda4Dat3); } if (v.companyC_x) { PdfPCell celda5Dat3 = new PdfPCell(new Paragraph(v.companyC, negritaPeque)); celda5Dat3.HorizontalAlignment = Element.ALIGN_CENTER; tablaDatos3.AddCell(celda5Dat3); } else { PdfPCell celda5Dat3 = new PdfPCell(new Paragraph("", negritaPeque)); celda5Dat3.HorizontalAlignment = Element.ALIGN_CENTER; tablaDatos3.AddCell(celda5Dat3); } if (v.companyCC_x) { PdfPCell celda6Dat3 = new PdfPCell(new Paragraph(v.companyCC, negritaPeque)); celda6Dat3.HorizontalAlignment = Element.ALIGN_CENTER; tablaDatos3.AddCell(celda6Dat3); } else { PdfPCell celda6Dat3 = new PdfPCell(new Paragraph("", negritaPeque)); celda6Dat3.HorizontalAlignment = Element.ALIGN_CENTER; tablaDatos3.AddCell(celda6Dat3); } for (int i = 0; i < tablaDatos3.Rows.Count; i++) { if (i <= 4) { hfClass.quitaBordes(i, tablaDatos3); } } pdfDoc.Add(tablaDatos3); //TABLA PARA LOS COMENTARIOS pdfDoc.Add(new Chunk("\n")); tabComentarios.HorizontalAlignment = Element.ALIGN_LEFT; tabComentarios.SetWidthPercentage(new float[] { 300, 300 }, PageSize.A4); if (v.comentarios_x) { PdfPCell celda1 = new PdfPCell(new Paragraph(v.comentarios, normalPeque)); celda1.Border = 0; tabComentarios.AddCell(celda1); } else { PdfPCell celda1 = new PdfPCell(new Paragraph("", normalPeque)); celda1.Border = 0; tabComentarios.AddCell(celda1); } if (v.compromisoK_x) { PdfPCell celda2 = new PdfPCell(new Paragraph(v.compromisoK, normalPeque)); celda2.Border = 0; tabComentarios.AddCell(celda2); } else { PdfPCell celda2 = new PdfPCell(new Paragraph("", normalPeque)); celda2.Border = 0; tabComentarios.AddCell(celda2); } if (v.compromisoC_x) { PdfPCell celda3 = new PdfPCell(new Paragraph("\n" + v.compromisoC, normalPeque)); celda3.Border = 0; tabComentarios.AddCell(celda3); } else { PdfPCell celda3 = new PdfPCell(new Paragraph("", normalPeque)); celda3.Border = 0; tabComentarios.AddCell(celda3); } PdfPCell celVacia = new PdfPCell(new Paragraph("", normalPeque)); celVacia.Border = 0; tabComentarios.AddCell(celVacia); pdfDoc.Add(tabComentarios); pdfDoc.Close(); ruta = "/PdfTemp/" + nombreArchivo; } catch (Exception ex) { Log.ErrorLogApp(ex, "CartaD", "Generar PDF"); } return(ruta); } }
private PdfPTable RenderTable(DataTable DT) { PdfPTable table = new PdfPTable(DT.Columns.Count); table.HeaderRows = 2; //table.DefaultCell.Border = 1; // font for everything float FontSize = 12.0f; BaseFont f = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, true); Font titlefont = new Font(f, FontSize + 6, Font.BOLD, BaseColor.RED); Font headerfont = new Font(f, FontSize, Font.BOLD, BaseColor.BLACK); Font datafont = new Font(f, FontSize, Font.NORMAL, BaseColor.BLACK); // cell style PdfPCell celltemplate = new PdfPCell(); celltemplate.Padding = 5.0f; celltemplate.NoWrap = false; //celltemplate.CellEvent = new CellMod(); celltemplate.Padding = 3.0f; IPdfPTableEvent stylingEvent = new TableStyling(DT, headerfont, celltemplate); table.TableEvent = stylingEvent; // Section Title PdfPCell TitleCell = new PdfPCell(celltemplate); TitleCell.Colspan = DT.Columns.Count; Paragraph Title = new Paragraph(DT.TableName, titlefont); Title.Alignment = Element.ALIGN_CENTER; TitleCell.PaddingBottom = 5; TitleCell.AddElement(Title); table.AddCell(TitleCell); // header column names for (int C = 0; C < DT.Columns.Count; C++) { string value = DT.Columns[C].ColumnName; Paragraph P = new Paragraph(value, headerfont); PdfPCell cell = new PdfPCell(celltemplate); cell.AddElement(P); table.AddCell(cell); } // data for (int R = 0; R < DT.Rows.Count; R++) { for (int C = 0; C < DT.Columns.Count; C++) { string value = (string)DT.Rows[R][C]; Paragraph P = new Paragraph(value, datafont); PdfPCell cell = new PdfPCell(celltemplate); cell.AddElement(P); table.AddCell(cell); } } return(table); }
public MemoryStream GeneratePdfTemplate(GarmentInvoicePurchasingDispositionViewModel viewModel, int clientTimeZoneOffset) { const int MARGIN = 15; Font header_font = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 18); Font normal_font = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 8); Font bold_font = FontFactory.GetFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 8); Document document = new Document(PageSize.A4, MARGIN, MARGIN, MARGIN, MARGIN); MemoryStream stream = new MemoryStream(); PdfWriter writer = PdfWriter.GetInstance(document, stream); document.Open(); #region Header PdfPTable headerTable = new PdfPTable(2); headerTable.SetWidths(new float[] { 10f, 10f }); headerTable.WidthPercentage = 100; PdfPTable headerTable1 = new PdfPTable(1); PdfPTable headerTable2 = new PdfPTable(2); headerTable2.SetWidths(new float[] { 15f, 40f }); headerTable2.WidthPercentage = 100; PdfPCell cellHeader1 = new PdfPCell() { Border = Rectangle.NO_BORDER }; PdfPCell cellHeader2 = new PdfPCell() { Border = Rectangle.NO_BORDER }; PdfPCell cellHeaderBody = new PdfPCell() { Border = Rectangle.NO_BORDER }; PdfPCell cellHeaderCS2 = new PdfPCell() { Border = Rectangle.NO_BORDER, Colspan = 2 }; cellHeaderCS2.Phrase = new Phrase("BUKTI PENGELUARAN BANK - DISPOSISI", bold_font); cellHeaderCS2.HorizontalAlignment = Element.ALIGN_CENTER; headerTable.AddCell(cellHeaderCS2); cellHeaderCS2.Phrase = new Phrase("", bold_font); cellHeaderCS2.HorizontalAlignment = Element.ALIGN_CENTER; headerTable.AddCell(cellHeaderCS2); cellHeaderBody.Phrase = new Phrase("PT. DANLIRIS", normal_font); headerTable1.AddCell(cellHeaderBody); cellHeaderBody.Phrase = new Phrase("Kel. Banaran, Kec. Grogol", normal_font); headerTable1.AddCell(cellHeaderBody); cellHeaderBody.Phrase = new Phrase("Sukoharjo - 57100", normal_font); headerTable1.AddCell(cellHeaderBody); cellHeader1.AddElement(headerTable1); headerTable.AddCell(cellHeader1); cellHeaderCS2.Phrase = new Phrase("", bold_font); headerTable2.AddCell(cellHeaderCS2); cellHeaderBody.Phrase = new Phrase("Tanggal", normal_font); headerTable2.AddCell(cellHeaderBody); cellHeaderBody.Phrase = new Phrase(": " + viewModel.PaymentDate.AddHours(clientTimeZoneOffset).ToString("dd MMMM yyyy", new CultureInfo("id-ID")), normal_font); headerTable2.AddCell(cellHeaderBody); cellHeaderBody.Phrase = new Phrase("NO", normal_font); headerTable2.AddCell(cellHeaderBody); cellHeaderBody.Phrase = new Phrase(": " + viewModel.PaymentDispositionNo, normal_font); headerTable2.AddCell(cellHeaderBody); //List<string> supplier = model.Details.Select(m => m.SupplierName).Distinct().ToList(); cellHeaderBody.Phrase = new Phrase("Dibayarkan ke", normal_font); headerTable2.AddCell(cellHeaderBody); cellHeaderBody.Phrase = new Phrase(": " + viewModel.Supplier.Name, normal_font); headerTable2.AddCell(cellHeaderBody); cellHeaderBody.Phrase = new Phrase("Bank", normal_font); headerTable2.AddCell(cellHeaderBody); cellHeaderBody.Phrase = new Phrase(": " + viewModel.AccountBank.BankName + " - A/C : " + viewModel.AccountBank.AccountNumber, normal_font); headerTable2.AddCell(cellHeaderBody); cellHeader2.AddElement(headerTable2); headerTable.AddCell(cellHeader2); cellHeaderCS2.Phrase = new Phrase("", normal_font); headerTable.AddCell(cellHeaderCS2); document.Add(headerTable); #endregion Header Dictionary <string, double> units = new Dictionary <string, double>(); Dictionary <string, double> percentageUnits = new Dictionary <string, double>(); int index = 1; double total = 0; double totalPay = 0; //if (viewModel.AccountBank.Currency.Code != "IDR" || viewModel.CurrencyCode == "IDR") //{ #region BodyNonIDR PdfPTable bodyNonIDRTable = new PdfPTable(6); PdfPCell bodyNonIDRCell = new PdfPCell(); float[] widthsBodyNonIDR = new float[] { 5f, 10f, 10f, 10f, 7f, 15f }; bodyNonIDRTable.SetWidths(widthsBodyNonIDR); bodyNonIDRTable.WidthPercentage = 100; bodyNonIDRCell.HorizontalAlignment = Element.ALIGN_CENTER; bodyNonIDRCell.Phrase = new Phrase("No.", bold_font); bodyNonIDRTable.AddCell(bodyNonIDRCell); bodyNonIDRCell.Phrase = new Phrase("No. Disposisi", bold_font); bodyNonIDRTable.AddCell(bodyNonIDRCell); bodyNonIDRCell.Colspan = 2; bodyNonIDRCell.Phrase = new Phrase("Kategori Barang", bold_font); bodyNonIDRTable.AddCell(bodyNonIDRCell); bodyNonIDRCell.Colspan = 1; //bodyNonIDRCell.Phrase = new Phrase("Divisi", bold_font); //bodyNonIDRTable.AddCell(bodyNonIDRCell); bodyNonIDRCell.Phrase = new Phrase("Mata Uang", bold_font); bodyNonIDRTable.AddCell(bodyNonIDRCell); bodyNonIDRCell.Phrase = new Phrase("Jumlah", bold_font); bodyNonIDRTable.AddCell(bodyNonIDRCell); foreach (GarmentInvoicePurchasingDispositionItemViewModel item in viewModel.Items) { //var details = item.Details // .GroupBy(m => new { m.unit.code, m.unit.name }) // .Select(s => new // { // s.First().unit.code, // s.First().unit.name, // Total = s.Sum(d => d.price) // }); bodyNonIDRCell.HorizontalAlignment = Element.ALIGN_CENTER; bodyNonIDRCell.VerticalAlignment = Element.ALIGN_TOP; bodyNonIDRCell.Phrase = new Phrase((index++).ToString(), normal_font); bodyNonIDRTable.AddCell(bodyNonIDRCell); bodyNonIDRCell.HorizontalAlignment = Element.ALIGN_LEFT; bodyNonIDRCell.Phrase = new Phrase(item.DispositionNoteNo, normal_font); bodyNonIDRTable.AddCell(bodyNonIDRCell); bodyNonIDRCell.Colspan = 2; bodyNonIDRCell.Phrase = new Phrase(item.Category, normal_font); bodyNonIDRTable.AddCell(bodyNonIDRCell); bodyNonIDRCell.Colspan = 1; //bodyNonIDRCell.Phrase = new Phrase(item.ProformaNo, normal_font); //bodyNonIDRTable.AddCell(bodyNonIDRCell); bodyNonIDRCell.HorizontalAlignment = Element.ALIGN_CENTER; bodyNonIDRCell.Phrase = new Phrase(viewModel.AccountBank.Currency.Code, normal_font); bodyNonIDRTable.AddCell(bodyNonIDRCell); bodyNonIDRCell.HorizontalAlignment = Element.ALIGN_RIGHT; bodyNonIDRCell.Phrase = new Phrase(string.Format("{0:n4}", item.TotalPaidPayment), normal_font); bodyNonIDRTable.AddCell(bodyNonIDRCell); total += item.TotalPaidPayment; //foreach (var detail in details) //{ // if (units.ContainsKey(detail.code)) // { // units[detail.code] += detail.Total; // } // else // { // units.Add(detail.code, detail.Total); // } // totalPay += detail.Total; //} } //foreach (var un in units) //{ // percentageUnits[un.Key] = un.Value * 100 / totalPay; //} bodyNonIDRCell.Colspan = 3; bodyNonIDRCell.Border = Rectangle.NO_BORDER; bodyNonIDRCell.Phrase = new Phrase("", normal_font); bodyNonIDRTable.AddCell(bodyNonIDRCell); bodyNonIDRCell.Colspan = 1; bodyNonIDRCell.Border = Rectangle.BOX; bodyNonIDRCell.HorizontalAlignment = Element.ALIGN_LEFT; bodyNonIDRCell.Phrase = new Phrase("Total", bold_font); bodyNonIDRTable.AddCell(bodyNonIDRCell); bodyNonIDRCell.Colspan = 1; bodyNonIDRCell.HorizontalAlignment = Element.ALIGN_CENTER; bodyNonIDRCell.Phrase = new Phrase(viewModel.CurrencyCode, bold_font); bodyNonIDRTable.AddCell(bodyNonIDRCell); bodyNonIDRCell.HorizontalAlignment = Element.ALIGN_RIGHT; bodyNonIDRCell.Phrase = new Phrase(string.Format("{0:n4}", total), bold_font); bodyNonIDRTable.AddCell(bodyNonIDRCell); document.Add(bodyNonIDRTable); #endregion BodyNonIDR //} //else //{ // #region Body // PdfPTable bodyTable = new PdfPTable(7); // PdfPCell bodyCell = new PdfPCell(); // float[] widthsBody = new float[] { 5f, 10f, 10f, 10f, 7f, 10f, 10f }; // bodyTable.SetWidths(widthsBody); // bodyTable.WidthPercentage = 100; // bodyCell.HorizontalAlignment = Element.ALIGN_CENTER; // bodyCell.Phrase = new Phrase("No.", bold_font); // bodyTable.AddCell(bodyCell); // bodyCell.Phrase = new Phrase("No. Disposisi", bold_font); // bodyTable.AddCell(bodyCell); // bodyCell.Phrase = new Phrase("Kategori Barang", bold_font); // bodyTable.AddCell(bodyCell); // bodyCell.Phrase = new Phrase("Divisi", bold_font); // bodyTable.AddCell(bodyCell); // bodyCell.Phrase = new Phrase("Mata Uang", bold_font); // bodyTable.AddCell(bodyCell); // bodyCell.Phrase = new Phrase("Jumlah", bold_font); // bodyTable.AddCell(bodyCell); // bodyCell.Phrase = new Phrase("Jumlah (IDR)", bold_font); // bodyTable.AddCell(bodyCell); // foreach (GarmentInvoicePurchasingDispositionItemViewModel item in viewModel.Items) // { // //var details = item.Details // // .GroupBy(m => new { m.unit.code, m.unit.name }) // // .Select(s => new // // { // // s.First().unit.code, // // s.First().unit.name, // // Total = s.Sum(d => d.price) // // }); // bodyCell.HorizontalAlignment = Element.ALIGN_CENTER; // bodyCell.VerticalAlignment = Element.ALIGN_TOP; // bodyCell.Phrase = new Phrase((index++).ToString(), normal_font); // bodyTable.AddCell(bodyCell); // bodyCell.HorizontalAlignment = Element.ALIGN_LEFT; // bodyCell.Phrase = new Phrase(item.DispositionNoteNo, normal_font); // bodyTable.AddCell(bodyCell); // bodyCell.Phrase = new Phrase(item.Category, normal_font); // bodyTable.AddCell(bodyCell); // bodyCell.Phrase = new Phrase(item.ProformaNo, normal_font); // bodyTable.AddCell(bodyCell); // bodyCell.HorizontalAlignment = Element.ALIGN_CENTER; // bodyCell.Phrase = new Phrase(viewModel.CurrencyCode, normal_font); // bodyTable.AddCell(bodyCell); // bodyCell.HorizontalAlignment = Element.ALIGN_RIGHT; // bodyCell.Phrase = new Phrase(string.Format("{0:n4}", item.TotalPaid), normal_font); // bodyTable.AddCell(bodyCell); // bodyCell.HorizontalAlignment = Element.ALIGN_RIGHT; // bodyCell.Phrase = new Phrase(string.Format("{0:n4}", (item.TotalPaid * viewModel.CurrencyRate)), normal_font); // bodyTable.AddCell(bodyCell); // total += item.TotalPaid; // //foreach (var detail in details) // //{ // // if (units.ContainsKey(detail.code)) // // { // // units[detail.code] += detail.Total; // // } // // else // // { // // units.Add(detail.code, detail.Total); // // } // // totalPay += detail.Total; // //} // } // //foreach (var un in units) // //{ // // percentageUnits[un.Key] = (un.Value * viewModel.CurrencyRate) * 100 / (totalPay * viewModel.CurrencyRate); // //} // bodyCell.Colspan = 3; // bodyCell.Border = Rectangle.NO_BORDER; // bodyCell.Phrase = new Phrase("", normal_font); // bodyTable.AddCell(bodyCell); // bodyCell.Colspan = 1; // bodyCell.Border = Rectangle.BOX; // bodyCell.HorizontalAlignment = Element.ALIGN_LEFT; // bodyCell.Phrase = new Phrase("Total", bold_font); // bodyTable.AddCell(bodyCell); // bodyCell.Colspan = 1; // bodyCell.HorizontalAlignment = Element.ALIGN_CENTER; // bodyCell.Phrase = new Phrase(viewModel.AccountBank.Currency.Code, bold_font); // bodyTable.AddCell(bodyCell); // bodyCell.HorizontalAlignment = Element.ALIGN_RIGHT; // bodyCell.Phrase = new Phrase(string.Format("{0:n4}", total), bold_font); // bodyTable.AddCell(bodyCell); // bodyCell.HorizontalAlignment = Element.ALIGN_RIGHT; // bodyCell.Phrase = new Phrase(string.Format("{0:n4}", total * viewModel.CurrencyRate), bold_font); // bodyTable.AddCell(bodyCell); // document.Add(bodyTable); // #endregion Body //} #region BodyFooter PdfPTable bodyFooterTable = new PdfPTable(6); bodyFooterTable.SetWidths(new float[] { 3f, 6f, 2f, 6f, 10f, 10f }); bodyFooterTable.WidthPercentage = 100; PdfPCell bodyFooterCell = new PdfPCell() { Border = Rectangle.NO_BORDER }; //bodyFooterCell.Colspan = 1; //bodyFooterCell.Phrase = new Phrase(""); //bodyFooterTable.AddCell(bodyFooterCell); //bodyFooterCell.Colspan = 1; //bodyFooterCell.HorizontalAlignment = Element.ALIGN_LEFT; //bodyFooterCell.Phrase = new Phrase("Total :", normal_font); //bodyFooterTable.AddCell(bodyFooterCell); //bodyFooterCell.Colspan = 4; //bodyFooterCell.HorizontalAlignment = Element.ALIGN_RIGHT; //bodyFooterCell.Phrase = new Phrase(string.Format("{0:n4}", total)); //bodyFooterTable.AddCell(bodyFooterCell); ////total = viewModel.CurrencyId > 0 ? total * viewModel.CurrencyRate : total; //foreach (var unit in percentageUnits) //{ // bodyFooterCell.Colspan = 1; // bodyFooterCell.Phrase = new Phrase(""); // bodyFooterTable.AddCell(bodyFooterCell); // bodyFooterCell.Phrase = new Phrase(unit.Key, normal_font); // bodyFooterTable.AddCell(bodyFooterCell); // bodyFooterCell.Phrase = new Phrase(viewModel.AccountBank.Currency.Code, normal_font); // bodyFooterTable.AddCell(bodyFooterCell); // //bodyFooterCell.Phrase = new Phrase(string.Format("{0:n4}", unit.Value), normal_font); // //bodyFooterTable.AddCell(bodyFooterCell); // bodyFooterCell.Phrase = new Phrase(string.Format("{0:n4}", unit.Value * total / 100), normal_font); // bodyFooterTable.AddCell(bodyFooterCell); // bodyFooterCell.Colspan = 2; // bodyFooterCell.Phrase = new Phrase(""); // bodyFooterTable.AddCell(bodyFooterCell); //} //bodyFooterCell.Colspan = 6; //bodyFooterCell.HorizontalAlignment = Element.ALIGN_LEFT; //bodyFooterCell.Phrase = new Phrase(""); //bodyFooterTable.AddCell(bodyFooterCell); bodyFooterCell.Colspan = 1; bodyFooterCell.HorizontalAlignment = Element.ALIGN_LEFT; bodyFooterCell.Phrase = new Phrase(""); bodyFooterTable.AddCell(bodyFooterCell); bodyFooterCell.Phrase = new Phrase("Total", normal_font); bodyFooterTable.AddCell(bodyFooterCell); bodyFooterCell.HorizontalAlignment = Element.ALIGN_RIGHT; bodyFooterCell.Phrase = new Phrase(": " + viewModel.AccountBank.Currency.Code, normal_font); bodyFooterTable.AddCell(bodyFooterCell); bodyFooterCell.Colspan = 3; bodyFooterCell.HorizontalAlignment = Element.ALIGN_LEFT; bodyFooterCell.Phrase = new Phrase(string.Format("{0:n4}", total), normal_font); bodyFooterTable.AddCell(bodyFooterCell); //document.Add(bodyFooterTable); //document.Add(new Paragraph("\n")); bodyFooterCell.Colspan = 1; bodyFooterCell.HorizontalAlignment = Element.ALIGN_LEFT; bodyFooterCell.Phrase = new Phrase(""); bodyFooterTable.AddCell(bodyFooterCell); bodyFooterCell.Phrase = new Phrase("Terbilang", normal_font); bodyFooterTable.AddCell(bodyFooterCell); bodyFooterCell.HorizontalAlignment = Element.ALIGN_RIGHT; bodyFooterCell.Phrase = new Phrase(": " + viewModel.AccountBank.Currency.Code, normal_font); bodyFooterTable.AddCell(bodyFooterCell); bodyFooterCell.Colspan = 3; bodyFooterCell.HorizontalAlignment = Element.ALIGN_LEFT; bodyFooterCell.Phrase = new Phrase(NumberToTextIDN.terbilang(total), normal_font); bodyFooterTable.AddCell(bodyFooterCell); document.Add(bodyFooterTable); document.Add(new Paragraph("\n")); #endregion BodyFooter #region Footer PdfPTable footerTable = new PdfPTable(2); PdfPCell cellFooter = new PdfPCell() { Border = Rectangle.NO_BORDER }; float[] widthsFooter = new float[] { 10f, 5f }; footerTable.SetWidths(widthsFooter); footerTable.WidthPercentage = 100; cellFooter.Phrase = new Phrase("Dikeluarkan dengan cek/BG No. : " + viewModel.BGCheckNumber, normal_font); footerTable.AddCell(cellFooter); cellFooter.Phrase = new Phrase("", normal_font); footerTable.AddCell(cellFooter); PdfPTable signatureTable = new PdfPTable(3); PdfPCell signatureCell = new PdfPCell() { HorizontalAlignment = Element.ALIGN_CENTER }; signatureCell.Phrase = new Phrase("Bag. Keuangan", normal_font); signatureTable.AddCell(signatureCell); signatureCell.Colspan = 2; signatureCell.HorizontalAlignment = Element.ALIGN_CENTER; signatureCell.Phrase = new Phrase("Direksi", normal_font); signatureTable.AddCell(signatureCell); signatureTable.AddCell(new PdfPCell() { Phrase = new Phrase("---------------------------", normal_font), FixedHeight = 40, VerticalAlignment = Element.ALIGN_BOTTOM, HorizontalAlignment = Element.ALIGN_CENTER }); signatureTable.AddCell(new PdfPCell() { Phrase = new Phrase("---------------------------", normal_font), FixedHeight = 40, Border = Rectangle.NO_BORDER, VerticalAlignment = Element.ALIGN_BOTTOM, HorizontalAlignment = Element.ALIGN_CENTER }); signatureTable.AddCell(new PdfPCell() { Phrase = new Phrase("---------------------------", normal_font), FixedHeight = 40, Border = Rectangle.NO_BORDER, VerticalAlignment = Element.ALIGN_BOTTOM, HorizontalAlignment = Element.ALIGN_CENTER }); footerTable.AddCell(new PdfPCell(signatureTable)); cellFooter.Phrase = new Phrase("", normal_font); footerTable.AddCell(cellFooter); document.Add(footerTable); #endregion Footer document.Close(); byte[] byteInfo = stream.ToArray(); stream.Write(byteInfo, 0, byteInfo.Length); stream.Position = 0; return(stream); }
virtual public bool Add(IElement o) { cell.AddElement(o); return(true); }
public ActionResult PDFGenerator(string id ) { using (Document document = new Document()) { string idpago = id; //while (id != null) int identificacionpago = Convert.ToInt32(idpago); DataTable dt = new DataTable(); Database conex = Conexion.getInstancia(); dt = conex.ExecuteDataSet("Usp_TraerPago", identificacionpago).Tables[0]; string pago = dt.Rows[0]["ValorPago"].ToString(); string aniopago = dt.Rows[0]["AnioPago"].ToString(); DateTime fechapago = Convert.ToDateTime(dt.Rows[0]["FechaPago"]); //int pag = Convert.ToInt32(ViewBag.datos); int idusuario = Convert.ToInt32(dt.Rows[0]["IdUsuario"].ToString()); DataTable dt1 = new DataTable(); dt1 = conex.ExecuteDataSet("Usp_UsuarioPago", idusuario).Tables[0]; string Numid = dt1.Rows[0]["NumIdentificacion"].ToString(); string Tipoid = dt1.Rows[0]["TipoIdentificacion"].ToString(); string Nombre = dt1.Rows[0]["NombresUsuario"].ToString(); string apellidos = dt1.Rows[0]["ApellidosUsuario"].ToString(); MemoryStream workStream = new MemoryStream(); // Document document = new Document(); PdfWriter.GetInstance(document, workStream).CloseStream = false; //Image string imageURL = @"D:\aldea.jpg"; iTextSharp.text.Image logo = iTextSharp.text.Image.GetInstance(imageURL); //Resize image depend upon your need logo.ScaleToFit(140f, 120f); //Give space before image logo.SpacingBefore = 10f; //Give some space after the image logo.SpacingAfter = 1f; logo.Alignment = Element.ALIGN_RIGHT; //Tamaño del logo //logo.ScaleToFit(50f, 50f); //Image //Image and text PdfPTable table = new PdfPTable(2); PdfPCell cell = new PdfPCell(); PdfPCell cell2 = new PdfPCell(); Paragraph p = new Paragraph(); Paragraph p2 = new Paragraph(); p.Add(new Phrase("Asociación Lasallista de Exalumnos ALDEA", new Font(Font.FontFamily.HELVETICA, 13f, Font.BOLD))); p2.Add(new Chunk(logo, 100, -30)); p2.Alignment = Element.ALIGN_CENTER; cell.AddElement(p); cell2.AddElement(p2); cell.BorderWidth = 0; cell2.BorderWidth = 0; table.AddCell(cell); table.AddCell(cell2); //Image and text document.Open(); document.Add(new Paragraph(" ")); document.Add(table); //document.Add(logo); document.Add(new Paragraph(" ")); document.Add(new Paragraph(" ")); document.Add(new Paragraph(" ")); document.Add(new Paragraph("Asociación Lasallista de Exalumnos ALDEA", new Font(Font.FontFamily.HELVETICA, 13f, Font.BOLD))); document.Add(new Paragraph("Certificado de aporte económico", new Font(Font.FontFamily.HELVETICA, 13f, Font.BOLD))); document.Add(new Paragraph(" ")); document.Add(new Paragraph(" ")); //document.Add(new Paragraph(" por el año " + aniopago)); // Element.ALIGN_JUSTIFIED; Paragraph p4 = new Paragraph("La Asociación Lasallista de Exalumnos ALDEA, certifica que la persona " + Nombre + " " + apellidos + " identificado con el documento " + Tipoid + " " + Numid + " " + " en la fecha " + fechapago.Day + "/" + fechapago.Month + "/" + fechapago.Year + " realizó un aporte por la suma de " + pago + " pesos a la asociación, destinado al año " + aniopago); p4.Alignment = Element.ALIGN_JUSTIFIED; document.Add(p4); //document.Add(new Paragraph("La Asociación Lasallista de Exalumnos ALDEA, certifica que la persona " + Nombre + " " + apellidos + " identificado con el documento " + Tipoid + " " + Numid + " " + " en la fecha "+ fechapago.Day+"/"+ fechapago.Month + "/" + fechapago.Year + " realizó un aporte por la suma de " + pago + " pesos a la asociación, destinado al año "+ aniopago)); document.Add(new Paragraph(" ")); document.Add(new Paragraph(" ")); document.Add(new Paragraph(" ")); document.Add(new Paragraph(" ")); document.Add(new Paragraph(" ")); document.Add(new Paragraph(" ")); document.Add(new Paragraph(" ")); document.Add(new Paragraph(" ")); document.Add(new Paragraph("___________________________ ")); document.Add(new Paragraph("Firma del Revisor Fiscal ")); document.Add(new Paragraph(" ")); document.Add(new Paragraph(" ")); document.Add(new Paragraph(" ")); document.Add(new Paragraph(" ")); document.Add(new Paragraph(" ")); document.Add(new Paragraph(" ")); document.Add(new Paragraph(" ")); document.Add(new Paragraph(" ")); document.Add(new Paragraph(" ")); document.Add(new Paragraph(" ")); document.Add(new Paragraph(" ")); document.Add(new Paragraph(" ")); Paragraph p3 = new Paragraph("Generado el " + DateTime.Now.ToString()); p3.Alignment = Element.ALIGN_RIGHT; document.Add(p3); //document.SaveAs(workStream); document.Close(); byte[] byteInfo = workStream.ToArray(); workStream.Write(byteInfo, 0, byteInfo.Length); workStream.Position = 0; return(File(workStream, "application/pdf")); } }
public PdfPTable incomePurchaseTable(List <IncomePurchaseReport> incomePurchaseInfoList) { // Table Start PdfPTable table = new PdfPTable(4); table.HorizontalAlignment = Element.ALIGN_LEFT; table.TotalWidth = 500f; table.SetTotalWidth(new float[] { 50f, 150f, 100f, 200f }); // Table Header BaseFont bfnTableHeader = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); Font fntTableHeader = new Font(bfnTableHeader, 10, 1, BaseColor.BLACK); PdfPCell cellSl = new PdfPCell(); cellSl.AddElement(new Chunk("SL", fntTableHeader)); cellSl.Border = 0; table.AddCell(cellSl); PdfPCell cellDate = new PdfPCell(); cellDate.AddElement(new Chunk("Date", fntTableHeader)); cellDate.Border = 0; table.AddCell(cellDate); PdfPCell cellCount = new PdfPCell(); cellCount.AddElement(new Chunk("Purchase Count", fntTableHeader)); cellCount.Border = 0; table.AddCell(cellCount); PdfPCell cellLineTotal = new PdfPCell(); cellLineTotal.AddElement(new Chunk("Purchase Amount", fntTableHeader)); cellLineTotal.Border = 0; table.AddCell(cellLineTotal); // Table Data int sl = 1; BaseFont bfnTableData = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); Font fntTableData = new Font(bfnTableData, 8, 1, BaseColor.BLACK); totalPurchaseAmount = 0; foreach (var item in incomePurchaseInfoList) { PdfPCell cellItemSl = new PdfPCell(); cellItemSl.AddElement(new Chunk((sl++).ToString(), fntTableData)); cellItemSl.Border = 0; table.AddCell(cellItemSl); PdfPCell cellItemDate = new PdfPCell(); cellItemDate.AddElement(new Chunk(item.PurchaseDate.ToString("d"), fntTableData)); cellItemDate.Border = 0; table.AddCell(cellItemDate); PdfPCell cellItemCount = new PdfPCell(); cellItemCount.AddElement(new Chunk(item.PurchaseCount.ToString(), fntTableData)); cellItemCount.Border = 0; table.AddCell(cellItemCount); PdfPCell cellItemLineTotal = new PdfPCell(); cellItemLineTotal.AddElement(new Chunk(item.PurchaseTotalAmount.ToString("N"), fntTableData)); cellItemLineTotal.Border = 0; table.AddCell(cellItemLineTotal); totalPurchaseAmount += item.PurchaseTotalAmount; } PdfPCell borderBottom = new PdfPCell(); borderBottom.AddElement(new Chunk("\n", fntTableData)); borderBottom.Colspan = 4; borderBottom.Border = PdfPCell.BOTTOM_BORDER; table.AddCell(borderBottom); // Total Amount PdfPCell nullCell = new PdfPCell(); nullCell.Colspan = 2; nullCell.Border = 0; table.AddCell(nullCell); PdfPCell cellTotal = new PdfPCell(); cellTotal.AddElement(new Chunk("Total Amount", fntTableHeader)); cellTotal.Border = 0; table.AddCell(cellTotal); PdfPCell cellTotalValue = new PdfPCell(); cellTotalValue.AddElement(new Chunk(totalPurchaseAmount.ToString("N"), fntTableHeader)); cellTotalValue.Border = 0; table.AddCell(cellTotalValue); return(table); }
public PdfPTable summaryTable() { // Table Start PdfPTable table = new PdfPTable(2); table.HorizontalAlignment = Element.ALIGN_LEFT; table.TotalWidth = 500f; table.SetTotalWidth(new float[] { 200f, 300f }); // Table Header BaseFont bfnTableHeader = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); Font fntTableHeader = new Font(bfnTableHeader, 10, 1, BaseColor.BLACK); // Table Data BaseFont bfnTableData = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); Font fntTableData = new Font(bfnTableData, 8, 1, BaseColor.BLACK); PdfPCell cellPurchase = new PdfPCell(); cellPurchase.AddElement(new Chunk("Purchase Amount", fntTableHeader)); cellPurchase.Border = 0; table.AddCell(cellPurchase); PdfPCell cellPurchaseValue = new PdfPCell(); cellPurchaseValue.AddElement(new Chunk(totalPurchaseAmount.ToString("N"), fntTableData)); cellPurchaseValue.Border = 0; table.AddCell(cellPurchaseValue); PdfPCell cellSales = new PdfPCell(); cellSales.AddElement(new Chunk("Sales Amount", fntTableHeader)); cellSales.Border = 0; table.AddCell(cellSales); PdfPCell cellSalesValue = new PdfPCell(); cellSalesValue.AddElement(new Chunk(totalSalesAmount.ToString("N"), fntTableData)); cellSalesValue.Border = 0; table.AddCell(cellSalesValue); PdfPCell cellExpense = new PdfPCell(); cellExpense.AddElement(new Chunk("Expense Amount", fntTableHeader)); cellExpense.Border = 0; table.AddCell(cellExpense); PdfPCell cellExpenseValue = new PdfPCell(); cellExpenseValue.AddElement(new Chunk(totalExpenseAmount.ToString("N"), fntTableData)); cellExpenseValue.Border = 0; table.AddCell(cellExpenseValue); PdfPCell borderBottom = new PdfPCell(); borderBottom.AddElement(new Chunk("\n", fntTableData)); borderBottom.Colspan = 2; borderBottom.Border = PdfPCell.BOTTOM_BORDER; table.AddCell(borderBottom); PdfPCell cellProfit = new PdfPCell(); cellProfit.AddElement(new Chunk("Total Profit", fntTableHeader)); cellProfit.Border = 0; table.AddCell(cellProfit); double totalProfit = totalSalesAmount - (totalPurchaseAmount + totalExpenseAmount); PdfPCell cellProfitValue = new PdfPCell(); cellProfitValue.AddElement(new Chunk(totalProfit.ToString("N"), fntTableData)); cellProfitValue.Border = 0; table.AddCell(cellProfitValue); return(table); }
public MemoryStream GeneratePdfTemplate(SalesInvoiceExportViewModel viewModel, int clientTimeZoneOffset) { const int MARGIN = 15; Font header_font = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 18); Font normal_font = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 8); Font bold_font = FontFactory.GetFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 8); Font Title_bold_font = FontFactory.GetFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 10); Document document = new Document(PageSize.A4, MARGIN, MARGIN, MARGIN, MARGIN); MemoryStream stream = new MemoryStream(); PdfWriter writer = PdfWriter.GetInstance(document, stream); document.Open(); #region Header #region Header_A PdfPTable headerTable_A = new PdfPTable(3); PdfPTable headerTable_A1 = new PdfPTable(1); PdfPTable headerTable_A2 = new PdfPTable(1); PdfPTable headerTable_A3 = new PdfPTable(1); headerTable_A.SetWidths(new float[] { 10f, 10f, 10f }); headerTable_A.WidthPercentage = 100; PdfPCell cellHeaderBody_A = new PdfPCell() { Border = Rectangle.NO_BORDER }; PdfPCell cellHeader_A1 = new PdfPCell() { Border = Rectangle.NO_BORDER }; PdfPCell cellHeader_A2 = new PdfPCell() { Border = Rectangle.NO_BORDER }; PdfPCell cellHeader_A3 = new PdfPCell() { Border = Rectangle.NO_BORDER }; cellHeaderBody_A.Phrase = new Phrase("\n", normal_font); headerTable_A1.AddCell(cellHeaderBody_A); cellHeaderBody_A.Phrase = new Phrase("INVOICE NO : " + viewModel.SalesInvoiceNo, normal_font); headerTable_A1.AddCell(cellHeaderBody_A); cellHeader_A1.AddElement(headerTable_A1); headerTable_A.AddCell(cellHeader_A1); cellHeaderBody_A.Phrase = new Phrase("\n", normal_font); headerTable_A2.AddCell(cellHeaderBody_A); cellHeaderBody_A.Phrase = new Phrase("DATE : " + viewModel.SalesInvoiceDate?.AddHours(clientTimeZoneOffset).ToString("dd MMMM yyyy", new CultureInfo("id-ID")), normal_font); headerTable_A2.AddCell(cellHeaderBody_A); cellHeader_A2.AddElement(headerTable_A2); headerTable_A.AddCell(cellHeader_A2); cellHeaderBody_A.Phrase = new Phrase("FM-PJ-00-03-006", normal_font); headerTable_A3.AddCell(cellHeaderBody_A); cellHeaderBody_A.Phrase = new Phrase("Page : " + "?????" + " of " + "?????", normal_font); headerTable_A3.AddCell(cellHeaderBody_A); cellHeader_A3.AddElement(headerTable_A3); headerTable_A.AddCell(cellHeader_A3); document.Add(headerTable_A); #endregion Header_A #region Header_B PdfPTable headerTable_B = new PdfPTable(2); PdfPTable headerTable_B1 = new PdfPTable(1); PdfPTable headerTable_B2 = new PdfPTable(1); headerTable_B.SetWidths(new float[] { 10f, 10f }); headerTable_B.WidthPercentage = 100; PdfPCell cellHeaderBody_B = new PdfPCell() { Border = Rectangle.NO_BORDER }; PdfPCell cellHeader_B1 = new PdfPCell(); PdfPCell cellHeader_B2 = new PdfPCell(); cellHeaderBody_B.Phrase = new Phrase("SOLD BY ORDERS AND FOR ACCOUNT AND RISK OF MESSRS : " + viewModel.BuyerName + "\n" + viewModel.BuyerAddress, normal_font); headerTable_B1.AddCell(cellHeaderBody_B); cellHeader_B1.AddElement(headerTable_B1); headerTable_B.AddCell(cellHeader_B1); foreach (var detail in viewModel.SalesInvoiceExportDetails) { cellHeaderBody_B.Phrase = new Phrase("CONTRACT NO : " + detail.ContractNo, normal_font); headerTable_B2.AddCell(cellHeaderBody_B); } cellHeaderBody_B.Phrase = new Phrase("SHIPPED PER : " + viewModel.ShippedPer, normal_font); headerTable_B2.AddCell(cellHeaderBody_B); cellHeaderBody_B.Phrase = new Phrase("SAILING ON OR ABOUT : " + viewModel.SailingDate?.AddHours(clientTimeZoneOffset).ToString("dd MMMM yyyy", new CultureInfo("id-ID")), normal_font); headerTable_B2.AddCell(cellHeaderBody_B); cellHeaderBody_B.Phrase = new Phrase("FROM : " + viewModel.From, normal_font); headerTable_B2.AddCell(cellHeaderBody_B); cellHeaderBody_B.Phrase = new Phrase("TO : " + viewModel.To, normal_font); headerTable_B2.AddCell(cellHeaderBody_B); cellHeader_B2.AddElement(headerTable_B2); headerTable_B.AddCell(cellHeader_B2); document.Add(headerTable_B); #endregion Header_B #region Header_C PdfPTable headerTable_C = new PdfPTable(2); PdfPTable headerTable_C1 = new PdfPTable(1); PdfPTable headerTable_C2 = new PdfPTable(1); headerTable_C.SetWidths(new float[] { 10f, 10f }); headerTable_C.WidthPercentage = 100; PdfPCell cellHeaderBody_C = new PdfPCell() { Border = Rectangle.NO_BORDER }; PdfPCell cellHeader_C1 = new PdfPCell() { Border = Rectangle.NO_BORDER }; PdfPCell cellHeader_C2 = new PdfPCell() { Border = Rectangle.NO_BORDER }; cellHeaderBody_C.Phrase = new Phrase("\n", normal_font); headerTable_C1.AddCell(cellHeaderBody_C); cellHeaderBody_C.Phrase = new Phrase("LETTER OF CREDIT NUMBER : " + viewModel.LetterOfCreditNumber, normal_font); headerTable_C1.AddCell(cellHeaderBody_C); cellHeaderBody_C.Phrase = new Phrase("ISSUED BY : " + viewModel.IssuedBy, normal_font); headerTable_C1.AddCell(cellHeaderBody_C); cellHeader_C1.AddElement(headerTable_C1); headerTable_C.AddCell(cellHeader_C1); cellHeaderBody_C.Phrase = new Phrase("\n", normal_font); headerTable_C2.AddCell(cellHeaderBody_C); cellHeaderBody_C.Phrase = new Phrase("DATE : " + viewModel.LCDate?.AddHours(clientTimeZoneOffset).ToString("dd MMMM yyyy", new CultureInfo("id-ID")), normal_font); headerTable_C2.AddCell(cellHeaderBody_C); cellHeaderBody_C.Phrase = new Phrase("", normal_font); headerTable_C1.AddCell(cellHeaderBody_C); cellHeader_C2.AddElement(headerTable_C2); headerTable_C.AddCell(cellHeader_C2); document.Add(headerTable_C); #endregion Header_C #endregion Header #region Body #region Body_A PdfPTable bodyTable_A = new PdfPTable(4); PdfPCell bodyCell_A = new PdfPCell(); float[] widthsBody = new float[] { 20f, 8f, 8f, 10f }; bodyTable_A.SetWidths(widthsBody); bodyTable_A.WidthPercentage = 100; bodyCell_A.HorizontalAlignment = Element.ALIGN_CENTER; bodyCell_A.Phrase = new Phrase("DESCRIPTION", bold_font); bodyTable_A.AddCell(bodyCell_A); bodyCell_A.Phrase = new Phrase("QUANTITY IN METERS", bold_font); bodyTable_A.AddCell(bodyCell_A); bodyCell_A.Phrase = new Phrase("UNIT PRICE USD", bold_font); bodyTable_A.AddCell(bodyCell_A); bodyCell_A.Phrase = new Phrase("TOTAL PRICE USD", bold_font); bodyTable_A.AddCell(bodyCell_A); double totalPrice = 0; double grandTotalPrice = 0; double totalLength = 0; foreach (var detail in viewModel.SalesInvoiceExportDetails) { //TAMBAHIN DESCRIPTION bodyCell_A.HorizontalAlignment = Element.ALIGN_LEFT; bodyCell_A.Phrase = new Phrase(detail.Description, normal_font); bodyTable_A.AddCell(bodyCell_A); bodyCell_A.Phrase = new Phrase("", normal_font); bodyTable_A.AddCell(bodyCell_A); bodyCell_A.Phrase = new Phrase("", normal_font); bodyTable_A.AddCell(bodyCell_A); bodyCell_A.Phrase = new Phrase("", normal_font); bodyTable_A.AddCell(bodyCell_A); foreach (var item in detail.SalesInvoiceExportItems) { totalPrice = item.QuantityItem.GetValueOrDefault() * item.Price.GetValueOrDefault(); grandTotalPrice += totalPrice; totalLength += item.QuantityItem.GetValueOrDefault(); bodyCell_A.HorizontalAlignment = Element.ALIGN_LEFT; bodyCell_A.Phrase = new Phrase(item.ProductName, normal_font); bodyTable_A.AddCell(bodyCell_A); bodyCell_A.HorizontalAlignment = Element.ALIGN_CENTER; bodyCell_A.Phrase = new Phrase(string.Format("{0:n2}", item.QuantityItem), normal_font); bodyTable_A.AddCell(bodyCell_A); bodyCell_A.Phrase = new Phrase(string.Format("{0:n0}", item.Price), normal_font); bodyTable_A.AddCell(bodyCell_A); bodyCell_A.Phrase = new Phrase(totalPrice.ToString("N2"), normal_font); bodyTable_A.AddCell(bodyCell_A); } } bodyCell_A.HorizontalAlignment = Element.ALIGN_CENTER; bodyCell_A.Phrase = new Phrase("TOTAL", bold_font); bodyTable_A.AddCell(bodyCell_A); bodyCell_A.Phrase = new Phrase(totalLength.ToString("N2"), bold_font); bodyTable_A.AddCell(bodyCell_A); bodyCell_A.Phrase = new Phrase(".............", bold_font); bodyTable_A.AddCell(bodyCell_A); bodyCell_A.Phrase = new Phrase(grandTotalPrice.ToString("N2"), bold_font); bodyTable_A.AddCell(bodyCell_A); document.Add(bodyTable_A); #endregion Body_A double convert = ((double)grandTotalPrice); string ENText = NumberToTextEN.toWords(convert); #region Body_B PdfPTable bodyTable_B = new PdfPTable(2); PdfPTable bodyTable_B1 = new PdfPTable(1); PdfPTable bodyTable_B2 = new PdfPTable(1); bodyTable_B.SetWidths(new float[] { 10f, 10f }); bodyTable_B.WidthPercentage = 100; PdfPCell cellBody_B = new PdfPCell() { Border = Rectangle.NO_BORDER }; PdfPCell bodyCell_A1 = new PdfPCell() { Border = Rectangle.NO_BORDER }; PdfPCell bodyCell_A2 = new PdfPCell() { Border = Rectangle.NO_BORDER }; cellBody_B.Phrase = new Phrase("", normal_font); bodyTable_B1.AddCell(cellBody_B); cellBody_B.Phrase = new Phrase("SAY : " + ENText + "Dollar", normal_font); bodyTable_B1.AddCell(cellBody_B); cellBody_B.Phrase = new Phrase("SHIPPING MARKS : " + viewModel.ShippingRemark, normal_font); bodyTable_B1.AddCell(cellBody_B); bodyCell_A1.AddElement(bodyTable_B1); bodyTable_B.AddCell(bodyCell_A1); cellBody_B.Phrase = new Phrase("", normal_font); bodyTable_B2.AddCell(cellBody_B); cellBody_B.Phrase = new Phrase(viewModel.TermOfPaymentType + " " + viewModel.TermOfPaymentRemark, normal_font); bodyTable_B2.AddCell(cellBody_B); cellBody_B.Phrase = new Phrase("REMARKS : " + viewModel.Remark, normal_font); bodyTable_B2.AddCell(cellBody_B); bodyCell_A2.AddElement(bodyTable_B2); bodyTable_B.AddCell(bodyCell_A2); document.Add(bodyTable_B); #endregion Body_B #endregion Body #region Footer #region Footer_A PdfPTable footerTable_A = new PdfPTable(1); PdfPTable footerTable_A1 = new PdfPTable(2); footerTable_A1.SetWidths(new float[] { 10f, 40f }); footerTable_A1.WidthPercentage = 80; PdfPCell cellFooter_A = new PdfPCell() { Border = Rectangle.NO_BORDER }; PdfPCell footerCell_A1 = new PdfPCell() { Border = Rectangle.NO_BORDER }; footerTable_A.HorizontalAlignment = Element.ALIGN_LEFT; cellFooter_A.HorizontalAlignment = Element.ALIGN_LEFT; cellFooter_A.Phrase = new Phrase("", normal_font); footerTable_A1.AddCell(cellFooter_A); cellFooter_A.Phrase = new Phrase("", normal_font); footerTable_A1.AddCell(cellFooter_A); cellFooter_A.Phrase = new Phrase("", normal_font); footerTable_A1.AddCell(cellFooter_A); cellFooter_A.Phrase = new Phrase("", normal_font); footerTable_A1.AddCell(cellFooter_A); foreach (var detail in viewModel.SalesInvoiceExportDetails) { cellFooter_A.Phrase = new Phrase("GROSS WEIGHT", normal_font); footerTable_A1.AddCell(cellFooter_A); cellFooter_A.Phrase = new Phrase(" : " + detail.GrossWeight + " " + detail.WeightUom + "S", normal_font); footerTable_A1.AddCell(cellFooter_A); cellFooter_A.Phrase = new Phrase("NETT WEIGHT", normal_font); footerTable_A1.AddCell(cellFooter_A); cellFooter_A.Phrase = new Phrase(" : " + detail.NetWeight + " " + detail.WeightUom + "S", normal_font); footerTable_A1.AddCell(cellFooter_A); cellFooter_A.Phrase = new Phrase("TOTAL MEASS.", normal_font); footerTable_A1.AddCell(cellFooter_A); cellFooter_A.Phrase = new Phrase(" : " + detail.TotalMeas + " " + detail.TotalUom, normal_font); footerTable_A1.AddCell(cellFooter_A); } footerCell_A1.AddElement(footerTable_A1); footerTable_A.AddCell(footerCell_A1); document.Add(footerTable_A); #endregion Footer_A #region Footer_B PdfPTable footerTable_B = new PdfPTable(1); PdfPTable footerTable_B1 = new PdfPTable(1); PdfPCell cellFooter_B = new PdfPCell() { Border = Rectangle.NO_BORDER }; PdfPCell footerCell_B1 = new PdfPCell() { Border = Rectangle.NO_BORDER }; footerTable_B.HorizontalAlignment = Element.ALIGN_CENTER; cellFooter_B.HorizontalAlignment = Element.ALIGN_RIGHT; cellFooter_B.Phrase = new Phrase("\n\n\n ( " + viewModel.Authorized + " )", normal_font); footerTable_B1.AddCell(cellFooter_B); cellFooter_B.Phrase = new Phrase("AUTHORIZED SIGNATURE", normal_font); footerTable_B1.AddCell(cellFooter_B); footerCell_B1.AddElement(footerTable_B1); footerTable_B.AddCell(footerCell_B1); document.Add(footerTable_B); #endregion Footer_B #endregion Footer document.Close(); byte[] byteInfo = stream.ToArray(); stream.Write(byteInfo, 0, byteInfo.Length); stream.Position = 0; return(stream); }
public MemoryStream GeneratePdfTemplate(ShinProductionOrderViewModel viewModel, int timeoffset) { Font header_font = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 18); Font normal_font = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 10); Font bold_font = FontFactory.GetFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 10); Document document = new Document(PageSize.A4, 40, 40, 40, 40); MemoryStream stream = new MemoryStream(); PdfWriter writer = PdfWriter.GetInstance(document, stream); document.Open(); #region customViewModel double spelling = viewModel.FinishingPrintingSalesContract.ShippingQuantityTolerance.GetValueOrDefault(); double spellOrder = ((spelling / 100) * viewModel.OrderQuantity) + viewModel.OrderQuantity; #endregion #region Header //string blankString = " "; //Paragraph bankSpace = new Paragraph(blankString, normal_font); //bankSpace.SpacingAfter = 30f; //document.Add(bankSpace); string codeNoString = "FM-PJ-00-03-021/R1"; Paragraph codeNo = new Paragraph(codeNoString, bold_font) { Alignment = Element.ALIGN_RIGHT }; codeNo.SpacingAfter = 20f; document.Add(codeNo); string titleString = "SURAT PERINTAH PRODUKSI"; Paragraph title = new Paragraph(titleString, bold_font) { Alignment = Element.ALIGN_CENTER }; title.SpacingAfter = 20f; document.Add(title); bold_font.SetStyle(Font.NORMAL); #endregion #region body PdfPTable tableIdentity = new PdfPTable(2); tableIdentity.DefaultCell.Border = Rectangle.NO_BORDER; tableIdentity.WidthPercentage = 100; PdfPCell cellIdentityContentLeft = new PdfPCell() { Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT }; PdfPCell cellIdentityContentRight = new PdfPCell() { Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_RIGHT }; PdfPCell cellIdentityContentLeft1WithBorder = new PdfPCell() { HorizontalAlignment = Element.ALIGN_LEFT }; PdfPCell cellIdentityContentRightWithBorder = new PdfPCell() { HorizontalAlignment = Element.ALIGN_RIGHT }; PdfPCell cellIdentityContentCenterWithBorder = new PdfPCell() { HorizontalAlignment = Element.ALIGN_CENTER }; PdfPTable tableIdentity1 = new PdfPTable(2); cellIdentityContentLeft.Phrase = new Phrase("No. Sales Contract", normal_font); tableIdentity1.AddCell(cellIdentityContentLeft); cellIdentityContentLeft.Phrase = new Phrase(": " + viewModel.FinishingPrintingSalesContract.PreSalesContract.No, normal_font); tableIdentity1.AddCell(cellIdentityContentLeft); cellIdentityContentLeft.Phrase = new Phrase("Nomor Order", normal_font); tableIdentity1.AddCell(cellIdentityContentLeft); cellIdentityContentLeft.Phrase = new Phrase(": " + viewModel.ProductionOrderNo, normal_font); tableIdentity1.AddCell(cellIdentityContentLeft); cellIdentityContentLeft.Phrase = new Phrase("Nama Buyer", normal_font); tableIdentity1.AddCell(cellIdentityContentLeft); cellIdentityContentLeft.Phrase = new Phrase(": " + viewModel.FinishingPrintingSalesContract.PreSalesContract.Buyer.Name, normal_font); tableIdentity1.AddCell(cellIdentityContentLeft); cellIdentityContentLeft.Phrase = new Phrase("Tipe Buyer", normal_font); tableIdentity1.AddCell(cellIdentityContentLeft); cellIdentityContentLeft.Phrase = new Phrase(": " + viewModel.FinishingPrintingSalesContract.PreSalesContract.Buyer.Type, normal_font); tableIdentity1.AddCell(cellIdentityContentLeft); cellIdentityContentLeft.Phrase = new Phrase("Material", normal_font); tableIdentity1.AddCell(cellIdentityContentLeft); cellIdentityContentLeft.Phrase = new Phrase(": " + viewModel.FinishingPrintingSalesContract.Material.Name, normal_font); tableIdentity1.AddCell(cellIdentityContentLeft); cellIdentityContentLeft.Phrase = new Phrase("Konstruksi Material", normal_font); tableIdentity1.AddCell(cellIdentityContentLeft); cellIdentityContentLeft.Phrase = new Phrase(": " + viewModel.MaterialConstruction.Name, normal_font); tableIdentity1.AddCell(cellIdentityContentLeft); cellIdentityContentLeft.Phrase = new Phrase("Nomor Benang Material", normal_font); tableIdentity1.AddCell(cellIdentityContentLeft); cellIdentityContentLeft.Phrase = new Phrase(": " + viewModel.FinishingPrintingSalesContract.YarnMaterial.Name, normal_font); tableIdentity1.AddCell(cellIdentityContentLeft); cellIdentityContentLeft.Phrase = new Phrase("Lebar Material", normal_font); tableIdentity1.AddCell(cellIdentityContentLeft); cellIdentityContentLeft.Phrase = new Phrase(": " + viewModel.MaterialWidth, normal_font); tableIdentity1.AddCell(cellIdentityContentLeft); cellIdentityContentLeft.Phrase = new Phrase("Jenis Order", normal_font); tableIdentity1.AddCell(cellIdentityContentLeft); cellIdentityContentLeft.Phrase = new Phrase(": " + viewModel.FinishingPrintingSalesContract.PreSalesContract.ProcessType.OrderType.Name, normal_font); tableIdentity1.AddCell(cellIdentityContentLeft); cellIdentityContentLeft.Phrase = new Phrase("Jenis Proses", normal_font); tableIdentity1.AddCell(cellIdentityContentLeft); cellIdentityContentLeft.Phrase = new Phrase(": " + viewModel.FinishingPrintingSalesContract.PreSalesContract.ProcessType.Name, normal_font); tableIdentity1.AddCell(cellIdentityContentLeft); cellIdentityContentLeft.Phrase = new Phrase("Jumlah Order", normal_font); tableIdentity1.AddCell(cellIdentityContentLeft); cellIdentityContentLeft.Phrase = new Phrase(": " + viewModel.OrderQuantity + " " + viewModel.FinishingPrintingSalesContract.UOM.Unit, normal_font); tableIdentity1.AddCell(cellIdentityContentLeft); cellIdentityContentLeft.Phrase = new Phrase("Jumlah Order + Toleransi Jumlah Kirim", normal_font); tableIdentity1.AddCell(cellIdentityContentLeft); cellIdentityContentLeft.Phrase = new Phrase(": " + spellOrder + " " + viewModel.FinishingPrintingSalesContract.UOM.Unit, normal_font); tableIdentity1.AddCell(cellIdentityContentLeft); cellIdentityContentLeft.Phrase = new Phrase("Asal Material", normal_font); tableIdentity1.AddCell(cellIdentityContentLeft); cellIdentityContentLeft.Phrase = new Phrase(": " + viewModel.MaterialOrigin, normal_font); tableIdentity1.AddCell(cellIdentityContentLeft); //cellIdentityContentLeft.Phrase = new Phrase("Lebar Finish", normal_font); //tableIdentity1.AddCell(cellIdentityContentLeft); //cellIdentityContentLeft.Phrase = new Phrase(": " + viewModel.FinishWidth, normal_font); //tableIdentity1.AddCell(cellIdentityContentLeft); //cellIdentityContentLeft.Phrase = new Phrase("Jenis Finish", normal_font); //tableIdentity1.AddCell(cellIdentityContentLeft); //cellIdentityContentLeft.Phrase = new Phrase(": " + viewModel.FinishType.Name, normal_font); //tableIdentity1.AddCell(cellIdentityContentLeft); //if (!string.IsNullOrWhiteSpace(viewModel.DesignCode) && !string.IsNullOrWhiteSpace(viewModel.DesignNumber)) //{ // cellIdentityContentLeft.Phrase = new Phrase("Kode Design", normal_font); // tableIdentity1.AddCell(cellIdentityContentLeft); // cellIdentityContentLeft.Phrase = new Phrase(": " + viewModel.DesignCode, normal_font); // tableIdentity1.AddCell(cellIdentityContentLeft); // cellIdentityContentLeft.Phrase = new Phrase("Nomor Design", normal_font); // tableIdentity1.AddCell(cellIdentityContentLeft); // cellIdentityContentLeft.Phrase = new Phrase(": " + viewModel.DesignNumber, normal_font); // tableIdentity1.AddCell(cellIdentityContentLeft); //} cellIdentityContentLeft.Phrase = new Phrase("Standar Handling", normal_font); tableIdentity1.AddCell(cellIdentityContentLeft); cellIdentityContentLeft.Phrase = new Phrase(": " + viewModel.HandlingStandard, normal_font); tableIdentity1.AddCell(cellIdentityContentLeft); cellIdentityContentLeft.Phrase = new Phrase("RUN", normal_font); tableIdentity1.AddCell(cellIdentityContentLeft); cellIdentityContentLeft.Phrase = new Phrase(": " + viewModel.Run, normal_font); tableIdentity1.AddCell(cellIdentityContentLeft); string runWidth = ""; if (viewModel.RunWidth != null) { runWidth = string.Join(',', viewModel.RunWidth.Select(x => x.Value)); } cellIdentityContentLeft.Phrase = new Phrase("Lebar RUN (cm)", normal_font); tableIdentity1.AddCell(cellIdentityContentLeft); cellIdentityContentLeft.Phrase = new Phrase(": " + runWidth, normal_font); tableIdentity1.AddCell(cellIdentityContentLeft); cellIdentityContentLeft.Phrase = new Phrase("Tulisan Pinggir Kain", normal_font); tableIdentity1.AddCell(cellIdentityContentLeft); cellIdentityContentLeft.Phrase = new Phrase(": " + viewModel.ArticleFabricEdge, normal_font); tableIdentity1.AddCell(cellIdentityContentLeft); if (!string.IsNullOrWhiteSpace(viewModel.Run) && viewModel.RunWidth != null && (viewModel.RunWidth.Count > 0)) { var index = 0; foreach (ProductionOrder_RunWidthViewModel runwidths in viewModel.RunWidth) { index++; cellIdentityContentLeft.Phrase = new Phrase("Lebar RUN (cm)", normal_font); tableIdentity1.AddCell(cellIdentityContentLeft); if (index > 1) { cellIdentityContentLeft.Phrase = new Phrase(" " + runwidths.Value, normal_font); tableIdentity1.AddCell(cellIdentityContentLeft); } else { cellIdentityContentLeft.Phrase = new Phrase(": " + runwidths.Value, normal_font); tableIdentity1.AddCell(cellIdentityContentLeft); } } } cellIdentityContentLeft.Phrase = new Phrase("Standar Shrinkage", normal_font); tableIdentity1.AddCell(cellIdentityContentLeft); cellIdentityContentLeft.Phrase = new Phrase(": " + viewModel.ShrinkageStandard, normal_font); tableIdentity1.AddCell(cellIdentityContentLeft); cellIdentityContentLeft.Phrase = new Phrase("Standar Test", normal_font); tableIdentity1.AddCell(cellIdentityContentLeft); cellIdentityContentLeft.Phrase = new Phrase(": " + viewModel.StandardTests.Name, normal_font); tableIdentity1.AddCell(cellIdentityContentLeft); //cellIdentityContentLeft.Phrase = new Phrase("Sample", normal_font); //tableIdentity1.AddCell(cellIdentityContentLeft); //cellIdentityContentLeft.Phrase = new Phrase(": " + viewModel.Sample, normal_font); //tableIdentity1.AddCell(cellIdentityContentLeft); cellIdentityContentLeft.Phrase = new Phrase("Packing Instruction", normal_font); tableIdentity1.AddCell(cellIdentityContentLeft); cellIdentityContentLeft.Phrase = new Phrase(": " + viewModel.FinishingPrintingSalesContract.Packing, normal_font); tableIdentity1.AddCell(cellIdentityContentLeft); cellIdentityContentLeft.Phrase = new Phrase("Tanggal Delivery", normal_font); tableIdentity1.AddCell(cellIdentityContentLeft); cellIdentityContentLeft.Phrase = new Phrase(": " + viewModel.DeliveryDate.AddHours(timeoffset).ToString("dd MMMM yyyy", new CultureInfo("id-ID")), normal_font); tableIdentity1.AddCell(cellIdentityContentLeft); cellIdentityContentLeft.Phrase = new Phrase("Keterangan", normal_font); tableIdentity1.AddCell(cellIdentityContentLeft); cellIdentityContentLeft.Phrase = new Phrase(": " + viewModel.Remark, normal_font); tableIdentity1.AddCell(cellIdentityContentLeft); cellIdentityContentLeft.Phrase = new Phrase("Nama Staff Penjualan", normal_font); tableIdentity1.AddCell(cellIdentityContentLeft); cellIdentityContentLeft.Phrase = new Phrase(": " + viewModel.Account.FirstName + " " + viewModel.Account.LastName, normal_font); tableIdentity1.AddCell(cellIdentityContentLeft); cellIdentityContentLeft.Phrase = new Phrase("Tanggal Order dibuat", normal_font); tableIdentity1.AddCell(cellIdentityContentLeft); cellIdentityContentLeft.Phrase = new Phrase(": " + viewModel.CreatedUtc.AddHours(timeoffset).ToString("dd MMMM yyyy", new CultureInfo("id-ID")), normal_font); tableIdentity1.AddCell(cellIdentityContentLeft); PdfPCell cell = new PdfPCell(); cell.BorderColor = BaseColor.White; PdfPTable tableBody1 = new PdfPTable(1); cellIdentityContentCenterWithBorder.Phrase = new Phrase("Standar Lampu", normal_font); tableBody1.AddCell(cellIdentityContentCenterWithBorder); if (viewModel.LampStandards.Count > 0) { foreach (var item in viewModel.LampStandards) { cellIdentityContentCenterWithBorder.Phrase = new Phrase(item.Name, normal_font); tableBody1.AddCell(cellIdentityContentCenterWithBorder); } } tableBody1.SpacingAfter = 30f; PdfPTable tableBody2 = new PdfPTable(4); cellIdentityContentCenterWithBorder.Phrase = new Phrase("Acuan / Color Way", normal_font); tableBody2.AddCell(cellIdentityContentCenterWithBorder); cellIdentityContentCenterWithBorder.Phrase = new Phrase("Warna yang Diminta ", normal_font); tableBody2.AddCell(cellIdentityContentCenterWithBorder); cellIdentityContentCenterWithBorder.Phrase = new Phrase("Jenis Warna", normal_font); tableBody2.AddCell(cellIdentityContentCenterWithBorder); cellIdentityContentCenterWithBorder.Phrase = new Phrase("Jumlah", normal_font); tableBody2.AddCell(cellIdentityContentCenterWithBorder); double Total = 0; string uom = ""; if (viewModel.Details.Count > 0) { foreach (var detail in viewModel.Details) { uom = detail.Uom.Unit; cellIdentityContentCenterWithBorder.Phrase = new Phrase(detail.ColorTemplate, normal_font); tableBody2.AddCell(cellIdentityContentCenterWithBorder); cellIdentityContentCenterWithBorder.Phrase = new Phrase(detail.ColorRequest, normal_font); tableBody2.AddCell(cellIdentityContentCenterWithBorder); cellIdentityContentCenterWithBorder.Phrase = new Phrase(detail.ColorType.Name, normal_font); tableBody2.AddCell(cellIdentityContentCenterWithBorder); cellIdentityContentCenterWithBorder.Phrase = new Phrase(detail.Quantity.ToString() + " " + detail.Uom.Unit, normal_font); tableBody2.AddCell(cellIdentityContentCenterWithBorder); Total += (double)detail.Quantity; } } cellIdentityContentCenterWithBorder.Phrase = new Phrase("Total", normal_font); tableBody2.AddCell(new PdfPCell(cellIdentityContentCenterWithBorder) { Colspan = 3 }); cellIdentityContentCenterWithBorder.Phrase = new Phrase(string.Format("{0:n2}", Total) + " " + uom, normal_font); tableBody2.AddCell(cellIdentityContentCenterWithBorder); cell.AddElement(tableBody1); cell.AddElement(tableBody2); tableIdentity.AddCell(tableIdentity1); tableIdentity.AddCell(cell); PdfPCell signatureCellAgent = new PdfPCell(tableIdentity); // dont remove tableIdentity.ExtendLastRow = false; tableIdentity.SpacingAfter = 10f; document.Add(tableIdentity); #endregion #region signature PdfPTable tableSignatureRegion = new PdfPTable(4); tableSignatureRegion.SpacingBefore = 30f; cellIdentityContentCenterWithBorder.Phrase = new Phrase("DIBUAT OLEH", normal_font); tableSignatureRegion.AddCell(cellIdentityContentCenterWithBorder); cellIdentityContentCenterWithBorder.Phrase = new Phrase("MENGETAHUI", normal_font); tableSignatureRegion.AddCell(cellIdentityContentCenterWithBorder); cellIdentityContentCenterWithBorder.Phrase = new Phrase("MENYETUJUI", normal_font); tableSignatureRegion.AddCell(new PdfPCell(cellIdentityContentCenterWithBorder) { Colspan = 2 }); string signatureArea = string.Empty; for (int i = 0; i < 5; i++) { signatureArea += Environment.NewLine; } cellIdentityContentCenterWithBorder.Phrase = new Phrase(signatureArea, normal_font); tableSignatureRegion.AddCell(cellIdentityContentCenterWithBorder); cellIdentityContentCenterWithBorder.Phrase = new Phrase(signatureArea, normal_font); tableSignatureRegion.AddCell(cellIdentityContentCenterWithBorder); cellIdentityContentCenterWithBorder.Phrase = new Phrase(signatureArea, normal_font); tableSignatureRegion.AddCell(cellIdentityContentCenterWithBorder); cellIdentityContentCenterWithBorder.Phrase = new Phrase(signatureArea, normal_font); tableSignatureRegion.AddCell(cellIdentityContentCenterWithBorder); cellIdentityContentCenterWithBorder.Phrase = new Phrase("PENJUALAN", normal_font); tableSignatureRegion.AddCell(cellIdentityContentCenterWithBorder); cellIdentityContentCenterWithBorder.Phrase = new Phrase("KABAG PENJUALAN", normal_font); tableSignatureRegion.AddCell(cellIdentityContentCenterWithBorder); cellIdentityContentCenterWithBorder.Phrase = new Phrase("KABAG F/P", normal_font); tableSignatureRegion.AddCell(cellIdentityContentCenterWithBorder); cellIdentityContentCenterWithBorder.Phrase = new Phrase("PPIC F/P", normal_font); tableSignatureRegion.AddCell(cellIdentityContentCenterWithBorder); PdfPCell tableSignatureRegionCell = new PdfPCell(tableSignatureRegion); // dont remove tableSignatureRegion.ExtendLastRow = false; document.Add(tableSignatureRegion); #endregion document.Close(); byte[] byteInfo = stream.ToArray(); stream.Write(byteInfo, 0, byteInfo.Length); stream.Position = 0; return(stream); }
private void ColumnHeaders(PdfPTable headerTable) { PdfPCell cell; cell = new PdfPCell(new Phrase("Customer: " + ReportObject.CustomerName, ReportFontBold)); cell.Border = Rectangle.NO_BORDER; cell.HorizontalAlignment = Element.ALIGN_LEFT; cell.Colspan = 5; headerTable.AddCell(cell); cell = new PdfPCell(new Phrase("Total Layaway Amt: $ " + ReportObject.CurrentLayaway.Amount.ToString(), ReportFontBold)); cell.Border = Rectangle.NO_BORDER; cell.HorizontalAlignment = Element.ALIGN_LEFT; cell.Colspan = 2; headerTable.AddCell(cell); //draw line cell = new PdfPCell(new Phrase(StringUtilities.fillString("_", 140), ReportFont)); cell.Colspan = 7; cell.HorizontalAlignment = Rectangle.ALIGN_LEFT; cell.Border = Rectangle.NO_BORDER; headerTable.AddCell(cell); //Column headers cell = new PdfPCell(new Phrase("ICN", ReportFontBold)); cell.Colspan = 2; cell.HorizontalAlignment = Rectangle.ALIGN_LEFT; cell.Border = Rectangle.NO_BORDER; headerTable.AddCell(cell); Phrase descPhraseText = new Phrase("", ReportFontSmall); descPhraseText.Add(new Phrase(" ", ReportFontBold)); descPhraseText.Add(new Phrase("Description", ReportFontBold)); //cell = new PdfPCell(new Phrase("Description", ReportFontBold)); //descPhrase.Add(descPhraseText); cell = new PdfPCell(); cell.Colspan = 3; cell.HorizontalAlignment = Rectangle.ALIGN_LEFT; cell.VerticalAlignment = Rectangle.ALIGN_TOP; cell.Border = Rectangle.NO_BORDER; cell.AddElement(descPhraseText); headerTable.AddCell(cell); Phrase qtyPhrase = new Phrase("", ReportFontSmall); qtyPhrase.Add(new Phrase(" ", ReportFontSmall)); qtyPhrase.Add(new Phrase("Qty", ReportFontBold)); //qtyPhrase.Add(qtyPhraseText); cell = new PdfPCell(); //cell = new PdfPCell(new Phrase("Qty", ReportFontBold)); cell.Colspan = 1; cell.HorizontalAlignment = Rectangle.ALIGN_LEFT; cell.VerticalAlignment = Rectangle.ALIGN_TOP; cell.Border = Rectangle.NO_BORDER; cell.AddElement(qtyPhrase); headerTable.AddCell(cell); cell = new PdfPCell(new Phrase("Aisle/Shelf Loc.", ReportFontBold)); cell.Colspan = 1; cell.HorizontalAlignment = Rectangle.ALIGN_LEFT; cell.Border = Rectangle.NO_BORDER; headerTable.AddCell(cell); cell = new PdfPCell(new Phrase(StringUtilities.fillString("-", 233), ReportFont)); cell.Colspan = 7; cell.HorizontalAlignment = Rectangle.ALIGN_LEFT; cell.Border = Rectangle.NO_BORDER; headerTable.AddCell(cell); }
private void listaDeInscriçõesToolStripMenuItem_Click(object sender, EventArgs e) { try { Eventos eventoSelecionado = (Eventos)listViewEventos.SelectedItems[0].Tag; saveFileDialog_Save.FileName = "ListaInscricoes_" + eventoSelecionado.Descricao + ".pdf"; saveFileDialog_Save.Filter = "All files (*.*)|*.*"; saveFileDialog_Save.FilterIndex = 0; if (saveFileDialog_Save.ShowDialog() == DialogResult.OK) { Document doc = new Document(PageSize.A4); doc.SetMargins(60, 60, 30, 30); PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(saveFileDialog_Save.FileName, FileMode.Create)); doc.Open(); //Font fontH1 = new Font(Currier, 16, Font.Bold); // <---------------- Título ----------------> Paragraph titulo = new Paragraph("Lista de Inscrições\n"); titulo.Alignment = Element.TITLE; // <---------------- Informações sobre o Evento ----------------> Paragraph evento = new Paragraph("\n\nEvento: " + eventoSelecionado.Descricao); Paragraph local = new Paragraph("Local: " + eventoSelecionado.Local); Paragraph data = new Paragraph(string.Format("Data: {0:dd} de {0:MMMM} de {0:yyyy}", eventoSelecionado.DataHora)); Paragraph hora = new Paragraph(string.Format("Hora: {0:HH:mm:ss}", eventoSelecionado.DataHora)); Paragraph limite = new Paragraph("Limite de Participação: " + eventoSelecionado.LimiteParticipacao + " crianças"); Paragraph idadeInf = new Paragraph("Idade Mínima: " + eventoSelecionado.IdadeInferior + " anos"); Paragraph idadeSup = new Paragraph("Idade Máxima: " + eventoSelecionado.IdadeSuperior + " anos\n\n\n\n"); evento.Alignment = Element.ALIGN_JUSTIFIED; local.Alignment = Element.ALIGN_JUSTIFIED; data.Alignment = Element.ALIGN_JUSTIFIED; hora.Alignment = Element.ALIGN_JUSTIFIED; limite.Alignment = Element.ALIGN_JUSTIFIED; idadeInf.Alignment = Element.ALIGN_JUSTIFIED; idadeSup.Alignment = Element.ALIGN_JUSTIFIED; // <---------------- Tabela ----------------> PdfPTable table = new PdfPTable(5); Paragraph coluna1 = new Paragraph("Nome"); Paragraph coluna2 = new Paragraph("Idade"); Paragraph coluna3 = new Paragraph("Responsável"); Paragraph coluna4 = new Paragraph("Telefone"); Paragraph coluna5 = new Paragraph("Telemóvel"); coluna1.Alignment = Element.ALIGN_CENTER; coluna2.Alignment = Element.ALIGN_CENTER; coluna3.Alignment = Element.ALIGN_CENTER; coluna4.Alignment = Element.ALIGN_CENTER; coluna5.Alignment = Element.ALIGN_CENTER; var cell1 = new PdfPCell(); var cell2 = new PdfPCell(); var cell3 = new PdfPCell(); var cell4 = new PdfPCell(); var cell5 = new PdfPCell(); cell1.AddElement(coluna1); cell2.AddElement(coluna2); cell3.AddElement(coluna3); cell4.AddElement(coluna4); cell5.AddElement(coluna5); table.AddCell(cell1); table.AddCell(cell2); table.AddCell(cell3); table.AddCell(cell4); table.AddCell(cell5); foreach (Inscricoes i in eventoSelecionado.Inscricoes.ToList <Inscricoes>()) { Phrase nome = new Phrase(i.Filhos.Nome); var cell = new PdfPCell(nome); table.AddCell(cell); Phrase idade = new Phrase(Convert.ToString(i.Filhos.Idade())); cell = new PdfPCell(idade); table.AddCell(cell); Phrase responsavel = new Phrase(i.Filhos.Clientes.Nome); cell = new PdfPCell(responsavel); table.AddCell(cell); Phrase telefone = new Phrase(i.Filhos.Telefone); cell = new PdfPCell(telefone); table.AddCell(cell); Phrase telemovel = new Phrase(i.Filhos.Telemovel); cell = new PdfPCell(telemovel); table.AddCell(cell); } // <---------------- Adicionar os dados todos ao documento ----------------> doc.Add(titulo); doc.Add(evento); doc.Add(local); doc.Add(data); doc.Add(hora); doc.Add(limite); doc.Add(idadeInf); doc.Add(idadeSup); doc.Add(table); doc.Close(); MessageBox.Show("Lista de Inscrições guardada com sucesso!", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information); } } catch { MessageBox.Show("Selecione o evento primeiro!", "Aviso", MessageBoxButtons.OK, MessageBoxIcon.Information); } }
public MemoryStream GeneratePdfTemplate(GarmentPackingListViewModel viewModel, string fob, string cprice) { //int maxSizesCount = viewModel.Items.Max(i => i.Details.Max(d => d.Sizes.GroupBy(g => g.Size.Id).Count())); var newItems = new List <GarmentPackingListItemViewModel>(); var newItems2 = new List <GarmentPackingListItemViewModel>(); var newDetails = new List <GarmentPackingListDetailViewModel>(); foreach (var item in viewModel.Items) { foreach (var detail in item.Details) { newDetails.Add(detail); } } // if wanna group by order no delete the note by @zhikariz newDetails = newDetails.OrderBy(a => a.Index).ThenBy(o => o.Carton1).ThenBy(o => o.Carton2).ToList(); foreach (var d in newDetails) { if (newItems.Count == 0) { var i = viewModel.Items.Single(a => a.Id == d.PackingListItemId); i.Details = new List <GarmentPackingListDetailViewModel>(); i.Details.Add(d); newItems.Add(i); } else { if (newItems.Last().Id == d.PackingListItemId) { newItems.Last().Details.Add(d); } else { var y = viewModel.Items.Select(a => new GarmentPackingListItemViewModel { Id = a.Id, RONo = a.RONo, Article = a.Article, BuyerAgent = a.BuyerAgent, ComodityDescription = a.ComodityDescription, OrderNo = a.OrderNo, AVG_GW = a.AVG_GW, AVG_NW = a.AVG_NW, Description = a.Description }) .Single(a => a.Id == d.PackingListItemId); y.Details = new List <GarmentPackingListDetailViewModel>(); y.Details.Add(d); newItems.Add(y); } } } foreach (var item in newItems) { if (newItems2.Count == 0) { newItems2.Add(item); } else { if (newItems2.Last().OrderNo == item.OrderNo) { foreach (var d in item.Details.OrderBy(a => a.Carton1)) { newItems2.Last().Details.Add(d); } } else { newItems2.Add(item); } } } var sizesCount = false; foreach (var item in newItems2) { var sizesMax = new Dictionary <int, string>(); foreach (var detail in item.Details.OrderBy(a => a.Carton1).ThenBy(a => a.Carton2)) { foreach (var size in detail.Sizes) { sizesMax[size.Size.Id] = size.Size.Size; } } if (sizesMax.Count > 11) { sizesCount = true; } } int SIZES_COUNT = sizesCount ? 20 : 11; Font header_font = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 14); Font normal_font = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 8); Font body_font = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 8); Font normal_font_underlined = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 8, Font.UNDERLINE); Font bold_font = FontFactory.GetFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 8); Document document = new Document(sizesCount ? PageSize.A4.Rotate() : PageSize.A4, 20, 20, 170, 30); MemoryStream stream = new MemoryStream(); PdfWriter writer = PdfWriter.GetInstance(document, stream); writer.PageEvent = new GarmentPackingListPdfByOrderNoPageEvent(_identityProvider, viewModel); document.Open(); #region Description PdfPTable tableDescription = new PdfPTable(3); tableDescription.SetWidths(new float[] { 2f, 0.2f, 7.8f }); PdfPCell cellDescription = new PdfPCell() { Border = Rectangle.NO_BORDER }; cellDescription.Phrase = new Phrase(cprice, normal_font); tableDescription.AddCell(cellDescription); cellDescription.Phrase = new Phrase(":", normal_font); tableDescription.AddCell(cellDescription); cellDescription.Phrase = new Phrase(fob, normal_font); tableDescription.AddCell(cellDescription); if (viewModel.PaymentTerm == "LC") { cellDescription.Phrase = new Phrase("LC No.", normal_font); tableDescription.AddCell(cellDescription); cellDescription.Phrase = new Phrase(":", normal_font); tableDescription.AddCell(cellDescription); cellDescription.Phrase = new Phrase(viewModel.LCNo, normal_font); tableDescription.AddCell(cellDescription); cellDescription.Phrase = new Phrase("Tgl. LC", normal_font); tableDescription.AddCell(cellDescription); cellDescription.Phrase = new Phrase(":", normal_font); tableDescription.AddCell(cellDescription); cellDescription.Phrase = new Phrase(viewModel.LCDate.GetValueOrDefault().ToOffset(new TimeSpan(_identityProvider.TimezoneOffset, 0, 0)).ToString("dd MMMM yyyy"), normal_font); tableDescription.AddCell(cellDescription); cellDescription.Phrase = new Phrase("ISSUED BY", normal_font); tableDescription.AddCell(cellDescription); cellDescription.Phrase = new Phrase(":", normal_font); tableDescription.AddCell(cellDescription); cellDescription.Phrase = new Phrase(viewModel.IssuedBy, normal_font); tableDescription.AddCell(cellDescription); } else { cellDescription.Phrase = new Phrase("Payment Term", normal_font); tableDescription.AddCell(cellDescription); cellDescription.Phrase = new Phrase(":", normal_font); tableDescription.AddCell(cellDescription); cellDescription.Phrase = new Phrase(viewModel.PaymentTerm, normal_font); tableDescription.AddCell(cellDescription); } new PdfPCell(tableDescription); tableDescription.ExtendLastRow = false; tableDescription.SpacingAfter = 5f; document.Add(tableDescription); #endregion PdfPCell cellBorderBottomRight = new PdfPCell() { Border = Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER | Rectangle.LEFT_BORDER, HorizontalAlignment = Element.ALIGN_CENTER }; PdfPCell cellBorderBottom = new PdfPCell() { Border = Rectangle.BOTTOM_BORDER, HorizontalAlignment = Element.ALIGN_CENTER }; double totalCtns = 0; double grandTotal = 0; var uom = ""; var arrayGrandTotal = new Dictionary <String, double>(); List <string> cartonNumbers = new List <string>(); //foreach (var x in viewModel.Items.OrderBy(o => o.RONo)) //{ // if (newItems.Count == 0) // { // newItems.Add(x); // } // else // { // if (newItems.Last().OrderNo == x.OrderNo && newItems.Last().Description == x.Description) // { // foreach (var d in x.Details.OrderBy(a => a.Carton1)) // { // newItems.Last().Details.Add(d); // } // } // else // { // var y = viewModel.Items.Select(a => new GarmentPackingListItemViewModel // { // Id = a.Id, // RONo = a.RONo, // Description = a.Description, // Article = a.Article, // BuyerAgent = a.BuyerAgent, // ComodityDescription = a.ComodityDescription, // OrderNo = a.OrderNo, // AVG_GW = a.AVG_GW, // AVG_NW = a.AVG_NW, // Uom = a.Uom // }) // .Single(a => a.OrderNo == x.OrderNo && a.Description == x.Description); // y.Details = new List<GarmentPackingListDetailViewModel>(); // foreach (var d in x.Details.OrderBy(a => a.Carton1)) // { // y.Details.Add(d); // } // newItems.Add(y); // } // } //} foreach (var item in newItems2) { #region Item PdfPTable tableItem = new PdfPTable(3); tableItem.SetWidths(new float[] { 2f, 0.2f, 7.8f }); PdfPCell cellItemContent = new PdfPCell() { Border = Rectangle.NO_BORDER }; cellItemContent.Phrase = new Phrase("DESCRIPTION OF GOODS", normal_font); tableItem.AddCell(cellItemContent); cellItemContent.Phrase = new Phrase(":", normal_font); tableItem.AddCell(cellItemContent); cellItemContent.Phrase = new Phrase(item.Description, normal_font); tableItem.AddCell(cellItemContent); new PdfPCell(tableItem); tableItem.ExtendLastRow = false; document.Add(tableItem); #endregion var sizes = new Dictionary <int, string>(); foreach (var detail in item.Details) { foreach (var size in detail.Sizes) { sizes[size.Size.Id] = size.Size.Size; } } PdfPTable tableDetail = new PdfPTable(SIZES_COUNT + 11); var width = new List <float> { 2f, 3.5f, 4f, 4f }; for (int i = 0; i < SIZES_COUNT; i++) { width.Add(1f); } width.AddRange(new List <float> { 1.5f, 1f, 1.5f, 2f, 1.5f, 1.5f, 1.5f }); tableDetail.SetWidths(width.ToArray()); PdfPCell cellDetailLine = new PdfPCell() { Border = Rectangle.BOTTOM_BORDER, Colspan = 19, Padding = 0.5f, Phrase = new Phrase("") }; tableDetail.AddCell(cellDetailLine); tableDetail.AddCell(cellDetailLine); cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("CARTON NO.", normal_font, 0.75f)); cellBorderBottomRight.Rowspan = 2; tableDetail.AddCell(cellBorderBottomRight); cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("COLOUR", normal_font, 0.75f)); tableDetail.AddCell(cellBorderBottomRight); cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("STYLE", normal_font, 0.75f)); tableDetail.AddCell(cellBorderBottomRight); cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("ORDER NO.", normal_font, 0.75f)); tableDetail.AddCell(cellBorderBottomRight); cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("S I Z E", normal_font, 0.75f)); cellBorderBottomRight.Colspan = SIZES_COUNT; cellBorderBottomRight.Rowspan = 1; tableDetail.AddCell(cellBorderBottomRight); cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("CTNS", normal_font, 0.75f)); cellBorderBottomRight.Colspan = 1; cellBorderBottomRight.Rowspan = 2; tableDetail.AddCell(cellBorderBottomRight); cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("@", normal_font, 0.75f)); tableDetail.AddCell(cellBorderBottomRight); cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("QTY", normal_font, 0.75f)); tableDetail.AddCell(cellBorderBottomRight); cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("SATUAN", normal_font, 0.75f)); tableDetail.AddCell(cellBorderBottomRight); cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("GW/\nCTN", normal_font, 0.75f)); cellBorderBottomRight.Rowspan = 2; tableDetail.AddCell(cellBorderBottomRight); cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("NW/\nCTN", normal_font, 0.75f)); tableDetail.AddCell(cellBorderBottomRight); cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("NNW/\nCTN", normal_font, 0.75f)); tableDetail.AddCell(cellBorderBottomRight); cellBorderBottomRight.Rowspan = 1; for (int i = 0; i < SIZES_COUNT; i++) { var size = sizes.OrderBy(a => a.Value).ElementAtOrDefault(i); cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(size.Key == 0 ? "" : size.Value, normal_font, 0.5f)); cellBorderBottomRight.Rowspan = 1; tableDetail.AddCell(cellBorderBottomRight); } double subCtns = 0; double subTotal = 0; var sizeSumQty = new Dictionary <int, double>(); var arraySubTotal = new Dictionary <String, double>(); foreach (var detail in item.Details.OrderBy(a => a.Carton1).ThenBy(a => a.Carton2)) { var ctnsQty = detail.CartonQuantity; var article = viewModel.Items.Where(a => a.Id == detail.PackingListItemId).Single().Article; uom = viewModel.Items.Where(a => a.Id == detail.PackingListItemId).Single().Uom.Unit; if (cartonNumbers.Contains($"{detail.Index} - {detail.Carton1}- {detail.Carton2}")) { ctnsQty = 0; } else { cartonNumbers.Add($"{detail.Index} - {detail.Carton1}- {detail.Carton2}"); } cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk($"{detail.Carton1}- {detail.Carton2}", normal_font, 0.6f)); tableDetail.AddCell(cellBorderBottomRight); cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(detail.Colour, normal_font, 0.6f)); tableDetail.AddCell(cellBorderBottomRight); cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(detail.Style, normal_font, 0.6f)); tableDetail.AddCell(cellBorderBottomRight); cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(item.OrderNo, normal_font, 0.6f)); tableDetail.AddCell(cellBorderBottomRight); for (int i = 0; i < SIZES_COUNT; i++) { var size = sizes.OrderBy(a => a.Value).ElementAtOrDefault(i); double quantity = 0; if (size.Key != 0) { quantity = detail.Sizes.Where(w => w.Size.Id == size.Key).Sum(s => s.Quantity); } if (sizeSumQty.ContainsKey(size.Key)) { sizeSumQty[size.Key] += quantity * detail.CartonQuantity; } else { sizeSumQty.Add(size.Key, quantity * detail.CartonQuantity); } cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(quantity == 0 ? "" : quantity.ToString(), normal_font, 0.6f)); tableDetail.AddCell(cellBorderBottomRight); } subCtns += ctnsQty; cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(ctnsQty.ToString(), normal_font, 0.6f)); tableDetail.AddCell(cellBorderBottomRight); cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(detail.QuantityPCS.ToString(), normal_font, 0.6f)); tableDetail.AddCell(cellBorderBottomRight); var totalQuantity = (detail.CartonQuantity * detail.QuantityPCS); subTotal += totalQuantity; if (!arraySubTotal.ContainsKey(uom)) { arraySubTotal.Add(uom, totalQuantity); } else { arraySubTotal[uom] += totalQuantity; } cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(totalQuantity.ToString(), normal_font, 0.6f)); tableDetail.AddCell(cellBorderBottomRight); cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(uom, normal_font, 0.6f)); tableDetail.AddCell(cellBorderBottomRight); cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(string.Format("{0:n2}", detail.GrossWeight), normal_font, 0.6f)); tableDetail.AddCell(cellBorderBottomRight); cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(string.Format("{0:n2}", detail.NetWeight), normal_font, 0.6f)); tableDetail.AddCell(cellBorderBottomRight); cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(string.Format("{0:n2}", detail.NetNetWeight), normal_font, 0.6f)); tableDetail.AddCell(cellBorderBottomRight); } cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("", normal_font, 0.6f)); tableDetail.AddCell(cellBorderBottomRight); cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("", normal_font, 0.6f)); tableDetail.AddCell(cellBorderBottomRight); cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("", normal_font, 0.6f)); tableDetail.AddCell(cellBorderBottomRight); cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("SUMMARY", normal_font, 0.6f)); tableDetail.AddCell(cellBorderBottomRight); for (int i = 0; i < SIZES_COUNT; i++) { var size = sizes.OrderBy(a => a.Value).ElementAtOrDefault(i); double quantity = 0; if (size.Key != 0) { quantity = sizeSumQty.Where(w => w.Key == size.Key).Sum(a => a.Value); } cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(quantity == 0 ? "" : quantity.ToString(), normal_font, 0.6f)); tableDetail.AddCell(cellBorderBottomRight); } cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("", normal_font, 0.6f)); tableDetail.AddCell(cellBorderBottomRight); cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("", normal_font, 0.6f)); tableDetail.AddCell(cellBorderBottomRight); cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("", normal_font, 0.6f)); tableDetail.AddCell(cellBorderBottomRight); cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("", normal_font, 0.6f)); tableDetail.AddCell(cellBorderBottomRight); cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("", normal_font, 0.6f)); tableDetail.AddCell(cellBorderBottomRight); cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("", normal_font, 0.6f)); tableDetail.AddCell(cellBorderBottomRight); cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("", normal_font, 0.6f)); tableDetail.AddCell(cellBorderBottomRight); totalCtns += subCtns; grandTotal += subTotal; if (!arrayGrandTotal.ContainsKey(uom)) { arrayGrandTotal.Add(uom, subTotal); } else { arrayGrandTotal[uom] += subTotal; } tableDetail.AddCell(new PdfPCell() { Border = Rectangle.BOTTOM_BORDER, Colspan = SIZES_COUNT + 7, Padding = 5, Phrase = new Phrase("SUB TOTAL ....................................................................................................................................................................... ", normal_font) }); var subTotalResult = string.Join(" / ", arraySubTotal.Select(x => x.Value + " " + x.Key).ToArray()); cellBorderBottom.Phrase = new Phrase(subTotalResult, normal_font); cellBorderBottom.Colspan = 2; tableDetail.AddCell(cellBorderBottom); cellBorderBottom.Phrase = new Phrase("", normal_font); cellBorderBottom.Colspan = 3; tableDetail.AddCell(cellBorderBottom); cellBorderBottom.Colspan = 1; tableDetail.AddCell(new PdfPCell() { Border = Rectangle.BOTTOM_BORDER, Colspan = SIZES_COUNT + 11, Phrase = new Phrase($" - Sub Ctns = {subCtns} - Sub G.W. = {String.Format("{0:0.00}", item.Details.Sum(a => a.GrossWeight * a.CartonQuantity))} Kgs - Sub N.W. = {String.Format("{0:0.00}", item.Details.Sum(a => a.NetWeight * a.CartonQuantity))} Kgs - Sub N.N.W. = {String.Format("{0:0.00}", item.Details.Sum(a => a.NetNetWeight * a.CartonQuantity))} Kgs", normal_font) }); new PdfPCell(tableDetail); tableDetail.ExtendLastRow = false; tableDetail.KeepTogether = true; tableDetail.WidthPercentage = 95f; tableDetail.SpacingAfter = 10f; document.Add(tableDetail); } #region GrandTotal PdfPTable tableGrandTotal = new PdfPTable(2); tableGrandTotal.SetWidths(new float[] { 18f + SIZES_COUNT * 1f, 3f }); PdfPCell cellHeaderLine = new PdfPCell() { Border = Rectangle.BOTTOM_BORDER, Colspan = 2, Padding = 0.5f, Phrase = new Phrase("") }; var grandTotalResult = string.Join(" / ", arrayGrandTotal.Select(x => x.Value + " " + x.Key).ToArray()); tableGrandTotal.AddCell(cellHeaderLine); tableGrandTotal.AddCell(new PdfPCell() { Border = Rectangle.BOTTOM_BORDER, Padding = 6, Phrase = new Phrase("GRAND TOTAL ...................................................................................................................................................................................", normal_font) }); tableGrandTotal.AddCell(new PdfPCell() { Border = Rectangle.BOTTOM_BORDER, Padding = 4, HorizontalAlignment = Element.ALIGN_CENTER, Phrase = new Phrase(grandTotalResult, normal_font) }); tableGrandTotal.AddCell(cellHeaderLine); var comodities = viewModel.Items.Select(s => s.Comodity.Name.ToUpper()).Distinct(); tableGrandTotal.AddCell(new PdfPCell() { Border = Rectangle.NO_BORDER, Colspan = 2, Padding = 5, Phrase = new Phrase($"{totalCtns} {viewModel.SayUnit} [ {NumberToTextEN.toWords(totalCtns).Trim().ToUpper()} {viewModel.SayUnit} OF {string.Join(" AND ", comodities)}]", normal_font) }); new PdfPCell(tableGrandTotal); tableGrandTotal.ExtendLastRow = false; tableGrandTotal.WidthPercentage = 95f; tableGrandTotal.SpacingAfter = 5f; document.Add(tableGrandTotal); #endregion #region Mark PdfPTable tableMark = new PdfPTable(2); tableMark.SetWidths(new float[] { 1f, 1f }); PdfPCell cellShippingMark = new PdfPCell() { Border = Rectangle.NO_BORDER }; Chunk chunkShippingMark = new Chunk("SHIPPING MARKS", normal_font); chunkShippingMark.SetUnderline(0.5f, -1); Phrase phraseShippingMark = new Phrase(); phraseShippingMark.Add(chunkShippingMark); phraseShippingMark.Add(new Chunk(" :", normal_font)); cellShippingMark.AddElement(phraseShippingMark); cellShippingMark.AddElement(new Paragraph(viewModel.ShippingMark, normal_font)); tableMark.AddCell(cellShippingMark); PdfPCell cellSideMark = new PdfPCell() { Border = Rectangle.NO_BORDER }; Chunk chunkSideMark = new Chunk("SIDE MARKS", normal_font); chunkSideMark.SetUnderline(0.5f, -1); Phrase phraseSideMark = new Phrase(); phraseSideMark.Add(chunkSideMark); phraseSideMark.Add(new Chunk(" :", normal_font)); cellSideMark.AddElement(phraseSideMark); cellSideMark.AddElement(new Paragraph(viewModel.SideMark, normal_font) { }); tableMark.AddCell(cellSideMark); byte[] shippingMarkImage; var noImage = "data:image/png;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAA0NDQ0ODQ4QEA4UFhMWFB4bGRkbHi0gIiAiIC1EKjIqKjIqRDxJOzc7STxsVUtLVWx9aWNpfZeHh5e+tb75+f8BDQ0NDQ4NDhAQDhQWExYUHhsZGRseLSAiICIgLUQqMioqMipEPEk7NztJPGxVS0tVbH1pY2l9l4eHl761vvn5///CABEIAAoACgMBIgACEQEDEQH/xAAVAAEBAAAAAAAAAAAAAAAAAAAAB//aAAgBAQAAAACnD//EABQBAQAAAAAAAAAAAAAAAAAAAAD/2gAIAQIQAAAAf//EABQBAQAAAAAAAAAAAAAAAAAAAAD/2gAIAQMQAAAAf//EABQQAQAAAAAAAAAAAAAAAAAAACD/2gAIAQEAAT8AH//EABQRAQAAAAAAAAAAAAAAAAAAAAD/2gAIAQIBAT8Af//EABQRAQAAAAAAAAAAAAAAAAAAAAD/2gAIAQMBAT8Af//Z"; if (String.IsNullOrEmpty(viewModel.ShippingMarkImageFile)) { viewModel.ShippingMarkImageFile = noImage; } if (IsBase64String(Base64.GetBase64File(viewModel.ShippingMarkImageFile))) { shippingMarkImage = Convert.FromBase64String(Base64.GetBase64File(viewModel.ShippingMarkImageFile)); Image shipMarkImage = Image.GetInstance(imgb: shippingMarkImage); if (shipMarkImage.Width > 60) { float percentage = 0.0f; percentage = 100 / shipMarkImage.Width; shipMarkImage.ScalePercent(percentage * 100); } PdfPCell shipMarkImageCell = new PdfPCell(shipMarkImage); shipMarkImageCell.Border = Rectangle.NO_BORDER; tableMark.AddCell(shipMarkImageCell); } byte[] sideMarkImage; if (String.IsNullOrEmpty(viewModel.SideMarkImageFile)) { viewModel.SideMarkImageFile = noImage; } if (IsBase64String(Base64.GetBase64File(viewModel.SideMarkImageFile))) { sideMarkImage = Convert.FromBase64String(Base64.GetBase64File(viewModel.SideMarkImageFile)); Image _sideMarkImage = Image.GetInstance(imgb: sideMarkImage); if (_sideMarkImage.Width > 60) { float percentage = 0.0f; percentage = 100 / _sideMarkImage.Width; _sideMarkImage.ScalePercent(percentage * 100); } PdfPCell _sideMarkImageCell = new PdfPCell(_sideMarkImage); _sideMarkImageCell.Border = Rectangle.NO_BORDER; tableMark.AddCell(_sideMarkImageCell); } new PdfPCell(tableMark); tableMark.ExtendLastRow = false; tableMark.SpacingAfter = 5f; document.Add(tableMark); #endregion #region Measurement PdfPTable tableMeasurement = new PdfPTable(3); tableMeasurement.SetWidths(new float[] { 2f, 0.2f, 12f }); PdfPCell cellMeasurement = new PdfPCell() { Border = Rectangle.NO_BORDER }; cellMeasurement.Phrase = new Phrase("GROSS WEIGHT", normal_font); tableMeasurement.AddCell(cellMeasurement); cellMeasurement.Phrase = new Phrase(":", normal_font); tableMeasurement.AddCell(cellMeasurement); cellMeasurement.Phrase = new Phrase(String.Format("{0:0.00}", viewModel.GrossWeight) + " KGS", normal_font); tableMeasurement.AddCell(cellMeasurement); cellMeasurement.Phrase = new Phrase("NET WEIGHT", normal_font); tableMeasurement.AddCell(cellMeasurement); cellMeasurement.Phrase = new Phrase(":", normal_font); tableMeasurement.AddCell(cellMeasurement); cellMeasurement.Phrase = new Phrase(String.Format("{0:0.00}", viewModel.NettWeight) + " KGS", normal_font); tableMeasurement.AddCell(cellMeasurement); cellMeasurement.Phrase = new Phrase("NET NET WEIGHT", normal_font); tableMeasurement.AddCell(cellMeasurement); cellMeasurement.Phrase = new Phrase(":", normal_font); tableMeasurement.AddCell(cellMeasurement); cellMeasurement.Phrase = new Phrase(String.Format("{0:0.00}", viewModel.NetNetWeight) + " KGS", normal_font); tableMeasurement.AddCell(cellMeasurement); cellMeasurement.Phrase = new Phrase("MEASUREMENT", normal_font); tableMeasurement.AddCell(cellMeasurement); cellMeasurement.Phrase = new Phrase(":", normal_font); tableMeasurement.AddCell(cellMeasurement); PdfPTable tableMeasurementDetail = new PdfPTable(5); tableMeasurementDetail.SetWidths(new float[] { 1f, 1f, 1f, 1.5f, 2f }); PdfPCell cellMeasurementDetail = new PdfPCell() { Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_RIGHT }; decimal totalCbm = 0; foreach (var measurement in viewModel.Measurements) { cellMeasurementDetail.Phrase = new Phrase(measurement.Length + " CM X ", normal_font); tableMeasurementDetail.AddCell(cellMeasurementDetail); cellMeasurementDetail.Phrase = new Phrase(measurement.Width + " CM X ", normal_font); tableMeasurementDetail.AddCell(cellMeasurementDetail); cellMeasurementDetail.Phrase = new Phrase(measurement.Height + " CM X ", normal_font); tableMeasurementDetail.AddCell(cellMeasurementDetail); cellMeasurementDetail.Phrase = new Phrase(measurement.CartonsQuantity + " CTNS = ", normal_font); tableMeasurementDetail.AddCell(cellMeasurementDetail); var cbm = (decimal)measurement.Length * (decimal)measurement.Width * (decimal)measurement.Height * (decimal)measurement.CartonsQuantity / 1000000; totalCbm += cbm; cellMeasurementDetail.Phrase = new Phrase(string.Format("{0:N2} CBM", cbm), normal_font); tableMeasurementDetail.AddCell(cellMeasurementDetail); } cellMeasurementDetail.Border = Rectangle.TOP_BORDER; cellMeasurementDetail.Phrase = new Phrase("", normal_font); tableMeasurementDetail.AddCell(cellMeasurementDetail); tableMeasurementDetail.AddCell(cellMeasurementDetail); cellMeasurementDetail.Phrase = new Phrase("TOTAL", normal_font); tableMeasurementDetail.AddCell(cellMeasurementDetail); cellMeasurementDetail.Phrase = new Phrase(viewModel.Measurements.Sum(m => m.CartonsQuantity) + " CTNS .", normal_font); tableMeasurementDetail.AddCell(cellMeasurementDetail); cellMeasurementDetail.Phrase = new Phrase(string.Format("{0:N2} CBM", totalCbm), normal_font); tableMeasurementDetail.AddCell(cellMeasurementDetail); new PdfPCell(tableMeasurementDetail); tableMeasurementDetail.ExtendLastRow = false; var paddingRight = SIZES_COUNT > 11 ? 400 : 200; tableMeasurement.AddCell(new PdfPCell(tableMeasurementDetail) { Border = Rectangle.NO_BORDER, PaddingRight = paddingRight }); tableMeasurement.AddCell(new PdfPCell { Border = Rectangle.NO_BORDER, Colspan = 3, Phrase = new Phrase("REMARK :", normal_font_underlined) }); tableMeasurement.AddCell(new PdfPCell { Border = Rectangle.NO_BORDER, Colspan = 3, Phrase = new Phrase(viewModel.Remark, normal_font) }); byte[] remarkImage; if (String.IsNullOrEmpty(viewModel.RemarkImageFile)) { viewModel.RemarkImageFile = noImage; } if (IsBase64String(Base64.GetBase64File(viewModel.RemarkImageFile))) { remarkImage = Convert.FromBase64String(Base64.GetBase64File(viewModel.RemarkImageFile)); Image images = Image.GetInstance(imgb: remarkImage); if (images.Width > 60) { float percentage = 0.0f; percentage = 100 / images.Width; images.ScalePercent(percentage * 100); } PdfPCell imageCell = new PdfPCell(images); imageCell.Border = Rectangle.NO_BORDER; imageCell.Colspan = 3; tableMeasurement.AddCell(imageCell); } new PdfPCell(tableMeasurement); tableMeasurement.ExtendLastRow = false; tableMeasurement.SpacingAfter = 5f; document.Add(tableMeasurement); #endregion #region sign PdfPTable tableSign = new PdfPTable(3); tableSign.WidthPercentage = 100; tableSign.SetWidths(new float[] { 1f, 1f, 1f }); PdfPCell cellBodySignNoBorder = new PdfPCell() { Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_CENTER }; cellBodySignNoBorder.Phrase = new Phrase("", normal_font); tableSign.AddCell(cellBodySignNoBorder); cellBodySignNoBorder.Phrase = new Phrase("", normal_font); tableSign.AddCell(cellBodySignNoBorder); cellBodySignNoBorder.Phrase = new Phrase("\n\n\n\n", normal_font); tableSign.AddCell(cellBodySignNoBorder); cellBodySignNoBorder.Phrase = new Phrase("", normal_font); tableSign.AddCell(cellBodySignNoBorder); cellBodySignNoBorder.Phrase = new Phrase("", normal_font); tableSign.AddCell(cellBodySignNoBorder); cellBodySignNoBorder.Phrase = new Phrase("( MRS. ADRIYANA DAMAYANTI )", normal_font); tableSign.AddCell(cellBodySignNoBorder); cellBodySignNoBorder.Phrase = new Phrase("", normal_font); tableSign.AddCell(cellBodySignNoBorder); cellBodySignNoBorder.Phrase = new Phrase("", normal_font); tableSign.AddCell(cellBodySignNoBorder); cellBodySignNoBorder.Phrase = new Phrase("AUTHORIZED SIGNATURE", normal_font_underlined); tableSign.AddCell(cellBodySignNoBorder); document.Add(tableSign); #endregion document.Close(); byte[] byteInfo = stream.ToArray(); stream.Write(byteInfo, 0, byteInfo.Length); stream.Position = 0; return(stream); }
public static void ToPdf(DataGridView dataGridView, string headerString = "Client List") { try { var saveFileDialog = new SaveFileDialog { Filter = @"Document PDF (*.pdf)|*.pdf", FileName = $"{headerString} {DateTime.Now:dd-MM-yyyy hh-mmm-ss}" }; if (saveFileDialog.ShowDialog() != DialogResult.OK) { return; } var doc = new Document(PageSize.A4.Rotate(), 15, 15, 20, 20); var file = new FileStream(saveFileDialog.FileName, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite); var writer = PdfWriter.GetInstance(doc, file); doc.Open(); //left-header var leftHeaderParagraph = new Paragraph { Alignment = Element.ALIGN_LEFT }; //logo var logo = iTextSharp.text.Image.GetInstance(Resources.app_logo_black, BaseColor.WHITE); var brandName = new Chunk("Rent Luxury"); leftHeaderParagraph.Add(logo); leftHeaderParagraph.Add(brandName); doc.Add(leftHeaderParagraph); //Report Header var baseFont = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); var headFont = new Font(baseFont, 16, 1, BaseColor.GRAY); var prgHeading = new Paragraph { Alignment = Element.ALIGN_CENTER }; prgHeading.Add(new Chunk(headerString.ToUpper(), headFont)); doc.Add(prgHeading); //Author var authorParagraph = new Paragraph(); var authorBaseFont = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); var authorFont = new Font(authorBaseFont, 10, 2, BaseColor.GRAY); authorParagraph.Alignment = Element.ALIGN_RIGHT; authorParagraph.Add(new Chunk($"Author : {Program.CurrentUser.FullName}", authorFont)); authorParagraph.Add(new Chunk("\nDate : " + DateTime.Now.ToShortDateString(), authorFont)); doc.Add(authorParagraph); //Add a line separation var p = new Paragraph(new Chunk(new LineSeparator(0.0F, 100.0F, BaseColor.GRAY, Element.ALIGN_LEFT, 1))); doc.Add(p); //Add line break doc.Add(new Chunk("\n", headFont)); //Write the table var table = new PdfPTable(dataGridView.ColumnCount); //Table header var tableBaseFont = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); var headerFont = new Font(tableBaseFont, 12, 1, BaseColor.WHITE); for (var i = 0; i < dataGridView.Columns.Count; i++) { var cell = new PdfPCell { BackgroundColor = BaseColor.GRAY, HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_CENTER, Padding = 8 }; cell.AddElement(new Chunk(dataGridView.Columns[i].HeaderText, headerFont)); table.AddCell(cell); } //table Data for (var i = 0; i < dataGridView.Rows.Count; i++) { for (var j = 0; j < dataGridView.Columns.Count; j++) { var contentFont = new Font(tableBaseFont, 10, 0, BaseColor.BLACK); var cell = new PdfPCell { BorderColor = BaseColor.GRAY, PaddingLeft = 4, PaddingTop = 8, PaddingBottom = 8, BackgroundColor = i % 2 == 0 ? new BaseColor(Color.FromArgb(216, 218, 216)) : BaseColor.WHITE, VerticalAlignment = Element.ALIGN_LEFT, HorizontalAlignment = Element.ALIGN_CENTER }; cell.AddElement(new Chunk(dataGridView[j, i].FormattedValue?.ToString(), contentFont)); table.AddCell(cell); } } doc.Add(table); doc.Close(); writer.Close(); doc.Close(); Process.Start(saveFileDialog.FileName); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
protected void ReportExportPDF(List <ReportSaleMonthDTO> lst) { MemoryStream ms = new MemoryStream(); Document doc = new Document(PageSize.A4.Rotate(), 3, 3, 7, 3); //var output = new FileStream(Server.MapPath(filename), FileMode.Create); var writer = PdfWriter.GetInstance(doc, ms); doc.Open(); try { #region Variable BaseColor bc = new BaseColor(255, 255, 255); float[] widths; string fontFamily = "C:/Windows/Fonts/Tahoma.ttf"; BaseFont bf = BaseFont.CreateFont(fontFamily, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); Font fontTitle = new Font(bf, 12, iTextSharp.text.Font.BOLD); Font fontHeader = new Font(bf, 10); Font fontGrid = new Font(bf, 9); PdfPTable table = new PdfPTable(1); PdfPTable tableGrid = new PdfPTable(8); PdfPCell[] cellAry; PdfPRow row; PdfPCell cell1 = new PdfPCell(); PdfPCell cell2 = new PdfPCell(); PdfPCell cell3 = new PdfPCell(); PdfPCell cell4 = new PdfPCell(); PdfPCell cell5 = new PdfPCell(); PdfPCell cell6 = new PdfPCell(); PdfPCell cell7 = new PdfPCell(); PdfPCell cell8 = new PdfPCell(); table.WidthPercentage = 95; tableGrid.WidthPercentage = 95; #endregion cell1 = GetNewCell(false); cell1.AddElement(GetNewParag("รายงานการขาย", fontTitle)); cellAry = new PdfPCell[] { cell1 }; row = new PdfPRow(cellAry); table.Rows.Add(row); cell1 = GetNewCell(false); cell1.AddElement(GetNewParag(" ", fontHeader)); cellAry = new PdfPCell[] { cell1 }; row = new PdfPRow(cellAry); table.Rows.Add(row); doc.Add(table); cell1 = GetNewCell(true); cell2 = GetNewCell(true); cell3 = GetNewCell(true); cell4 = GetNewCell(true); cell5 = GetNewCell(true); cell6 = GetNewCell(true); cell7 = GetNewCell(true); cell8 = GetNewCell(true); cell1.AddElement(GetNewParag("ชื่อลูกค้า", fontHeader, 1)); cell2.AddElement(GetNewParag("วันที่", fontHeader, 1)); cell3.AddElement(GetNewParag("เลขที่", fontHeader, 1)); cell4.AddElement(GetNewParag("สินค้า", fontHeader, 1)); cell5.AddElement(GetNewParag("จำนวน", fontHeader, 1)); cell6.AddElement(GetNewParag("รวม", fontHeader, 1)); cell7.AddElement(GetNewParag("ราคา", fontHeader, 1)); cell8.AddElement(GetNewParag("ภาษีมูลค่าเพิ่ม", fontHeader, 1)); cellAry = new PdfPCell[] { cell1, cell2, cell3, cell4, cell5, cell6, cell7, cell8 }; row = new PdfPRow(cellAry); widths = new float[] { 50f, 20f, 20f, 65f, 15f, 25f, 25f, 30f }; tableGrid.SetWidths(widths); tableGrid.Rows.Add(row); foreach (ReportSaleMonthDTO item in lst) { cell1 = GetNewCell(true); cell2 = GetNewCell(true); cell3 = GetNewCell(true); cell4 = GetNewCell(true); cell5 = GetNewCell(true); cell6 = GetNewCell(true); cell7 = GetNewCell(true); cell8 = GetNewCell(true); cell1.AddElement(GetNewParag(item.CustomerName, fontGrid)); cell2.AddElement(GetNewParag(item.ReceivedDateStr, fontGrid, 1)); cell3.AddElement(GetNewParag(item.SaleNumber, fontGrid, 1)); cell4.AddElement(GetNewParag(item.ItemName, fontGrid)); cell5.AddElement(GetNewParag(item.AmountStr, fontGrid, 1)); cell6.AddElement(GetNewParag(item.TotalStr, fontGrid, 2)); cell7.AddElement(GetNewParag(item.TotalExVatStr, fontGrid, 2)); cell8.AddElement(GetNewParag(item.VATAmountStr, fontGrid, 2)); cellAry = new PdfPCell[] { cell1, cell2, cell3, cell4, cell5, cell6, cell7, cell8 }; row = new PdfPRow(cellAry); tableGrid.Rows.Add(row); } doc.Add(tableGrid); } catch (Exception ex) { } finally { doc.Close(); writer.Close(); } string filename = "ReportSale_" + DateTime.Now.ToString("yyyyMMdd"); Response.Clear(); Response.Buffer = false; Response.ContentEncoding = Encoding.UTF8; Response.HeaderEncoding = Encoding.UTF8; Response.AddHeader("content-disposition", "attachment;filename=" + filename + ".pdf"); Response.ContentType = "application/pdf"; Response.BinaryWrite(ms.ToArray()); Response.Flush(); Response.SuppressContent = true; }
void ExportDataTableToPdf(DataTable dtblTable, String strPdfPath, string strHeader) { System.IO.FileStream fs = new FileStream(strPdfPath, FileMode.Create, FileAccess.Write, FileShare.None); Document document = new Document(); document.SetPageSize(iTextSharp.text.PageSize.A4); PdfWriter writer = PdfWriter.GetInstance(document, fs); document.Open(); //Report Header BaseFont bfntHead = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); Font fntHead = new Font(bfntHead, 16, 1, Color.GRAY); Paragraph prgHeading = new Paragraph(); prgHeading.Alignment = Element.ALIGN_CENTER; prgHeading.Add(new Chunk(strHeader.ToUpper(), fntHead)); document.Add(prgHeading); //Author Paragraph prgAuthor = new Paragraph(); BaseFont btnAuthor = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); Font fntAuthor = new Font(btnAuthor, 8, 2, Color.GRAY); prgAuthor.Alignment = Element.ALIGN_RIGHT; prgAuthor.Add(new Chunk("Author : Dotnet Mob", fntAuthor)); prgAuthor.Add(new Chunk("\nRun Date : " + DateTime.Now.ToShortDateString(), fntAuthor)); document.Add(prgAuthor); //Add a line seperation Paragraph p = new Paragraph(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(0.0F, 100.0F, Color.BLACK, Element.ALIGN_LEFT, 1))); document.Add(p); //Add line break document.Add(new Chunk("\n", fntHead)); //Write the table PdfPTable table = new PdfPTable(dataGridView1.Columns.Count); //Table header BaseFont btnColumnHeader = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); Font fntColumnHeader = new Font(btnColumnHeader, 10, 1, Color.WHITE); for (int i = 0; i < dtblTable.Columns.Count; i++) { PdfPCell cell = new PdfPCell(); cell.BackgroundColor = Color.GRAY; cell.AddElement(new Chunk(dtblTable.Columns[i].ColumnName.ToUpper(), fntColumnHeader)); table.AddCell(cell); } //table Data for (int i = 0; i < dtblTable.Rows.Count; i++) { for (int j = 0; j < dtblTable.Columns.Count; j++) { table.AddCell(dtblTable.Rows[i][j].ToString()); } } document.Add(table); document.Close(); writer.Close(); fs.Close(); }
public override void OnEndPage(iTextSharp.text.pdf.PdfWriter writer, iTextSharp.text.Document document) { base.OnEndPage(writer, document); iTextSharp.text.Font baseFontNormal = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12f, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK); iTextSharp.text.Font baseFontBig = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12f, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLACK); Phrase p1Header = new Phrase(null, null); //removing Header HTML COntent if (HeaderText != null) { FontFactory.RegisterDirectories(); List <IElement> htmlarraylist = HTMLWorker.ParseToList(new StringReader(HeaderText), null); for (int k = 0; k < htmlarraylist.Count; k++) { p1Header.Add((IElement)htmlarraylist[k]); } } Phrase p1Footer = new Phrase(null, null); //removing Footer HTML COntent if (FooterText != null) { FontFactory.RegisterDirectories(); List <IElement> htmlarrayFooterlist = HTMLWorker.ParseToList(new StringReader(FooterText), null); for (int m = 0; m < htmlarrayFooterlist.Count; m++) { p1Footer.Add((IElement)htmlarrayFooterlist[m]); } } //Create PdfTable object PdfPTable pdfTab = new PdfPTable(3); pdfTab.WidthPercentage = 90; float[] tblDescWidth52 = new float[3]; tblDescWidth52[0] = 25; tblDescWidth52[1] = 72; tblDescWidth52[2] = 2; pdfTab.SetWidths(tblDescWidth52); String text = "Page " + writer.PageNumber + " of "; //We will have to create separate cells to include image logo and 2 separate strings //Row 1 if (HeaderRequired) { PdfPCell pdfCell1 = new PdfPCell(); PdfPCell pdfCell2 = new PdfPCell(p1Header); PdfPCell pdfCell3 = new PdfPCell(); // iTextSharp.text.Image imgLogo = iTextSharp.text.Image.GetInstance(HttpContext.Current.Server.MapPath("~/Images/customer Images/ReportLogo/" + LogoPath)); // iTextSharp.text.Image imgLogo = iTextSharp.text.Image.GetInstance("F:/MAIN V10/Sharda_Hospital/Sharda_12_08_2016/WinApps/ReportLogo/Win7645logo3.PNG"); // imgLogo.ScaleToFit(80, 60); // pdfCell1.AddElement(imgLogo); string base64Image = LogoPath; // new 18-08 Regex regex = new Regex(@"^data:image/(?<mediaType>[^;]+);base64,(?<data>.*)"); // new 18-08 Match match = regex.Match(base64Image); // new 18-08 Image image = Image.GetInstance( // new 18-08 Convert.FromBase64String(match.Groups["data"].Value) // new 18-08 ); image.ScaleToFit(80, 60); // new 18-08 pdfCell1.AddElement(image); // new 18-08 //Row 2 PdfPCell pdfCell4 = new PdfPCell(new Phrase(null, baseFontNormal)); //Row 3 //set the alignment of all three cells and set border to 0 pdfCell1.HorizontalAlignment = Element.ALIGN_CENTER; pdfCell2.HorizontalAlignment = Element.ALIGN_LEFT; pdfCell3.HorizontalAlignment = Element.ALIGN_CENTER; pdfCell4.HorizontalAlignment = Element.ALIGN_CENTER; pdfCell2.VerticalAlignment = Element.ALIGN_CENTER; pdfCell3.VerticalAlignment = Element.ALIGN_MIDDLE; pdfCell4.VerticalAlignment = Element.ALIGN_TOP; pdfCell4.Colspan = 3; pdfCell1.Border = 0; pdfCell2.Border = 0; pdfCell3.Border = 0; pdfCell4.Border = 0; //add all three cells into PdfTable pdfTab.AddCell(pdfCell1); pdfTab.AddCell(pdfCell2); pdfTab.AddCell(pdfCell3); pdfTab.AddCell(pdfCell4); pdfTab.TotalWidth = document.PageSize.Width - 80f; pdfTab.WidthPercentage = 70; //call WriteSelectedRows of PdfTable. This writes rows from PdfWriter in PdfTable //first param is start row. -1 indicates there is no end row and all the rows to be included to write //Third and fourth param is x and y position to start writing pdfTab.WriteSelectedRows(0, -1, 40, document.PageSize.Height - 30, writer.DirectContent); //Move the pointer and draw line to separate header section from rest of page if (BorderRequired) { cb.MoveTo(40, document.PageSize.Height - 100); cb.LineTo(document.PageSize.Width - 40, document.PageSize.Height - 100); cb.Stroke(); } } //footer code if (FooterRequired) { //Move the pointer and draw line to separate footer section from rest of page if (BorderRequired) { cb.MoveTo(40, document.PageSize.GetBottom(50)); cb.LineTo(document.PageSize.Width - 40, document.PageSize.GetBottom(50)); cb.Stroke(); } //Add Footer text to footer PdfPTable pdfTaba = new PdfPTable(1); PdfPCell pdfCellfooter = new PdfPCell(p1Footer); pdfCellfooter.HorizontalAlignment = Element.ALIGN_LEFT; pdfCellfooter.Border = 0; pdfCellfooter.VerticalAlignment = Element.ALIGN_BOTTOM; if (PaperSize == "") { pdfTaba.TotalWidth = document.PageSize.Width - 80f; } else { pdfTaba.TotalWidth = document.PageSize.Width; } pdfTaba.WidthPercentage = 100; pdfTaba.AddCell(pdfCellfooter); //call WriteSelectedRows of PdfTable. This writes rows from PdfWriter in PdfTable //first param is start row. -1 indicates there is no end row and all the rows to be included to write //Third and fourth param is x and y position to start writing // pdfTaba.WriteSelectedRows(0, -1, document.PageSize.GetRight(550), document.PageSize.GetBottom(50), writer.DirectContent); if (PaperSize == "A4 Size") { pdfTaba.WriteSelectedRows(0, -1, 40, document.PageSize.Height - 750, writer.DirectContent); } else { pdfTaba.WriteSelectedRows(0, -1, 40, document.PageSize.Height - 500, writer.DirectContent); } } if (PageRequired) { //Add paging to footer cb.BeginText(); cb.SetFontAndSize(bf, 8); cb.SetTextMatrix(document.PageSize.GetRight(120), document.PageSize.GetBottom(35)); cb.ShowText(text); cb.EndText(); float len = bf.GetWidthPoint(text, 12); cb.AddTemplate(footerTemplate, document.PageSize.GetRight(120) + len, document.PageSize.GetBottom(35)); } if (BorderRequired) { //Add Paging to Border var content = writer.DirectContent; var pageBorderRect = new Rectangle(document.PageSize); pageBorderRect.Left += 40f; pageBorderRect.Right -= 40f; pageBorderRect.Top -= 30f; pageBorderRect.Bottom += 30f; content.SetColorStroke(BaseColor.BLACK); content.Rectangle(pageBorderRect.Left, pageBorderRect.Bottom, pageBorderRect.Width, pageBorderRect.Height); content.Stroke(); } }
public MemoryStream GeneratePdfTemplate(VBRealizationDocumentNonPOViewModel viewModel, int timeoffsset) { const int MARGIN = 20; const int MARGIN_VERTICAL = 10; Font header_font = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 18); Font normal_font = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 11); Font normal_font_8 = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 9); Font bold_font = FontFactory.GetFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 11); Font bold_font_8 = FontFactory.GetFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 8); Font note_font = FontFactory.GetFont(BaseFont.HELVETICA_OBLIQUE, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 8); Font bold_italic_font = FontFactory.GetFont(BaseFont.HELVETICA_BOLDOBLIQUE, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 12); Font Title_bold_font = FontFactory.GetFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 13); Document document = new Document(PageSize.A4, MARGIN_VERTICAL, MARGIN_VERTICAL, MARGIN, MARGIN); MemoryStream stream = new MemoryStream(); PdfWriter writer = PdfWriter.GetInstance(document, stream); document.Open(); #region Header PdfPTable headerTable_A = new PdfPTable(2); PdfPTable headerTable_B = new PdfPTable(1); PdfPTable headerTable_C = new PdfPTable(1); PdfPTable headerTable1 = new PdfPTable(1); PdfPTable headerTable2 = new PdfPTable(1); PdfPTable headerTable3 = new PdfPTable(7); PdfPTable headerTable3a = new PdfPTable(5); PdfPTable headerTable3b = new PdfPTable(5); PdfPTable headerTable4 = new PdfPTable(2); headerTable_A.SetWidths(new float[] { 10f, 10f }); headerTable_A.WidthPercentage = 100; headerTable3.SetWidths(new float[] { 5f, 15f, 15f, 15f, 20f, 15f, 20f }); headerTable3.WidthPercentage = 110; headerTable3a.SetWidths(new float[] { 3f, 15f, 5f, 15f, 62f }); headerTable3a.WidthPercentage = 110; headerTable3b.SetWidths(new float[] { 3f, 15f, 5f, 15f, 62f }); headerTable3b.WidthPercentage = 110; headerTable4.SetWidths(new float[] { 10f, 40f }); headerTable4.WidthPercentage = 100; PdfPCell cellHeader1 = new PdfPCell() { Border = Rectangle.NO_BORDER }; PdfPCell cellHeader2 = new PdfPCell() { Border = Rectangle.NO_BORDER }; PdfPCell cellHeader3 = new PdfPCell() { Border = Rectangle.NO_BORDER }; PdfPCell cellHeader4 = new PdfPCell() { Border = Rectangle.NO_BORDER }; PdfPCell cellHeader3a = new PdfPCell() { Border = Rectangle.NO_BORDER }; PdfPCell cellHeaderBody = new PdfPCell() { Border = Rectangle.NO_BORDER }; PdfPCell cellHeaderBody1 = new PdfPCell() { }; PdfPCell cellHeaderBody1a = new PdfPCell() { BorderWidthTop = 2 }; PdfPCell cellHeaderBody1a1 = new PdfPCell() { }; PdfPCell cellHeaderBody1a2 = new PdfPCell() { }; PdfPCell cellHeaderBody1b = new PdfPCell() { BorderWidthTop = 2 }; PdfPCell cellHeaderBody1b1 = new PdfPCell() { }; PdfPCell cellHeaderBody1b2 = new PdfPCell() { }; PdfPCell cellHeaderBody1c = new PdfPCell() { }; PdfPCell cellHeaderBody2 = new PdfPCell() { Border = Rectangle.NO_BORDER }; PdfPCell cellHeaderBody3 = new PdfPCell() { Border = Rectangle.NO_BORDER }; PdfPCell cellHeaderBody4 = new PdfPCell() { Border = Rectangle.NO_BORDER }; PdfPCell cellHeaderBody4a = new PdfPCell() { Border = Rectangle.NO_BORDER }; PdfPCell cellHeaderBody4b = new PdfPCell() { Border = Rectangle.NO_BORDER }; PdfPCell cellHeaderBody5 = new PdfPCell() { Border = Rectangle.NO_BORDER }; PdfPCell cellHeaderBody5a = new PdfPCell() { Border = Rectangle.NO_BORDER }; PdfPCell cellHeaderBody6 = new PdfPCell() { }; cellHeader1.AddElement(headerTable1); headerTable_A.AddCell(cellHeader1); cellHeader2.AddElement(headerTable2); headerTable_A.AddCell(cellHeader2); document.Add(headerTable_A); cellHeaderBody.HorizontalAlignment = Element.ALIGN_LEFT; cellHeaderBody1.HorizontalAlignment = Element.ALIGN_CENTER; cellHeaderBody1a.HorizontalAlignment = Element.ALIGN_RIGHT; cellHeaderBody1a1.HorizontalAlignment = Element.ALIGN_RIGHT; cellHeaderBody1a2.HorizontalAlignment = Element.ALIGN_RIGHT; cellHeaderBody1b.HorizontalAlignment = Element.ALIGN_CENTER; cellHeaderBody1b1.HorizontalAlignment = Element.ALIGN_CENTER; cellHeaderBody1b2.HorizontalAlignment = Element.ALIGN_CENTER; cellHeaderBody1c.HorizontalAlignment = Element.ALIGN_CENTER; cellHeaderBody2.HorizontalAlignment = Element.ALIGN_CENTER; cellHeaderBody3.HorizontalAlignment = Element.ALIGN_RIGHT; cellHeaderBody4.HorizontalAlignment = Element.ALIGN_CENTER; cellHeaderBody4a.HorizontalAlignment = Element.ALIGN_CENTER; cellHeaderBody4b.HorizontalAlignment = Element.ALIGN_LEFT; cellHeaderBody5.HorizontalAlignment = Element.ALIGN_RIGHT; cellHeaderBody5a.HorizontalAlignment = Element.ALIGN_CENTER; cellHeaderBody6.HorizontalAlignment = Element.ALIGN_LEFT; // Document title cellHeaderBody2.Colspan = 7; cellHeaderBody2.Phrase = new Phrase("REALISASI VB INKLARING TANPA PO", bold_font); headerTable3.AddCell(cellHeaderBody2); // Document number cellHeaderBody3.Colspan = 7; cellHeaderBody3.Phrase = new Phrase($"{viewModel.DocumentNo}", bold_font); headerTable3.AddCell(cellHeaderBody3); // Realisasi VB Bagian cellHeaderBody3.Colspan = 7; cellHeaderBody3.HorizontalAlignment = Element.ALIGN_LEFT; // Override default to right cellHeaderBody3.Phrase = new Phrase($"Realisasi VB Bagian: {viewModel.Unit.Name}", bold_font); headerTable3.AddCell(cellHeaderBody3); // Tanggal cellHeaderBody3.Colspan = 7; cellHeaderBody3.HorizontalAlignment = Element.ALIGN_LEFT; // Override default to right cellHeaderBody3.Phrase = new Phrase($"Tanggal: {viewModel.Date?.AddHours(timeoffsset).ToString("dd MMMM yyyy", new CultureInfo("id-ID"))}", bold_font); headerTable3.AddCell(cellHeaderBody3); // New line cellHeaderBody3.Phrase = new Phrase(" ", normal_font); headerTable3.AddCell(cellHeaderBody3); // Table header cellHeaderBody1.Phrase = new Phrase("No", normal_font); headerTable3.AddCell(cellHeaderBody1); cellHeaderBody1.Phrase = new Phrase("Tanggal", normal_font); headerTable3.AddCell(cellHeaderBody1); cellHeaderBody1.Colspan = 2; cellHeaderBody1.Phrase = new Phrase("Keterangan", normal_font); headerTable3.AddCell(cellHeaderBody1); cellHeaderBody1.Colspan = 1; cellHeaderBody1.Phrase = new Phrase("No. BL / AWB", normal_font); headerTable3.AddCell(cellHeaderBody1); cellHeaderBody1.Phrase = new Phrase("Mata Uang", normal_font); headerTable3.AddCell(cellHeaderBody1); cellHeaderBody1.Phrase = new Phrase("Jumlah", normal_font); headerTable3.AddCell(cellHeaderBody1); int index = 1; /*decimal count_price = 0;*/ /*decimal total_all = 0;*/ decimal total_realization = 0; decimal ppn_manually = 0; decimal pph_supplier = 0; decimal pph_danliris = 0; var currencyCode = viewModel.Currency.Code; var currencydescription = viewModel.Currency.Description; foreach (var itm in viewModel.Items) { // No cellHeaderBody1.Phrase = new Phrase(index.ToString(), normal_font); cellHeaderBody1.HorizontalAlignment = Element.ALIGN_CENTER; headerTable3.AddCell(cellHeaderBody1); index++; // Tanggal cellHeaderBody1.Phrase = new Phrase(itm.DateDetail?.AddHours(timeoffsset).ToString("dd/MM/yyyy"), normal_font); headerTable3.AddCell(cellHeaderBody1); // Keterangan cellHeaderBody1.Colspan = 2; cellHeaderBody1.Phrase = new Phrase(itm.Remark, normal_font); cellHeaderBody1.HorizontalAlignment = Element.ALIGN_LEFT; headerTable3.AddCell(cellHeaderBody1); // No. BL / AWB cellHeaderBody1.Colspan = 1; cellHeaderBody1.Phrase = new Phrase(itm.BLAWBNumber, normal_font); cellHeaderBody1.HorizontalAlignment = Element.ALIGN_LEFT; headerTable3.AddCell(cellHeaderBody1); if (itm.IsGetPPn) { /*var temp = itm.Amount * 0.1m; * total_all = itm.Amount + temp;*/ ppn_manually += itm.PPnAmount; } /*else * { * total_all = itm.Amount; * }*/ if (itm.IsGetPPh) { if (itm.IncomeTaxBy == "Supplier") { pph_supplier += itm.PPhAmount; } else { pph_danliris += itm.PPhAmount; } } // Mata Uang cellHeaderBody1.Colspan = 1; cellHeaderBody1.Phrase = new Phrase(currencyCode, normal_font); cellHeaderBody1.HorizontalAlignment = Element.ALIGN_CENTER; headerTable3.AddCell(cellHeaderBody1); // Jumlah cellHeaderBody1.Phrase = new Phrase(itm.Amount.ToString("#,##0.00", new CultureInfo("id-ID")), normal_font); cellHeaderBody1.HorizontalAlignment = Element.ALIGN_RIGHT; // Override default to center headerTable3.AddCell(cellHeaderBody1); /*count_price += total_all;*/ total_realization += itm.Amount; } // Jumlah Realisasi cellHeaderBody1a.Colspan = 5; cellHeaderBody1a.HorizontalAlignment = Element.ALIGN_LEFT; cellHeaderBody1a.Phrase = new Phrase("Jumlah Realisasi", normal_font); headerTable3.AddCell(cellHeaderBody1a); // Mata Uang cellHeaderBody1b.Phrase = new Phrase(currencyCode, normal_font); headerTable3.AddCell(cellHeaderBody1b); // Jumlah cellHeaderBody1a.Phrase = new Phrase(total_realization.ToString("#,##0.00", new CultureInfo("id-ID")), normal_font); cellHeaderBody1a.HorizontalAlignment = Element.ALIGN_RIGHT; headerTable3.AddCell(cellHeaderBody1a); // PPn cellHeaderBody1a1.Colspan = 5; cellHeaderBody1a1.HorizontalAlignment = Element.ALIGN_LEFT; cellHeaderBody1a1.Phrase = new Phrase("PPN", normal_font); headerTable3.AddCell(cellHeaderBody1a1); // Mata Uang cellHeaderBody1b1.Phrase = new Phrase(currencyCode, normal_font); headerTable3.AddCell(cellHeaderBody1b1); // Jumlah cellHeaderBody1a1.Phrase = new Phrase(ppn_manually.ToString("#,##0.00", new CultureInfo("id-ID")), normal_font); cellHeaderBody1a1.HorizontalAlignment = Element.ALIGN_RIGHT; headerTable3.AddCell(cellHeaderBody1a1); // PPh ditanggung Dan Liris cellHeaderBody1a1.Colspan = 5; cellHeaderBody1a1.HorizontalAlignment = Element.ALIGN_LEFT; cellHeaderBody1a1.Phrase = new Phrase("PPh ditanggung Dan Liris", normal_font); headerTable3.AddCell(cellHeaderBody1a1); // Mata Uang cellHeaderBody1b1.Phrase = new Phrase(currencyCode, normal_font); headerTable3.AddCell(cellHeaderBody1b1); // Jumlah cellHeaderBody1a1.Phrase = new Phrase(pph_danliris.ToString("#,##0.00", new CultureInfo("id-ID")), normal_font); cellHeaderBody1a1.HorizontalAlignment = Element.ALIGN_RIGHT; headerTable3.AddCell(cellHeaderBody1a1); // PPh ditanggung Supplier cellHeaderBody1a1.Colspan = 5; cellHeaderBody1a1.HorizontalAlignment = Element.ALIGN_LEFT; cellHeaderBody1a1.Phrase = new Phrase("PPh ditanggung Supplier", normal_font); headerTable3.AddCell(cellHeaderBody1a1); // Mata Uang cellHeaderBody1b1.Phrase = new Phrase(currencyCode, normal_font); headerTable3.AddCell(cellHeaderBody1b1); // Jumlah cellHeaderBody1a1.Phrase = new Phrase(pph_supplier.ToString("#,##0.00", new CultureInfo("id-ID")), normal_font); cellHeaderBody1a1.HorizontalAlignment = Element.ALIGN_RIGHT; headerTable3.AddCell(cellHeaderBody1a1); // Total Keseluruhan cellHeaderBody1a2.Colspan = 5; cellHeaderBody1a2.HorizontalAlignment = Element.ALIGN_LEFT; cellHeaderBody1a2.Phrase = new Phrase("Total", normal_font); headerTable3.AddCell(cellHeaderBody1a2); // Mata Uang cellHeaderBody1b2.Phrase = new Phrase(currencyCode, normal_font); headerTable3.AddCell(cellHeaderBody1b2); // Jumlah var grandTotal = total_realization + ppn_manually - pph_supplier; cellHeaderBody1a2.Phrase = new Phrase(grandTotal.ToString("#,##0.00", new CultureInfo("id-ID")), normal_font); cellHeaderBody1a2.HorizontalAlignment = Element.ALIGN_RIGHT; headerTable3.AddCell(cellHeaderBody1a2); var vbDate = viewModel.VBDocument?.Date?.AddHours(timeoffsset).ToString("dd-MMMM-yy", new CultureInfo("id-ID")); if (viewModel.VBNonPOType == "Tanpa Nomor VB") { if (viewModel.VBDocument != null && !string.IsNullOrWhiteSpace(viewModel.VBDocument?.DocumentNo)) { vbDate = viewModel.VBDocument?.Date?.AddHours(timeoffsset).ToString("dd-MMMM-yy", new CultureInfo("id-ID")); } else { vbDate = ""; } } // Tanggal VB cellHeaderBody6.Colspan = 3; cellHeaderBody6.Phrase = new Phrase($"Tanggal VB: {vbDate}", normal_font); headerTable3.AddCell(cellHeaderBody6); // No VB cellHeaderBody1.Colspan = 2; cellHeaderBody1.Phrase = new Phrase($"No.VB: {viewModel.VBDocument?.DocumentNo}", normal_font); cellHeaderBody1.HorizontalAlignment = Element.ALIGN_LEFT; headerTable3.AddCell(cellHeaderBody1); if (viewModel.VBDocument == null) { // Mata Uang cellHeaderBody1.Colspan = 1; cellHeaderBody1.Phrase = new Phrase(currencyCode, normal_font); cellHeaderBody1.HorizontalAlignment = Element.ALIGN_CENTER; headerTable3.AddCell(cellHeaderBody1); // Jumlah cellHeaderBody1.Phrase = new Phrase(0.ToString("#,##0.00", new CultureInfo("id-ID")), normal_font); cellHeaderBody1.HorizontalAlignment = Element.ALIGN_RIGHT; // Override default to center headerTable3.AddCell(cellHeaderBody1); } else { // Mata Uang cellHeaderBody1.Colspan = 1; cellHeaderBody1.Phrase = new Phrase(currencyCode, normal_font); cellHeaderBody1.HorizontalAlignment = Element.ALIGN_CENTER; headerTable3.AddCell(cellHeaderBody1); // Jumlah cellHeaderBody1.Phrase = new Phrase($"{viewModel.VBDocument?.Amount.GetValueOrDefault().ToString("#,##0.00", new CultureInfo("id-ID"))}", normal_font); cellHeaderBody1.HorizontalAlignment = Element.ALIGN_RIGHT; // Override default to center headerTable3.AddCell(cellHeaderBody1); } var priceterbilang = grandTotal; var res = grandTotal - (viewModel.VBDocument == null ? 0 : viewModel.VBDocument.Amount.GetValueOrDefault()); if (res > 0) { // Kurang cellHeaderBody5.Colspan = 5; cellHeaderBody5.Phrase = new Phrase("Kurang", bold_font); headerTable3.AddCell(cellHeaderBody5); // Mata Uang cellHeaderBody5a.Phrase = new Phrase(currencyCode, normal_font); headerTable3.AddCell(cellHeaderBody5a); // Jumlah cellHeaderBody5a.Phrase = new Phrase("(" + res.ToString("#,##0.00", new CultureInfo("id-ID")) + ")", normal_font); cellHeaderBody5a.HorizontalAlignment = Element.ALIGN_RIGHT; // Override default to center headerTable3.AddCell(cellHeaderBody5a); } else { // Sisa cellHeaderBody5.Colspan = 5; cellHeaderBody5.Phrase = new Phrase("Sisa", bold_font); headerTable3.AddCell(cellHeaderBody5); // Mata Uang cellHeaderBody5a.Phrase = new Phrase(currencyCode, normal_font); headerTable3.AddCell(cellHeaderBody5a); // Jumlah cellHeaderBody5a.Phrase = new Phrase($"{(res * -1).ToString("#,##0.00", new CultureInfo("id-ID"))}", normal_font); cellHeaderBody5a.HorizontalAlignment = Element.ALIGN_RIGHT; // Override default to center headerTable3.AddCell(cellHeaderBody5a); } string total = grandTotal.ToString("#,##0.00", new CultureInfo("id-ID")); // New Line cellHeaderBody4a.Colspan = 7; cellHeaderBody4a.Phrase = new Phrase(" ", normal_font); headerTable3.AddCell(cellHeaderBody4a); // Terbilang cellHeaderBody4a.Colspan = 7; cellHeaderBody4a.HorizontalAlignment = Element.ALIGN_LEFT; cellHeaderBody4a.Phrase = new Phrase("Terbilang: " + Nom(grandTotal, currencyCode, currencydescription), normal_font); headerTable3.AddCell(cellHeaderBody4a); // New Line cellHeaderBody4a.Colspan = 7; cellHeaderBody4a.Phrase = new Phrase(" ", normal_font); headerTable3.AddCell(cellHeaderBody4a); // Beban Unit cellHeaderBody4.Colspan = 7; cellHeaderBody4.HorizontalAlignment = Element.ALIGN_LEFT; cellHeaderBody4.Phrase = new Phrase("Beban Unit:", bold_font); headerTable3.AddCell(cellHeaderBody4); cellHeader3.AddElement(headerTable3); headerTable_B.AddCell(cellHeader3); cellHeader4.AddElement(headerTable4); headerTable_B.AddCell(cellHeader4); document.Add(headerTable_B); #endregion Header #region NewCheckbox var layoutOrderOther = viewModel.UnitCosts.ToList().FirstOrDefault(s => s.Unit.VBDocumentLayoutOrder == 10); var unitCost12 = viewModel.UnitCosts.ToList().FirstOrDefault(s => s.Unit.VBDocumentLayoutOrder == 12); if (unitCost12 != null) { unitCost12.Unit.VBDocumentLayoutOrder = 10; } if (layoutOrderOther != null) { layoutOrderOther.Unit.VBDocumentLayoutOrder = 12; } var items = viewModel.UnitCosts.Where(element => element.IsSelected).OrderBy(s => s.Unit.VBDocumentLayoutOrder).ToList(); List <PdfFormField> annotations = new List <PdfFormField>(); foreach (var item in items) { PdfPCell cellform = new PdfPCell() { Border = Rectangle.NO_BORDER }; cellform.FixedHeight = 5f; // Initiate form checkbox PdfFormField _checkGroup = PdfFormField.CreateEmpty(writer); RadioCheckField _radioG; PdfFormField _radioField1; Rectangle kotak = new Rectangle(100, 100); _radioG = new RadioCheckField(writer, kotak, "abc", "Yes"); _radioG.CheckType = RadioCheckField.TYPE_CHECK; _radioG.BorderStyle = PdfBorderDictionary.STYLE_SOLID; _radioG.BorderColor = BaseColor.Black; _radioG.BorderWidth = BaseField.BORDER_WIDTH_MEDIUM; _radioG.Checked = item.IsSelected; bool flag = item.IsSelected; _radioG.Rotation = 0; _radioG.Options = TextField.READ_ONLY; _radioField1 = _radioG.CheckField; cellform.CellEvent = new BebanUnitEvent(_checkGroup, _radioField1, 1); headerTable3a.AddCell(cellform); // Beban Unit Item if (string.IsNullOrEmpty(item.Unit.Name)) { cellHeaderBody.Phrase = new Phrase("......", normal_font_8); } else { cellHeaderBody.Phrase = new Phrase(item.Unit.Name, normal_font_8); } cellHeaderBody.HorizontalAlignment = Element.ALIGN_LEFT; headerTable3a.AddCell(cellHeaderBody); cellHeaderBody.Phrase = new Phrase("", normal_font_8); if (!flag) { cellHeaderBody.Phrase = new Phrase($"...........", normal_font_8); headerTable3a.AddCell(cellHeaderBody); } else { var nom = item.Amount.ToString("#,##0.00", new CultureInfo("id-ID")); // Beban Unit Item Mata Uang cellHeaderBody.Phrase = new Phrase(currencyCode, normal_font_8); cellHeaderBody.HorizontalAlignment = Element.ALIGN_RIGHT; headerTable3a.AddCell(cellHeaderBody); // Beban Unit Item Nominal cellHeaderBody.Phrase = new Phrase(nom, normal_font_8); cellHeaderBody.HorizontalAlignment = Element.ALIGN_RIGHT; headerTable3a.AddCell(cellHeaderBody); } // Empty space cellHeaderBody.Phrase = new Phrase(" ", normal_font_8); headerTable3a.AddCell(cellHeaderBody); annotations.Add(_checkGroup); } for (var i = 0; i < 9 - (3 * (items.Count() % 3)); i++) { cellHeaderBody.Phrase = new Phrase(" ", normal_font); headerTable3a.AddCell(cellHeaderBody); } cellHeader3a.AddElement(headerTable3a); headerTable_C.AddCell(cellHeader3a); var cellLeft = new PdfPCell() { Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, }; var emptyBorder = new PdfPCell() { Border = Rectangle.NO_BORDER }; cellLeft.Colspan = 5; cellLeft.Phrase = new Phrase("\n\nKeterangan: ", normal_font); headerTable3b.AddCell(cellLeft); cellLeft.Colspan = 1; cellLeft.Phrase = new Phrase("", normal_font); headerTable3b.AddCell(cellLeft); cellLeft.Colspan = 4; cellLeft.Phrase = new Phrase(viewModel.Remark, normal_font); headerTable3b.AddCell(cellLeft); emptyBorder.AddElement(headerTable3b); headerTable_C.AddCell(emptyBorder); document.Add(headerTable_C); foreach (var annotation in annotations) { writer.AddAnnotation(annotation); } #endregion #region Keterangan cellHeaderBody4a.Colspan = 7; cellHeaderBody4a.HorizontalAlignment = Element.ALIGN_LEFT; cellHeaderBody4a.Phrase = new Phrase("Keterangan: " + viewModel.Remark, normal_font); headerTable3.AddCell(cellHeaderBody4a); #endregion #region Footer PdfPTable table = new PdfPTable(5) { WidthPercentage = 97 }; float[] widths = new float[] { 1f, 1f, 1f, 1f, 1f }; table.SetWidths(widths); PdfPCell cell = new PdfPCell() { Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE, }; cell.Phrase = new Phrase("\n\n", normal_font); table.AddCell(cell); cell.Phrase = new Phrase("\n\n", normal_font); table.AddCell(cell); cell.Phrase = new Phrase("\n\n", normal_font); table.AddCell(cell); cell.Phrase = new Phrase("\n\n", normal_font); table.AddCell(cell); cell.Phrase = new Phrase("\n\n", normal_font); table.AddCell(cell); // Menyetujui cell.Phrase = new Phrase("Menyetujui,", normal_font); table.AddCell(cell); // Diperiksa cell.Phrase = new Phrase("Diperiksa,", normal_font); table.AddCell(cell); // Mengetahui cell.Colspan = 2; cell.Phrase = new Phrase("Mengetahui,", normal_font); table.AddCell(cell); // Pembuat laporan cell.Colspan = 1; cell.Phrase = new Phrase("Pembuat laporan,", normal_font); table.AddCell(cell); for (var i = 0; i < 11; i++) { cell.Phrase = new Phrase("", normal_font); table.AddCell(cell); cell.Phrase = new Phrase("", normal_font); table.AddCell(cell); cell.Phrase = new Phrase("", normal_font); table.AddCell(cell); cell.Phrase = new Phrase("", normal_font); table.AddCell(cell); cell.Phrase = new Phrase("", normal_font); table.AddCell(cell); } cell.Phrase = new Phrase("(..................)", normal_font); table.AddCell(cell); cell.Phrase = new Phrase("(..................)", normal_font); table.AddCell(cell); cell.Phrase = new Phrase("(..................)", normal_font); table.AddCell(cell); cell.Phrase = new Phrase($"(..................)", normal_font); table.AddCell(cell); cell.Phrase = new Phrase($"({viewModel.CreatedBy})", normal_font); table.AddCell(cell); document.Add(table); #endregion Footer document.Close(); byte[] byteInfo = stream.ToArray(); stream.Write(byteInfo, 0, byteInfo.Length); stream.Position = 0; return(stream); }
public void CreatePdfReport(List <Position> positions, Vehicle vehicle, dynamic report, MemoryStream stream) { Document doc = new Document(PageSize.A4, 15, 15, 15, 15); string[] headers = { "Conduite", "Début", "Fin", "Distance", "Adresse départ", "Adresse d'arrivée", "Vitesse moy" }; float[] columnWidths = { 140f, 140, 140, 120, 200f, 200f, 100 }; PdfWriter.GetInstance(doc, stream).CloseStream = false; doc.Open(); PdfPTable tblHeader = new PdfPTable(2); tblHeader.WidthPercentage = 100; PdfPCell leftCell = new PdfPCell(); leftCell.Border = 0; Paragraph paragraph = new Paragraph($"Rapport de conduite", FontFactory.GetFont("Calibri", 18, BaseColor.BLACK)); paragraph.Alignment = Element.ALIGN_LEFT; leftCell.AddElement(paragraph); leftCell.AddElement(null); leftCell.AddElement(null); PdfPCell rightCell = new PdfPCell(); rightCell.Border = 0; var prg = new Paragraph("Véhicule : " + report.VehicleName); rightCell.AddElement(prg); prg = new Paragraph("Date : " + report.ReportDate); rightCell.AddElement(prg); PdfPCell emptyCell = new PdfPCell(); emptyCell.Border = 0; tblHeader.AddCell(leftCell); tblHeader.AddCell(rightCell); doc.Add(tblHeader); doc.Add(new Chunk(Environment.NewLine)); Paragraph p = new Paragraph(new Chunk( new iTextSharp.text.pdf.draw.LineSeparator(0.0F, 100.0F, BaseColor.BLACK, Element.ALIGN_LEFT, 1))); // call the below to add the line when required. doc.Add(p); doc.Add(new Chunk(Environment.NewLine)); doc.Add(new Chunk(Environment.NewLine)); PdfPTable table = new PdfPTable(2); table.WidthPercentage = 90; var bodyLeftCell = new PdfPCell(); bodyLeftCell.Border = 0; bodyLeftCell.AddElement( new Paragraph("Distance : " + report.Distance.ToString(CultureInfo.InvariantCulture) + " Km.")); bodyLeftCell.AddElement( new Paragraph("Vitesse moyene: " + report.AvgSpeed.ToString(CultureInfo.InvariantCulture) + " Km/h")); bodyLeftCell.AddElement(new Paragraph("Vitesse max: " + report.MaxSpeed + " Km/h")); var bodyRightCell = new PdfPCell() ; bodyRightCell.Border = 0; table.AddCell(bodyLeftCell); // table.AddCell(emptyCell); table.AddCell(bodyRightCell); table.DefaultCell.Border = 0; ; doc.Add(table); doc.Add(new Chunk(Environment.NewLine)); p.Alignment = Element.ALIGN_CENTER; doc.Add(new Chunk(Environment.NewLine)); doc.Add(new Chunk(Environment.NewLine)); PdfPTable pTable = new PdfPTable(headers.Length); pTable.WidthPercentage = 90; pTable.SetWidths(columnWidths); foreach (string t in headers) { var cell = new PdfPCell(new Phrase(t, FontFactory.GetFont("Calibri", 12, BaseColor.BLACK))) { HorizontalAlignment = Element.ALIGN_CENTER, BackgroundColor = new BaseColor(230, 230, 250) }; pTable.AddCell(cell); } foreach (var position in report.Positions) { pTable.AddCell( ItextSharpHelper.Cell(position.MotionStatus == "Stopped" ? "Arrêt" : "Conduite", BaseColor.BLACK)); pTable.AddCell(ItextSharpHelper.Cell(DateTime.Parse(position.StartPeriod).ToShortTimeString().ToString(), BaseColor.BLACK)); pTable.AddCell(ItextSharpHelper.Cell(DateTime.Parse(position.EndPeriod).ToShortTimeString(), BaseColor.BLACK)); pTable.AddCell(ItextSharpHelper.Cell(position.Distance.ToString(CultureInfo.InvariantCulture), BaseColor.BLACK)); pTable.AddCell(ItextSharpHelper.Cell(position.StartAddres, BaseColor.BLACK)); pTable.AddCell(ItextSharpHelper.Cell(position.ArrivalAddres, BaseColor.BLACK)); pTable.AddCell(ItextSharpHelper.Cell(position.AvgSpeed.ToString(CultureInfo.InvariantCulture), BaseColor.BLACK)); } // doc.Add(p); doc.Add(pTable); doc.Close(); }
public void PrintPO(poheader poh, List <podetail> PODetail, string taxStr) { Dictionary <string, string> companyInfo = getCompanyInformation(); //string stateDetail = customer custDetail = CustomerDB.getCustomerDetailForPO(poh.CustomerID); string[] companyBillingAdd = CompanyAddressDB.getCompTopBillingAdd(Login.companyID); string poNoSuffix = ""; string supplAdd = ""; string stype = ""; if (poh.DocumentID == "POGENERAL") { poNoSuffix = "G-"; supplAdd = "Contractor:\n" + custDetail.name + Main.delimiter1 + "\n" + custDetail.BillingAddress + "\n"; stype = "Contractor"; } else if (poh.DocumentID == "PURCHASEORDER") { poNoSuffix = "P-"; stype = "Supplier"; } supplAdd = stype + ":\n" + custDetail.name + Main.delimiter1 + "\n" + custDetail.BillingAddress + "\n"; if (custDetail.StateName.ToString().Length != 0) { supplAdd = supplAdd + "Sate Name:" + custDetail.StateName; } if (custDetail.StateCode.ToString().Length != 0) { supplAdd = supplAdd + "\nState Code:" + custDetail.StateCode; } if (custDetail.OfficeName.ToString().Length != 0) { supplAdd = supplAdd + "\nGST:" + custDetail.OfficeName; // For GST Code } //; : main.delimiter2 //$ : main.delimiter1 string InvoiceTo = "Invoice To: \n" + companyBillingAdd[0] + Main.delimiter1 + "\n" + companyBillingAdd[1] + "\nGST:" + companyInfo["GST"] + "\nCIN:" + companyInfo["CIN"] + "\nPAN:" + companyInfo["PAN"]; string DespatchTo = "Dispatch To:\n" + companyBillingAdd[0] + Main.delimiter1 + "\n" + poh.DeliveryAddress + "\nGST:" + companyInfo["GST"]; string HeaderString = supplAdd + Main.delimiter2 + "PO No : " + poNoSuffix + poh.PONo + " , Date: " + String.Format("{0:dd MMMM, yyyy}", Convert.ToDateTime(poh.PODate)) + Main.delimiter2 + stype + " Reference : " + poh.ReferenceQuotation.Replace(";", ",\n") + Main.delimiter2 + "Mode Of Dispatch:" + CatalogueValueDB.getParamValue("TransportationMode", poh.TransportationMode) + Main.delimiter2 + "Delivery Period : " + poh.DeliveryPeriod + " Days" + Main.delimiter2 + InvoiceTo + Main.delimiter2 + "Price basis : " + CatalogueValueDB.getParamValue("PriceBasis", poh.PriceBasis) + Main.delimiter2 + "Delivery at : " + poh.DeliveryAt + Main.delimiter2 + "Terms of Payment : " + PTDefinitionDB.getPaymentTermString(poh.PaymentTerms) + Main.delimiter2 + "Tax : " + CatalogueValueDB.getParamValue("TaxStatus", poh.TaxTerms) + Main.delimiter2 + DespatchTo + Main.delimiter2 + "Partial Shipment : " + poh.PartialShipment + Main.delimiter2 + "Transhipment : " + poh.Transhipment + Main.delimiter2 + "Packaging Specification : " + poh.PackingSpec + Main.delimiter2 + poh.SpecialNote; string footer1 = "Amount In Words\n\n"; string ColHeader = "SI No.;Description of Goods;Quantity;Unit;Unit Rate;Amount;Warranty\nIn Days"; string footer2 = "This Purchase Order, being computer generated, does not require physical signature."; string declaration = "We, Cellcomm Solutions Limited (also referred to as “CSL”), are pleased to place" + " this Purchase Order (also referred to as 'PO') with the " + stype + " addressed below.In accepting this Purchase Order, the " + stype + " undertakes to supply the Goods described herein as per the details and instructions shown below" + " (such details and instructions being the Specific Terms and Conditions agreed between the Parties) " + "and also subject to the General Terms & Conditions contained herein."; string termsAndCond = getTCString(poh.TermsAndCondition, poh.DocumentID); double totQuant = 0.00; double totAmnt = 0.00; int n = 1; string ColDetailString = ""; var count = PODetail.Count(); foreach (podetail pod in PODetail) { if (n == count) { ColDetailString = ColDetailString + n + Main.delimiter1 + pod.Description + Main.delimiter1 + pod.Quantity + Main.delimiter1 + pod.Unit + Main.delimiter1 + pod.Price + Main.delimiter1 + (pod.Quantity * pod.Price) + Main.delimiter1 + pod.WarrantyDays; } else { ColDetailString = ColDetailString + n + Main.delimiter1 + pod.Description + Main.delimiter1 + pod.Quantity + Main.delimiter1 + pod.Unit + Main.delimiter1 + pod.Price + Main.delimiter1 + (pod.Quantity * pod.Price) + Main.delimiter1 + pod.WarrantyDays + Main.delimiter2; } totQuant = totQuant + pod.Quantity; totAmnt = totAmnt + (pod.Quantity * pod.Price); n++; } try { SaveFileDialog sfd = new SaveFileDialog(); sfd.Title = "Save As PDF"; sfd.Filter = "Pdf files (*.Pdf)|*.pdf"; sfd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); if (poh.Status == 0 && poh.DocumentStatus < 99) { sfd.FileName = poh.DocumentID + "-Temp-" + poh.TemporaryNo; } else { sfd.FileName = poh.DocumentID + "-" + poh.PONo; } ///sfd.FileName = poh.DocumentID + "-" + poh.PONo; if (sfd.ShowDialog() == DialogResult.Cancel || sfd.FileName == "") { return; } FileStream fs = new FileStream(sfd.FileName, FileMode.Create, FileAccess.Write); Rectangle rec = new Rectangle(PageSize.A4); iTextSharp.text.Document doc = new iTextSharp.text.Document(rec); PdfWriter writer = PdfWriter.GetInstance(doc, fs); MyEvent evnt = new MyEvent(); writer.PageEvent = evnt; doc.Open(); Font font1 = FontFactory.GetFont("Arial", 8, iTextSharp.text.Font.NORMAL, BaseColor.BLACK); Font font2 = FontFactory.GetFont("Arial", 8, iTextSharp.text.Font.BOLD, BaseColor.BLACK); Font font3 = FontFactory.GetFont("Arial", 8, iTextSharp.text.Font.ITALIC, BaseColor.BLACK); Font font4 = FontFactory.GetFont("Arial", 5, iTextSharp.text.Font.NORMAL, BaseColor.BLACK); String URL = "Cellcomm2.JPG"; iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(URL); img.Alignment = Element.ALIGN_LEFT; PdfPTable tableHeader = new PdfPTable(2); tableHeader.WidthPercentage = 100; PdfPCell cellImg = new PdfPCell(); Paragraph pp = new Paragraph(); pp.Add(new Chunk(img, 0, 0)); cellImg.AddElement(pp); cellImg.Border = 0; tableHeader.AddCell(cellImg); PdfPCell cellAdd = new PdfPCell(); Paragraph ourAddr = new Paragraph(""); CompanyDetailDB compDB = new CompanyDetailDB(); cmpnydetails det = compDB.getdetails().FirstOrDefault(comp => comp.companyID == 1); if (det != null) { ourAddr.Add(new Chunk(det.companyname + "\n", font2)); ourAddr.Add(new Chunk(det.companyAddress.Replace("\r\n", "\n"), font4)); StringBuilder sb = new StringBuilder(); sb.Append("\nGST : " + companyInfo["GST"] + "\nState Code for GST : " + companyInfo["StateCode"] + "\nCIN : " + companyInfo["CIN"] + "\nPAN : " + companyInfo["PAN"]); ourAddr.Add(new Chunk(sb.ToString(), font4)); ourAddr.Alignment = Element.ALIGN_RIGHT; ourAddr.SetLeading(0.0f, 1.5f); } cellAdd.AddElement(ourAddr); cellAdd.Border = 0; tableHeader.AddCell(cellAdd); PdfPTable tableDocName = new PdfPTable(1); tableDocName.WidthPercentage = 100; PdfPCell cellHdr = new PdfPCell(new Phrase("PURCHASE ORDER", font2)); cellHdr.Border = 0; cellHdr.HorizontalAlignment = PdfPCell.ALIGN_CENTER; tableDocName.AddCell(cellHdr); if (poh.CountryID != null && poh.CountryID != "India") { PdfPCell cellHdrInr = new PdfPCell(new Phrase("(Import)", font2)); cellHdrInr.Border = 0; cellHdrInr.HorizontalAlignment = PdfPCell.ALIGN_CENTER; tableDocName.AddCell(cellHdrInr); } Paragraph paragraphOpenCluse = new Paragraph(new Phrase(declaration, font1)); paragraphOpenCluse.Alignment = Element.ALIGN_JUSTIFIED; paragraphOpenCluse.SpacingBefore = 10; PrintPurchaseOrder prog = new PrintPurchaseOrder(); string[] HeaderStr = HeaderString.Split(Main.delimiter2); PdfPTable TableAddress = new PdfPTable(7); TableAddress.SpacingBefore = 20f; TableAddress.WidthPercentage = 100; float[] HWidths = new float[] { 1f, 8f, 2f, 1.5f, 1.5f, 3f, 1.5f }; TableAddress.SetWidths(HWidths); PdfPCell cell; int[] arr = { 6, 7, 9, 10 }; float wid = 0; for (int i = 0; i < HeaderStr.Length; i++) { if (i == 0 || i == 5 || i == 10) { string[] format = HeaderStr[i].Split(Main.delimiter1); Phrase phr = new Phrase(); phr.Add(new Chunk(format[0], font2)); phr.Add(new Chunk(format[1], font1)); cell = new PdfPCell(phr); cell.Colspan = 2; cell.Rowspan = 4; cell.HorizontalAlignment = 0; //0=Left, 1=Centre, 2=Right TableAddress.AddCell(cell); } else { cell = new PdfPCell(new Phrase(HeaderStr[i].Trim(), font1)); cell.Colspan = 5; cell.MinimumHeight = wid; TableAddress.AddCell(cell); } } string[] ColHeaderStr = ColHeader.Split(';'); PdfPTable TableItemDetails = new PdfPTable(7); TableItemDetails.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER; TableItemDetails.WidthPercentage = 100; float[] width = new float[] { 1f, 8f, 2f, 1.5f, 2f, 2.5f, 1.5f }; TableItemDetails.SetWidths(width); for (int i = 0; i < ColHeaderStr.Length; i++) { if (i == 4 || i == 5) { PdfPCell hcell = new PdfPCell(new Phrase(ColHeaderStr[i].Trim() + "\n(" + poh.CurrencyID + ")", font2)); hcell.HorizontalAlignment = PdfPCell.ALIGN_CENTER; TableItemDetails.AddCell(hcell); } else { PdfPCell hcell = new PdfPCell(new Phrase(ColHeaderStr[i].Trim(), font2)); hcell.HorizontalAlignment = PdfPCell.ALIGN_CENTER; TableItemDetails.AddCell(hcell); } } //--- PdfPCell foot = new PdfPCell(new Phrase("")); foot.Colspan = 7; foot.BorderWidthTop = 0; foot.MinimumHeight = 0.5f; TableItemDetails.AddCell(foot); TableItemDetails.HeaderRows = 2; TableItemDetails.FooterRows = 1; TableItemDetails.SkipFirstHeader = false; TableItemDetails.SkipLastFooter = true; //--- int track = 0; decimal dc1 = 0; decimal dc2 = 0; string[] DetailStr = ColDetailString.Split(Main.delimiter2); float hg = 0f; for (int i = 0; i < DetailStr.Length; i++) { track = 0; hg = TableItemDetails.GetRowHeight(i + 1); string[] str = DetailStr[i].Split(Main.delimiter1); for (int j = 0; j < str.Length; j++) { PdfPCell pcell; if (j == 2 || j == 4 || j == 5) { decimal p = 1; if (Decimal.TryParse(str[j], out p)) { pcell = new PdfPCell(new Phrase(String.Format("{0:0.00}", Convert.ToDecimal(str[j])), font1)); } else { pcell = new PdfPCell(new Phrase("")); } pcell.Border = 0; if (j == 5) { if (str[0].Length == 0) { pcell.BorderWidthBottom = 0.01f; track = 1; dc2 = Convert.ToDecimal(str[j]); } else { dc1 = Convert.ToDecimal(str[j]); } } } else { if (j == 6) { if ((str[j].Trim().Length == 0 || Convert.ToInt32(str[j]) == 0) && (track != 1)) { pcell = new PdfPCell(new Phrase("NA", font1)); } else { pcell = new PdfPCell(new Phrase(str[j], font1)); } } else if (j == 3) { int m = 1; if (Int32.TryParse(str[j], out m) == true) { if (Convert.ToInt32(str[j]) == 0) { pcell = new PdfPCell(new Phrase("", font1)); } else { pcell = new PdfPCell(new Phrase(str[j], font1)); } } else { pcell = new PdfPCell(new Phrase(str[j], font1)); } } else { pcell = new PdfPCell(new Phrase(str[j], font1)); } pcell.Border = 0; } pcell.MinimumHeight = 10; //pcell.MinimumHeight = 20; if (j == 1) { pcell.HorizontalAlignment = PdfPCell.ALIGN_LEFT; } else { pcell.HorizontalAlignment = PdfPCell.ALIGN_CENTER; } pcell.BorderWidthLeft = 0.01f; pcell.BorderWidthRight = 0.01f; TableItemDetails.AddCell(pcell); } } double roundedAmt = Math.Round(totAmnt, 0); double diffAmount = roundedAmt - totAmnt; if (diffAmount != 0) { TableItemDetails.AddCell(""); TableItemDetails.AddCell(""); PdfPCell cellTot = new PdfPCell(new Phrase("", font1)); cellTot.Colspan = 3; cellTot.HorizontalAlignment = PdfPCell.ALIGN_CENTER; TableItemDetails.AddCell(cellTot); TableItemDetails.AddCell(new Phrase(String.Format("{0:0.00}", totAmnt), font1)); TableItemDetails.AddCell(""); TableItemDetails.AddCell(""); TableItemDetails.AddCell(""); PdfPCell cellRound = new PdfPCell(new Phrase("Rounding off", font1)); cellRound.Colspan = 3; cellRound.HorizontalAlignment = PdfPCell.ALIGN_CENTER; TableItemDetails.AddCell(cellRound); TableItemDetails.AddCell(new Phrase(String.Format("{0:0.00}", diffAmount), font1)); TableItemDetails.AddCell(""); } TableItemDetails.AddCell(""); TableItemDetails.AddCell(""); PdfPCell cellTotal = new PdfPCell(new Phrase("Total", font1)); cellTotal.Colspan = 3; cellTotal.HorizontalAlignment = PdfPCell.ALIGN_CENTER; TableItemDetails.AddCell(cellTotal); TableItemDetails.AddCell(new Phrase(String.Format("{0:0.00}", roundedAmt), font1)); TableItemDetails.AddCell(""); string total = footer1 + NumberToString.convert(roundedAmt.ToString()).Replace("INR", poh.CurrencyID) + "\n\n"; PdfPCell fcell1 = new PdfPCell(new Phrase((total), font1)); fcell1.Colspan = 6; fcell1.MinimumHeight = 50; fcell1.HorizontalAlignment = PdfPCell.ALIGN_LEFT; fcell1.BorderWidthRight = 0; fcell1.BorderWidthTop = 0; TableItemDetails.AddCell(fcell1); PdfPCell fcell4 = new PdfPCell(new Phrase("E. & O.E", font1)); fcell4.HorizontalAlignment = PdfPCell.ALIGN_RIGHT; fcell4.BorderWidthLeft = 0; fcell4.BorderWidthTop = 0; TableItemDetails.AddCell(fcell4); PdfPTable tableSub = new PdfPTable(1); tableSub.DefaultCell.Border = 0; tableSub.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER; tableSub.AddCell(new Phrase("Subject To Bangalore Jurisdiction", font2)); PdfPCell celSub = new PdfPCell(tableSub); celSub.Border = 0; celSub.Colspan = 7; TableItemDetails.AddCell(celSub); TableItemDetails.KeepRowsTogether(TableItemDetails.Rows.Count - 6, TableItemDetails.Rows.Count); Paragraph footer = new Paragraph(new Phrase("Note : " + footer2, font3)); footer.Alignment = Element.ALIGN_LEFT; PdfPTable TCTab = new PdfPTable(2); if (poh.TermsAndCondition.Trim().Length != 0) { Chunk TCchunk = new Chunk("General Terms & Conditions\n", font2); TCchunk.SetUnderline(0.2f, -2f); TCTab = new PdfPTable(2); TCTab.WidthPercentage = 100; PdfPCell TCCell = new PdfPCell(); TCCell.Colspan = 2; TCCell.Border = 0; TCCell.AddElement(TCchunk); TCTab.AddCell(TCCell); try { string[] ParaTC = termsAndCond.Split(Main.delimiter2); for (int i = 0; i < ParaTC.Length - 1; i++) { TCCell = new PdfPCell(); TCCell.Colspan = 2; TCCell.Border = 0; Paragraph header = new Paragraph(); Paragraph details = new Paragraph(); details.IndentationLeft = 12f; details.IndentationRight = 12f; details.Alignment = Element.ALIGN_JUSTIFIED; string paraHeaderStr = (i + 1) + ". " + ParaTC[i].Substring(0, ParaTC[i].IndexOf(Main.delimiter1)) + ":"; string paraFooterStr = ParaTC[i].Substring(ParaTC[i].IndexOf(Main.delimiter1) + 1); header.Add(new Phrase(paraHeaderStr, font2)); details.Add(new Phrase(paraFooterStr, font1)); TCCell.AddElement(header); TCCell.AddElement(details); TCTab.AddCell(TCCell); } } catch (Exception ex) { MessageBox.Show(this.ToString() + "-" + System.Reflection.MethodBase.GetCurrentMethod().Name + "() : Error-" + ex.ToString()); } try { if (TCTab.Rows.Count >= 3) { TCTab.KeepRowsTogether(0, 3); } } catch (Exception ex) { MessageBox.Show(this.ToString() + "-" + System.Reflection.MethodBase.GetCurrentMethod().Name + "() : Error-" + ex.ToString()); } } doc.Add(tableHeader); doc.Add(tableDocName); doc.Add(paragraphOpenCluse); doc.Add(TableAddress); doc.Add(TableItemDetails); doc.Add(footer); if (poh.TermsAndCondition.Trim().Length != 0) { doc.Add(TCTab); } doc.Close(); if (poh.Status == 0 && poh.DocumentStatus < 99) { String wmurl = ""; wmurl = "004.png"; PrintWaterMark.PdfStampWithNewFile(wmurl, sfd.FileName); } MessageBox.Show("Document Saved"); } catch (Exception ex) { MessageBox.Show("Failed to Save Document"); } }
public void ExportDatatablePdf(DataTable dtblTable, String strPdfPath, string strHeader) { System.IO.FileStream fs = new FileStream(strPdfPath, FileMode.Create, FileAccess.Write, FileShare.None); Document document = new Document(); document.SetPageSize(iTextSharp.text.PageSize.LETTER); PdfWriter writer = PdfWriter.GetInstance(document, fs); document.Open(); //Report Header BaseFont bfTimes = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false); Font times = new Font(bfTimes, 12, Font.ITALIC, iTextSharp.text.BaseColor.RED); BaseFont bfntHead = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); Font fntHead = new Font(bfntHead, 16, 1, iTextSharp.text.BaseColor.BLACK); Paragraph prgHeading = new Paragraph(); prgHeading.Alignment = Element.ALIGN_CENTER; prgHeading.Add(new Chunk(strHeader.ToUpper(), fntHead)); document.Add(prgHeading); //Add a line seperation Paragraph p = new Paragraph(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(0.0F, 100.0F, iTextSharp.text.BaseColor.BLACK, Element.ALIGN_LEFT, 1))); document.Add(p); //Add line break document.Add(new Chunk("\n", fntHead)); //Write the table PdfPTable table = new PdfPTable(dtblTable.Columns.Count); //Table header BaseFont btnColumnHeader = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); Font fntColumnHeader = new Font(btnColumnHeader, 9, 1, iTextSharp.text.BaseColor.BLACK); for (int i = 0; i < dtblTable.Columns.Count; i++) { PdfPCell cell = new PdfPCell(); cell.BorderColor = WebColors.GetRGBColor("#c4e4ff"); cell.BackgroundColor = WebColors.GetRGBColor("#c5d9ea"); cell.AddElement(new Chunk(dtblTable.Columns[i].ColumnName.ToUpper(), fntColumnHeader)); table.AddCell(cell); } //table Data BaseFont btnColumnData = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); Font fntColumnData = new Font(btnColumnData, 9, 2, iTextSharp.text.BaseColor.BLACK); for (int i = 0; i < dtblTable.Rows.Count; i++) { for (int j = 0; j < dtblTable.Columns.Count; j++) { PdfPCell cell = new PdfPCell(); cell.BorderColor = WebColors.GetRGBColor("#c4e4ff"); cell.BackgroundColor = iTextSharp.text.BaseColor.WHITE; cell.AddElement(new Chunk(dtblTable.Rows[i][j].ToString(), fntColumnData)); table.AddCell(cell); // table.AddCell(dtblTable.Rows[i][j].ToString()); } } document.Add(table); document.Close(); writer.Close(); fs.Close(); }
public ActionResult GerarRelatorioLista() { // Prepara geração if ((String)Session["Ativa"] == null) { return(RedirectToAction("Login", "ControleAcesso")); } String data = DateTime.Today.Date.ToShortDateString(); data = data.Substring(0, 2) + data.Substring(3, 2) + data.Substring(6, 4); String nomeRel = "AgendaLista" + "_" + data + ".pdf"; List <AGENDA> lista = (List <AGENDA>)Session["ListaAgenda"]; AGENDA filtro = (AGENDA)Session["FiltroAgenda"]; Font meuFont = FontFactory.GetFont("Arial", 8, iTextSharp.text.Font.NORMAL, BaseColor.BLACK); Font meuFont1 = FontFactory.GetFont("Arial", 9, iTextSharp.text.Font.NORMAL, BaseColor.BLACK); Font meuFont2 = FontFactory.GetFont("Arial", 12, iTextSharp.text.Font.NORMAL, BaseColor.BLACK); // Cria documento Document pdfDoc = new Document(PageSize.A4.Rotate(), 10, 10, 10, 10); PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDoc, Response.OutputStream); pdfDoc.Open(); // Linha horizontal Paragraph line = new Paragraph(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(0.0F, 100.0F, BaseColor.BLUE, Element.ALIGN_LEFT, 1))); pdfDoc.Add(line); // Cabeçalho PdfPTable table = new PdfPTable(5); table.WidthPercentage = 100; table.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right table.SpacingBefore = 1f; table.SpacingAfter = 1f; PdfPCell cell = new PdfPCell(); cell.Border = 0; Image image = Image.GetInstance(Server.MapPath("~/Images/5.png")); image.ScaleAbsolute(50, 50); cell.AddElement(image); table.AddCell(cell); cell = new PdfPCell(new Paragraph("Agenda - Listagem", meuFont2)) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER }; cell.Border = 0; cell.Colspan = 4; table.AddCell(cell); pdfDoc.Add(table); // Linha Horizontal Paragraph line1 = new Paragraph(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(0.0F, 100.0F, BaseColor.BLUE, Element.ALIGN_LEFT, 1))); pdfDoc.Add(line1); line1 = new Paragraph(" "); pdfDoc.Add(line1); // Grid table = new PdfPTable(new float[] { 60f, 60f, 90f, 200f, 120f, 70f, 50f }); table.WidthPercentage = 100; table.HorizontalAlignment = 0; table.SpacingBefore = 1f; table.SpacingAfter = 1f; cell = new PdfPCell(new Paragraph("Itens de Agenda selecionados pelos parametros de filtro abaixo", meuFont1)) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_LEFT }; cell.Colspan = 6; cell.BackgroundColor = BaseColor.LIGHT_GRAY; table.AddCell(cell); cell = new PdfPCell(new Paragraph("Data", meuFont)) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_LEFT }; cell.BackgroundColor = BaseColor.LIGHT_GRAY; table.AddCell(cell); cell = new PdfPCell(new Paragraph("Hora", meuFont)) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_LEFT }; cell.BackgroundColor = BaseColor.LIGHT_GRAY; table.AddCell(cell); cell = new PdfPCell(new Paragraph("Categoria", meuFont)) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_LEFT }; cell.BackgroundColor = BaseColor.LIGHT_GRAY; table.AddCell(cell); cell = new PdfPCell(new Paragraph("Título", meuFont)) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_LEFT }; cell.BackgroundColor = BaseColor.LIGHT_GRAY; table.AddCell(cell); cell = new PdfPCell(new Paragraph("Contato", meuFont)) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_LEFT }; cell.BackgroundColor = BaseColor.LIGHT_GRAY; table.AddCell(cell); cell = new PdfPCell(new Paragraph("Status", meuFont)) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_LEFT }; cell.BackgroundColor = BaseColor.LIGHT_GRAY; table.AddCell(cell); cell = new PdfPCell(new Paragraph("Anexos", meuFont)) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_LEFT }; cell.BackgroundColor = BaseColor.LIGHT_GRAY; table.AddCell(cell); foreach (AGENDA item in lista) { cell = new PdfPCell(new Paragraph(item.AGEN_DT_DATA.ToShortDateString(), meuFont)) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_LEFT }; table.AddCell(cell); cell = new PdfPCell(new Paragraph(item.AGEN_HR_HORA.ToString(), meuFont)) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_LEFT }; table.AddCell(cell); cell = new PdfPCell(new Paragraph(item.CATEGORIA_AGENDA.CAAG_NM_NOME, meuFont)) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_LEFT }; table.AddCell(cell); cell = new PdfPCell(new Paragraph(item.AGEN_NM_TITULO, meuFont)) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_LEFT }; table.AddCell(cell); if (item.USUARIO1 != null) { cell = new PdfPCell(new Paragraph(item.USUARIO1.USUA_NM_NOME, meuFont)) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_LEFT }; table.AddCell(cell); } else { cell = new PdfPCell(new Paragraph("-", meuFont)) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_LEFT }; table.AddCell(cell); } if (item.AGEN_IN_STATUS == 1) { cell = new PdfPCell(new Paragraph("Ativo", meuFont)) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_LEFT }; table.AddCell(cell); } else if (item.AGEN_IN_STATUS == 2) { cell = new PdfPCell(new Paragraph("Suspenso", meuFont)) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_LEFT }; table.AddCell(cell); } else { cell = new PdfPCell(new Paragraph("Encerrado", meuFont)) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_LEFT }; table.AddCell(cell); } if (item.AGENDA_ANEXO.Count > 0) { cell = new PdfPCell(new Paragraph(item.AGENDA_ANEXO.Count.ToString(), meuFont)) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_LEFT }; table.AddCell(cell); } else { cell = new PdfPCell(new Paragraph("0", meuFont)) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_LEFT }; table.AddCell(cell); } } pdfDoc.Add(table); // Linha Horizontal Paragraph line2 = new Paragraph(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(0.0F, 100.0F, BaseColor.BLUE, Element.ALIGN_LEFT, 1))); pdfDoc.Add(line2); // Rodapé Chunk chunk1 = new Chunk("Parâmetros de filtro: ", FontFactory.GetFont("Arial", 10, Font.NORMAL, BaseColor.BLACK)); pdfDoc.Add(chunk1); String parametros = String.Empty; Int32 ja = 0; if (filtro != null) { if (filtro.CAAG_CD_ID > 0) { parametros += "Categoria: " + filtro.CAAG_CD_ID; ja = 1; } if (filtro.AGEN_DT_DATA != null) { if (ja == 0) { parametros += "Data: " + filtro.AGEN_DT_DATA.ToShortDateString(); ja = 1; } else { parametros += " e Data: " + filtro.AGEN_DT_DATA.ToShortDateString(); } } if (filtro.AGEN_NM_TITULO != null) { if (ja == 0) { parametros += "Título: " + filtro.AGEN_NM_TITULO; ja = 1; } else { parametros += " e Título: " + filtro.AGEN_NM_TITULO; } } if (filtro.AGEN_DS_DESCRICAO != null) { if (ja == 0) { parametros += "Descrição: " + filtro.AGEN_DS_DESCRICAO; ja = 1; } else { parametros += " e Descrição: " + filtro.AGEN_DS_DESCRICAO; } } if (ja == 0) { parametros = "Nenhum filtro definido."; } } else { parametros = "Nenhum filtro definido."; } Chunk chunk = new Chunk(parametros, FontFactory.GetFont("Arial", 9, Font.NORMAL, BaseColor.BLACK)); pdfDoc.Add(chunk); // Linha Horizontal Paragraph line3 = new Paragraph(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(0.0F, 100.0F, BaseColor.BLUE, Element.ALIGN_LEFT, 1))); pdfDoc.Add(line3); // Finaliza pdfWriter.CloseStream = false; pdfDoc.Close(); Response.Buffer = true; Response.ContentType = "application/pdf"; Response.AddHeader("content-disposition", "attachment;filename=" + nomeRel); Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.Write(pdfDoc); Response.End(); return(RedirectToAction("MontarTelaAgenda")); }
void ExportDataTableToPdf(DataTable dttable, string strpdfFile, string strHeader, string folderpath) { try { System.IO.FileStream fs = new FileStream(strpdfFile, FileMode.Create, FileAccess.Write, FileShare.None); Document document = new Document(); document.SetPageSize(iTextSharp.text.PageSize.A4); PdfWriter writer = PdfWriter.GetInstance(document, fs); document.Open(); BaseFont bfntHead = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); Font fntHead = new iTextSharp.text.Font(bfntHead, 8, 1, iTextSharp.text.Color.GRAY); Paragraph prgHeading = new Paragraph(); prgHeading.Alignment = Element.ALIGN_CENTER; prgHeading.Add(new Chunk(strHeader.ToUpper(), fntHead)); document.Add(prgHeading); Paragraph prgspace = new Paragraph(); prgspace.Add(new Chunk("\n")); document.Add(prgspace); PdfPTable table = new PdfPTable(dttable.Columns.Count); BaseFont btncolumnheader = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1257, BaseFont.NOT_EMBEDDED); iTextSharp.text.Font fntColumnHeader = new Font(btncolumnheader, 4, 1, iTextSharp.text.Color.WHITE); BaseFont btnrow = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1257, BaseFont.NOT_EMBEDDED); iTextSharp.text.Font fntRow = new Font(btnrow, 4, 1, iTextSharp.text.Color.BLACK); for (int i = 0; i < dttable.Columns.Count; i++) { PdfPCell cell = new PdfPCell(); cell.Rotation = 90; cell.HorizontalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE; cell.BackgroundColor = iTextSharp.text.Color.GRAY; cell.AddElement(new Chunk(dttable.Columns[i].ColumnName.ToUpper(), fntColumnHeader)); table.AddCell(cell); } for (int i = 0; i < dttable.Rows.Count; i++) { for (int j = 0; j < dttable.Columns.Count; j++) { PdfPCell cell = new PdfPCell(); if (dttable.Rows[i][j].ToString() == "0") { cell.AddElement(new Chunk("", fntRow)); } else { cell.AddElement(new Chunk(dttable.Rows[i][j].ToString(), fntRow)); } table.AddCell(cell); } } document.Add(table); document.Close(); writer.Close(); fs.Close(); System.Diagnostics.Process.Start(folderpath + "ITEM_WISE_SALE_ORDER.pdf"); MessageBox.Show("PDF Created Sucessfully"); } catch (Exception excp) { if (excp.Message.Contains("The process cannot access the file")) { MessageBox.Show("Please Close the Already open PDF File.."); return; } } }
private void button1_Click(object sender, EventArgs e) { // Document documento = new Document(); PdfWriter wri = PdfWriter.GetInstance(documento, new FileStream("C:/Users/lizar/Documents/" + MenuSocio.nombre_usuario + "-reporte.pdf", FileMode.Create)); documento.Open(); PdfPTable table = new PdfPTable(4); //table.DefaultCell.Border = 0; PdfPCell imagen = new PdfPCell(new Paragraph()); iTextSharp.text.Image im = iTextSharp.text.Image.GetInstance("C:/Users/lizar/Desktop/ImagenesClub/logo.png"); /*float porc = 80 / im.Width; * im.ScalePercent(porc * 100);*/ imagen.Colspan = 4; imagen.AddElement(im); table.AddCell(imagen); PdfPCell celdaInicial = (new PdfPCell(new Paragraph("Credencial de Socio", FontFactory.GetFont("arial", 14, BaseColor.WHITE))) { HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE }); celdaInicial.BackgroundColor = BaseColor.GREEN; celdaInicial.Colspan = 4;//combina celdas debe tener el mismo tamaño o menor rowspan filas colpan columnas /*celdaInicial.BorderWidthBottom = 0; * celdaInicial.BorderWidthLeft = 0; * celdaInicial.BorderWidthTop = 0; * celdaInicial.BorderWidthRight=0;*/ table.AddCell(celdaInicial); PdfPCell imagen2 = new PdfPCell(new Paragraph()); iTextSharp.text.Image im2 = iTextSharp.text.Image.GetInstance(MenuSocio.imagenfoto);//imagend el socio imagen2.AddElement(im2); float por = 50 / im.Width; im.ScalePercent(por * 100); imagen2.Colspan = 1; imagen2.Rowspan = 2; /*imagen2.BorderWidthBottom = 0; * imagen2.BorderWidthLeft = 0; * imagen2.BorderWidthTop = 0; * imagen2.BorderWidthRight = 0;*/ table.AddCell(imagen2); PdfPCell nombre = (new PdfPCell(new Paragraph("Correo: " + textBox1.Text, FontFactory.GetFont("arial", 12, 1, BaseColor.BLACK))) { HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE }); nombre.Colspan = 3; nombre.Rowspan = 1; /*nombre.BorderWidthBottom = 0; * nombre.BorderWidthLeft = 0; * nombre.BorderWidthTop = 0; * nombre.BorderWidthRight = 0;*/ table.AddCell(nombre); PdfPCell correo = (new PdfPCell(new Paragraph("Nombre:" + textBox2.Text, FontFactory.GetFont("arial", 12, BaseColor.BLACK))) { HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE }); correo.Colspan = 3; correo.Rowspan = 1; table.AddCell(correo); PdfPCell fechanaci = (new PdfPCell(new Paragraph("Fecha de Nacimiento:" + textBox3.Text, FontFactory.GetFont("arial", 12, BaseColor.BLACK))) { HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE }); fechanaci.Colspan = 4; fechanaci.Rowspan = 1; table.AddCell(fechanaci); PdfPCell tip = new PdfPCell(new Paragraph(" Status: ")); tip.Colspan = 2; tip.Rowspan = 1; table.AddCell(tip); if (radioButton1.Checked == true) { PdfPCell tip2 = (new PdfPCell(new Paragraph(radioButton1.Text, FontFactory.GetFont("arial", 12, BaseColor.BLACK))) { HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE }); tip2.Colspan = 2; tip2.Rowspan = 1; table.AddCell(tip2); } if (radioButton2.Checked == true) { PdfPCell tip2 = (new PdfPCell(new Paragraph(radioButton2.Text, FontFactory.GetFont("arial", 12, BaseColor.BLACK))) { HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE }); tip2.Colspan = 2; tip2.Rowspan = 1; table.AddCell(tip2); } PdfPCell actividad = new PdfPCell(new Paragraph(" Actividad: ")); actividad.Colspan = 2; actividad.Rowspan = 1; table.AddCell(actividad); PdfPCell actividad2 = (new PdfPCell(new Paragraph(textBox6.Text, FontFactory.GetFont("arial", 12, 1, BaseColor.BLACK))) { HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE }); actividad2.Colspan = 2; actividad2.Rowspan = 1; table.AddCell(actividad2); PdfPCell horario = new PdfPCell(new Paragraph(" Horario: ")); horario.Colspan = 2; horario.Rowspan = 1; table.AddCell(horario); PdfPCell horario2 = (new PdfPCell(new Paragraph(textBox5.Text, FontFactory.GetFont("arial", 12, 1, BaseColor.BLACK))) { HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE }); horario2.Colspan = 2; horario2.Rowspan = 1; table.AddCell(horario2); PdfPCell tiempo = (new PdfPCell(new Paragraph("Fecha de Inscripción: " + textBox7.Text, FontFactory.GetFont("arial", 12, 1, BaseColor.BLACK))) { HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE }); tiempo.Colspan = 4; tiempo.Rowspan = 1; table.AddCell(tiempo); documento.Add(table); documento.Close(); MessageBox.Show("Se creo el pdf con exito"); }