private void Form1_Paint(object sender, PaintEventArgs e) { ++frames; var fx = e.Graphics; using ( var buffer = new Bitmap( ClientSize.Width, ClientSize.Height ) ) { using ( var clr = Graphics.FromImage(buffer) ) clr.Clear( Color.Transparent ); var target = buffer.LockBits( ClientRectangle, System.Drawing.Imaging.ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format32bppArgb ); int y = 0; while ( y < ClientSize.Height ) { #if false string text = "Hello, World!"; Font.RenderLineTo( target, text, new Rectangle(0,y,ClientSize.Width,ClientSize.Height-y), Industry.FX.HorizontalAlignment.Center, VerticalAlignment.Top ); y += Font.MeasureLine(text).Advance.Y; #else Paragraph text = new Paragraph(); text.Add( new TextRun() { Font = RedFont , Text = "He" } ); text.Add( new TextRun() { Font = BlueFont, Text = "llo, W" } ); text.Add( new TextRun() { Font = RedFont , Text = "orld!" } ); var lines = text.ToLines(ClientSize.Width); FX.Font.RenderLinesTo( target, lines, new Rectangle(0,y,ClientSize.Width,int.MaxValue), FX.HorizontalAlignment.Center, VerticalAlignment.Top ); y += FX.Font.MeasureLines(lines).Advance.Y; #endif } DateTime now = DateTime.Now; var span = now-prev; if ( span.TotalSeconds >= 1.0 ) { prev = now; framedisplay = frames; frames = 0; } RedFont.RenderLineTo( target, "FPS: "+framedisplay, ClientRectangle, Industry.FX.HorizontalAlignment.Right, VerticalAlignment.Top ); buffer.UnlockBits(target); fx.DrawImage(buffer,0,0); } Invalidate(); }
public static Text GetActivatedText(Text text) { var activeText = new Text(); foreach(var paragraph in text) { var activeParagraph = new Paragraph(); foreach(var sentence in paragraph) { activeParagraph.Add(GetActivatedSentence(sentence)); } activeText.Add(activeParagraph); } return activeText; }
static void Main() { Document doc = new Document(); doc.Title = "My First Document"; doc.Author = "Nakov"; doc.Add(new Paragraph("I am a paragraph")); doc.Add(new Hyperlink("http://dir.bg")); doc.Add(new Paragraph("I am another paragraph")); doc.Add(new Heading("Heading 1")); Paragraph paragraph = new Paragraph(); paragraph.Add(new TextElement("Default Font", Font.DefaultFont)); paragraph.Add(new TextElement(" ")); paragraph.Add(new TextElement("Second Red", new Font(color: Color.Red))); paragraph.Add(new TextElement(" ")); paragraph.Add(new TextElement("Green Italic", new Font(color: Color.Green, style: FontStyle.Italic))); paragraph.Add(new Paragraph()); paragraph.Add( new TextElement("Consolas Bold Blue Italic", new Font( color: Color.Blue, style: FontStyle.BoldItalic, name: "Consolas"))); doc.Add(paragraph); doc.Add(new Heading("Heading 2<br>", 2)); doc.Add( new Hyperlink("http://softuni.bg") .Add(Image.CreateFromFile("../../logo.png")) .Add(new TextElement("some text")) ); doc.Add(paragraph); var htmlDoc = new HtmlDocument(doc); var writer = new StringWriter(); htmlDoc.Render(writer); Console.WriteLine(writer.ToString()); File.WriteAllText("document.html", writer.ToString()); var txtDoc = new TxtDocument(doc); writer = new StringWriter(); txtDoc.Render(writer); Console.WriteLine(writer.ToString()); File.WriteAllText("document.txt", writer.ToString()); }
public OutputPdfGenerator Create(List <IntelItem> items, string subject) { try { using (var memoryStream = new MemoryStream()) { var pdfWriter = new PdfWriter(memoryStream); var pdfDocument = new PdfDocument(pdfWriter); var document = new Document(pdfDocument, PageSize.LETTER, true); items.Sort(IntelItem.DateTimeCollectedComparer); items.ForEach((i) => { var p = new Paragraph(); p.Add(new Text(!String.IsNullOrEmpty(i.Description) ? i.Description : "").SetBold()); p.Add("\n"); p.Add(new Text(!String.IsNullOrEmpty(i?.DateTimeCollected.ToShortDateString()) ? i.DateTimeCollected.ToShortDateString() : "").SetBold()); p.Add("\n"); p.Add(new Text(!String.IsNullOrEmpty(i.Content) ? i.Content : "")); p.Add("\n"); p.Add(new Text(!String.IsNullOrEmpty(i.Author) ? i.Author : "")); p.Add("\n"); p.Add(new Text(!String.IsNullOrEmpty(i.CovertArea.ToString()) ? i.CovertArea.ToString() : "")); p.Add("\n"); p.Add(new Text(!String.IsNullOrEmpty(i.Url) ? i.Url : "")); p.Add("\n"); p.Add("\n"); document.Add(p); }); document.Close(); _result = memoryStream.ToArray(); } _outName = $"{subject}.pdf"; } catch (Exception e) { _logger.LogError(e.Message); } return(this); }
static void Main(string[] args) { TableStyle tableStyle1 = new TableStyle("TableStyle1"); tableStyle1.Width = new Size(6.3, Unit.Inch); tableStyle1.Alignment = TableAlignment.Left; tableStyle1.LeftMargin = new Size(0, Unit.Inch); ColumnStyle columnStyle1 = new ColumnStyle("ColumnStyle1"); columnStyle1.Width = new Size(1.2, Unit.Inch); ColumnStyle columnStyle2 = new ColumnStyle("ColumnStyle2"); columnStyle2.Width = new Size(1.3, Unit.Inch); CellStyle cellStyle1 = new CellStyle("CellStyle1"); cellStyle1.CellProperties.BackgroundColor = "#CCCCCC"; //gray cellStyle1.CellProperties.Border = new Border(new Size(0.0069, Unit.Inch), BorderStyle.Solid, "#000000"); CellStyle cellStyle2 = new CellStyle("CellStyle2"); cellStyle2.CellProperties.Border = new Border(new Size(0.0069, Unit.Inch), BorderStyle.Solid, "#000000"); TextDocument doc = new TextDocument(); doc.AutomaticStyles.Styles.Add(tableStyle1); doc.AutomaticStyles.Styles.Add(columnStyle1); doc.AutomaticStyles.Styles.Add(columnStyle2); doc.AutomaticStyles.Styles.Add(cellStyle1); doc.AutomaticStyles.Styles.Add(cellStyle2); Column column1 = new Column(); column1.Style = "ColumnStyle1"; Column column2 = new Column(); column2.Style = "ColumnStyle1"; Column column3 = new Column(); column3.Style = "ColumnStyle2"; Column column4 = new Column(); column4.Style = "ColumnStyle2"; Column column5 = new Column(); column5.Style = "ColumnStyle2"; Table table1 = new Table(); table1.Style = "TableStyle1"; table1.Columns.Add(column1); table1.Columns.Add(column2); table1.Columns.Add(column3); table1.Columns.Add(column4); table1.Columns.Add(column5); Cell cell11 = new Cell("A"); cell11.Style = "CellStyle1"; Cell cell12 = new Cell("B"); cell12.Style = "CellStyle1"; Cell cell13 = new Cell("C"); cell13.Style = "CellStyle1"; Cell cell14 = new Cell("D"); cell14.Style = "CellStyle1"; Cell cell15 = new Cell("E"); cell15.Style = "CellStyle1"; Row row1 = new Row(); row1.Cells.Add(cell11); row1.Cells.Add(cell12); row1.Cells.Add(cell13); row1.Cells.Add(cell14); row1.Cells.Add(cell15); Cell cell21 = new Cell("1"); cell21.Style = "CellStyle2"; Cell cell22 = new Cell("2"); cell22.Style = "CellStyle2"; Cell cell23 = new Cell("3"); cell23.Style = "CellStyle2"; Cell cell24 = new Cell("4"); cell24.Style = "CellStyle2"; Cell cell25 = new Cell("5"); cell25.Style = "CellStyle2"; Row row2 = new Row(); row2.Cells.Add(cell21); row2.Cells.Add(cell22); row2.Cells.Add(cell23); row2.Cells.Add(cell24); row2.Cells.Add(cell25); table1.Rows.Add(row1); table1.Rows.Add(row2); table1.Rows.Add(row2); table1.Rows.Add(row2); Paragraph p1 = new Paragraph(); p1.Add("Table with style"); Paragraph p2 = new Paragraph(); doc.Body.Add(p1); doc.Body.Add(p2); doc.Body.Add(table1); doc.Save("c:\\test\\output.odt", true); }
//To export the dataGridView to pdf public void exportgridviewtopdf(DataGridView dgvAccounts, string filename) { ////Report Header BaseFont head = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1250, BaseFont.NOT_EMBEDDED); Paragraph p = new Paragraph(); p.Alignment = Element.ALIGN_CENTER; p.Add(new Chunk("KERICHO COUNTY REFERRAL HOSPITAL")); p.Add(new Chunk("\nP.O BOX 11 -20200 KERICHO")); p.Add(new Chunk("\nDate: " + DateTime.Now.ToShortDateString())); //Line Separation Paragraph pra = new Paragraph(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(1.0F, 100.0F, BaseColor.BLACK, Element.ALIGN_LEFT, 1))); p.Add(new Chunk("\n")); //Table Head Paragraph p2 = new Paragraph(); p2.Alignment = Element.ALIGN_CENTER; p2.Add(new Chunk("Statement of Accounts")); //Table Data BaseFont bf = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1250, BaseFont.EMBEDDED); PdfPTable records = new PdfPTable(dgvAccounts.Columns.Count); records.DefaultCell.Padding = 1; records.WidthPercentage = 100; PdfPCell cells = new PdfPCell(); records.HorizontalAlignment = Element.ALIGN_LEFT; records.DefaultCell.BorderWidth = 1; iTextSharp.text.Font text = new iTextSharp.text.Font(bf, 10, iTextSharp.text.Font.NORMAL); //For header foreach (DataGridViewColumn column in dgvAccounts.Columns) { PdfPCell cell = new PdfPCell(new Phrase(column.HeaderText, text)); cell.BackgroundColor = new iTextSharp.text.BaseColor(240, 240, 240); records.AddCell(cell); } //Add datarow foreach (DataGridViewRow row in dgvAccounts.Rows) { foreach (DataGridViewCell cell in row.Cells) { records.AddCell(new Phrase(cell.Value.ToString(), text)); } } var savefiledialoge = new SaveFileDialog(); savefiledialoge.FileName = filename; savefiledialoge.DefaultExt = ".pdf"; if (savefiledialoge.ShowDialog() == DialogResult.OK) { using (FileStream stream = new FileStream(savefiledialoge.FileName, FileMode.Create)) { Document pdfdoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f); PdfWriter.GetInstance(pdfdoc, stream); pdfdoc.Open(); pdfdoc.Add(p); pdfdoc.Add(pra); pdfdoc.Add(p2); pdfdoc.Add(new Chunk("\n")); pdfdoc.Add(records); pdfdoc.Close(); stream.Close(); } } }
private void bgworker_DoWork(object sender, DoWorkEventArgs e) { pic_loading.Invoke(new Action(() => { pic_loading.Visible = true; btn_submit.Enabled = false; })); String query = "", empid = "", date_from = "", date_to = "", pay_code = "", table = "hr_dtr_sum_files", filename = "", code = "", col = "", val = "", date_in = "", employee_name = "", days_worked = "", absent_total = "", employee_id = ""; Double legal_hol_ot = 0.00, special_hol_ot = 0.00, dayoff_ot_total = 0.00, late_total = 0.00, ut_total = 0.00, ot_total = 0.00; DataTable pay_period = null; query = "SELECT empid,firstname,lastname FROM rssys.hr_employee"; cbo_employee.Invoke(new Action(() => { if (cbo_employee.SelectedIndex != -1) { empid = cbo_employee.SelectedValue.ToString(); query += " WHERE empid='" + empid + "'"; } })); query += " ORDER BY empid ASC"; DataTable employees = db.QueryBySQLCode(query); cbo_payollperiod.Invoke(new Action(() => { pay_code = cbo_payollperiod.SelectedValue.ToString(); })); pay_period = get_date(pay_code); if (pay_period.Rows.Count > 0) { date_from = DateTime.Parse(pay_period.Rows[0]["date_from"].ToString()).ToShortDateString(); date_to = DateTime.Parse(pay_period.Rows[0]["date_to"].ToString()).ToShortDateString(); } filename = RandomString(5) + "_" + DateTime.Now.ToString("yyyy-MM-dd"); filename += ".pdf"; System.IO.FileStream fs = new FileStream(fileloc_dtr + "/ViewController/RPT/TimeKeeping/dtr_summary_pdf/" + filename, FileMode.Create); Document document = new Document(PageSize.LEGAL.Rotate(), 25, 25, 30, 30); PdfWriter.GetInstance(document, fs); document.Open(); BaseFont bf = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); iTextSharp.text.Font font = new iTextSharp.text.Font(bf, 9, iTextSharp.text.Font.NORMAL); Paragraph paragraph = new Paragraph(); paragraph.Alignment = Element.ALIGN_CENTER; paragraph.Font = FontFactory.GetFont("Arial", 12); paragraph.SetLeading(1, 1); paragraph.Add("DAILY TIME RECORD SUMMARY"); Phrase line_break = new Phrase("\n"); document.Add(paragraph); document.Add(line_break); Paragraph paragraph_2 = new Paragraph(); paragraph_2.Alignment = Element.ALIGN_CENTER; paragraph_2.Font = FontFactory.GetFont("Arial", 12); paragraph_2.SetLeading(1, 1); paragraph_2.Add("For the payroll period " + date_from + " to " + date_to); Phrase line_break_2 = new Phrase("\n"); document.Add(paragraph_2); document.Add(line_break_2); PdfPTable t = new PdfPTable(9); float[] widths = new float[] { 10, 10, 10, 10, 10, 10, 10, 10, 10 }; t.WidthPercentage = 100; t.SetWidths(widths); t.AddCell(new PdfPCell(new Phrase(new Chunk("Employee Name", font))) { HorizontalAlignment = Element.ALIGN_LEFT }); t.AddCell(new PdfPCell(new Phrase(new Chunk("Days Worked (# days)", font))) { HorizontalAlignment = Element.ALIGN_CENTER }); t.AddCell(new PdfPCell(new Phrase(new Chunk("Abcences (# days)", font))) { HorizontalAlignment = Element.ALIGN_CENTER }); t.AddCell(new PdfPCell(new Phrase(new Chunk("Total Late (Hrs/Amt.)", font))) { HorizontalAlignment = Element.ALIGN_CENTER }); t.AddCell(new PdfPCell(new Phrase(new Chunk("Total Undertime(Hrs/Amt.)", font))) { HorizontalAlignment = Element.ALIGN_CENTER }); //t.AddCell(new PdfPCell(new Phrase(new Chunk("Total Overtime", font))) { HorizontalAlignment = Element.ALIGN_CENTER }); t.AddCell(new PdfPCell(new Phrase(new Chunk("Reg OT(Hrs/Amt.)", font))) { HorizontalAlignment = Element.ALIGN_CENTER }); t.AddCell(new PdfPCell(new Phrase(new Chunk("Dayoff OT(Hrs/Amt.)", font))) { HorizontalAlignment = Element.ALIGN_CENTER }); t.AddCell(new PdfPCell(new Phrase(new Chunk("Legal Hol. OT(Hrs/Amt.)", font))) { HorizontalAlignment = Element.ALIGN_CENTER }); t.AddCell(new PdfPCell(new Phrase(new Chunk("Special Hol. OT(Hrs/Amt.)", font))) { HorizontalAlignment = Element.ALIGN_CENTER }); for (int r = 0; r < employees.Rows.Count; r++) { legal_hol_ot = 0.00; special_hol_ot = 0.00; employee_id = employees.Rows[r]["empid"].ToString(); employee_name = employees.Rows[r]["firstname"].ToString() + ", " + employees.Rows[r]["lastname"].ToString(); days_worked = compute_daysworked(employee_id, date_from, date_to); absent_total = compute_absent(employee_id, date_from, date_to, days_worked); late_total = compute_late(employee_id, date_from, date_to); ut_total = compute_undertime(employee_id, date_from, date_to); ot_total = compute_overtime(employee_id, date_from, date_to); dayoff_ot_total = get_dayoff_ot_total(employee_id, pay_code); legal_hol_ot = get_legal_hol_ot(employee_id, pay_code); special_hol_ot = get_special_hol_ot(employee_id, pay_code); t.AddCell(new PdfPCell(new Phrase(new Chunk(employee_name, font))) { HorizontalAlignment = Element.ALIGN_LEFT }); t.AddCell(new PdfPCell(new Phrase(new Chunk(days_worked, font))) { HorizontalAlignment = Element.ALIGN_CENTER }); t.AddCell(new PdfPCell(new Phrase(new Chunk(absent_total, font))) { HorizontalAlignment = Element.ALIGN_CENTER }); if (late_total > 0) { t.AddCell(new PdfPCell(new Phrase(new Chunk(late_total.ToString("0.00"), font))) { HorizontalAlignment = Element.ALIGN_CENTER }); } else { t.AddCell(new PdfPCell(new Phrase(new Chunk("", font))) { HorizontalAlignment = Element.ALIGN_CENTER }); } if (ut_total > 0) { t.AddCell(new PdfPCell(new Phrase(new Chunk(ut_total.ToString("0.00"), font))) { HorizontalAlignment = Element.ALIGN_CENTER }); } else { t.AddCell(new PdfPCell(new Phrase(new Chunk("", font))) { HorizontalAlignment = Element.ALIGN_CENTER }); } if (ot_total > 0) { t.AddCell(new PdfPCell(new Phrase(new Chunk(ot_total.ToString("0.00"), font))) { HorizontalAlignment = Element.ALIGN_CENTER }); } else { t.AddCell(new PdfPCell(new Phrase(new Chunk("", font))) { HorizontalAlignment = Element.ALIGN_CENTER }); } //t.AddCell(new PdfPCell(new Phrase(new Chunk("0", font))) { HorizontalAlignment = Element.ALIGN_CENTER }); if (dayoff_ot_total > 0) { t.AddCell(new PdfPCell(new Phrase(new Chunk(dayoff_ot_total.ToString("0.00"), font))) { HorizontalAlignment = Element.ALIGN_CENTER }); } else { t.AddCell(new PdfPCell(new Phrase(new Chunk("", font))) { HorizontalAlignment = Element.ALIGN_CENTER }); } if (legal_hol_ot > 0) { t.AddCell(new PdfPCell(new Phrase(new Chunk(legal_hol_ot.ToString("0.00"), font))) { HorizontalAlignment = Element.ALIGN_CENTER }); } else { t.AddCell(new PdfPCell(new Phrase(new Chunk("", font))) { HorizontalAlignment = Element.ALIGN_CENTER }); } if (special_hol_ot > 0) { t.AddCell(new PdfPCell(new Phrase(new Chunk(special_hol_ot.ToString("0.00"), font))) { HorizontalAlignment = Element.ALIGN_CENTER }); } else { t.AddCell(new PdfPCell(new Phrase(new Chunk("", font))) { HorizontalAlignment = Element.ALIGN_CENTER }); } } document.Add(t); document.Close(); code = db.get_pk("dtr_sum_id"); col = "dtr_sum_id,filename,date_created"; val = "'" + code + "','" + filename + "','" + DateTime.Now.ToShortDateString() + "'"; if (db.InsertOnTable(table, col, val)) { db.set_pkm99("dtr_sum_id", db.get_nextincrementlimitchar(code, 8)); //changes from 'hr_empid' MessageBox.Show("New DTR Summary created."); } else { MessageBox.Show("Failed on saving."); } pic_loading.Invoke(new Action(() => { pic_loading.Visible = false; btn_submit.Enabled = true; })); display_list(); }
public MemoryStream GeneratePdfTemplate(GarmentCoverLetterViewModel viewModel, GarmentPackingListViewModel pl, Buyer buyer, int timeoffset) { const int MARGIN = 20; Font header_font_bold = FontFactory.GetFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 12); 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, 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); Font small_font = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 5); //Font body_bold_font = FontFactory.GetFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 8); Document document = new Document(PageSize.A4, MARGIN, MARGIN, 140, MARGIN); MemoryStream stream = new MemoryStream(); PdfWriter writer = PdfWriter.GetInstance(document, stream); writer.PageEvent = new GarmentCoverLetterPdfTemplatePageEvent(); document.Open(); PdfPTable tableTitle = new PdfPTable(1); tableTitle.WidthPercentage = 100; tableTitle.SetWidths(new float[] { 6f }); PdfPCell cellTitle = new PdfPCell() { MinimumHeight = 15, Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_CENTER }; //cellTitle.Phrase = new Phrase("Ref No. : FM-00-SP-24-008", header_font); //tableTitle.AddCell(cellTitle); cellTitle.Phrase = new Phrase("SURAT PENGANTAR", header_font_bold); tableTitle.AddCell(cellTitle); cellTitle.Phrase = new Phrase(viewModel.invoiceNo, header_font_bold); tableTitle.AddCell(cellTitle); tableTitle.SpacingAfter = 10; document.Add(tableTitle); #region header PdfPTable tableHeader = new PdfPTable(3); tableHeader.WidthPercentage = 100; tableHeader.SetWidths(new float[] { 3f, 1.5f, 2f }); PdfPCell cellHeaderLeft = new PdfPCell() { MinimumHeight = 15, Border = Rectangle.BOTTOM_BORDER | Rectangle.LEFT_BORDER | Rectangle.RIGHT_BORDER | Rectangle.TOP_BORDER, HorizontalAlignment = Element.ALIGN_LEFT }; cellHeaderLeft.Phrase = new Phrase("Kepada Yth.\n\n" + //$"{viewModel.emkl.Name} \n\n" + $"{viewModel.destination} \n" + $"{viewModel.address} \n" + $"PIC : {viewModel.pic} \n\n" + $"Forwarder : {viewModel.forwarder.name} \n\n" + $"ATTN : {viewModel.attn} \n" + $"PHONE : {viewModel.phone}", normal_font); cellHeaderLeft.Rowspan = 7; tableHeader.AddCell(cellHeaderLeft); cellHeaderLeft.Phrase = new Phrase("Tanggal", normal_font); cellHeaderLeft.Rowspan = 1; tableHeader.AddCell(cellHeaderLeft); cellHeaderLeft.Phrase = new Phrase(viewModel.date.GetValueOrDefault().ToOffset(new TimeSpan(timeoffset, 0, 0)).ToString("dd MMMM yyyy", new System.Globalization.CultureInfo("en-EN")), normal_font); tableHeader.AddCell(cellHeaderLeft); cellHeaderLeft.Phrase = new Phrase("Order ", normal_font); tableHeader.AddCell(cellHeaderLeft); cellHeaderLeft.Phrase = new Phrase(viewModel.order.Name, normal_font); tableHeader.AddCell(cellHeaderLeft); cellHeaderLeft.Phrase = new Phrase("Jumlah Pcs ", normal_font); tableHeader.AddCell(cellHeaderLeft); cellHeaderLeft.Phrase = new Phrase(viewModel.pcsQuantity == 0 ? "-" : $"{ string.Format("{0:n0}", viewModel.pcsQuantity)} PCS", normal_font); tableHeader.AddCell(cellHeaderLeft); cellHeaderLeft.Phrase = new Phrase("Jumlah Sets", normal_font); tableHeader.AddCell(cellHeaderLeft); cellHeaderLeft.Phrase = new Phrase(viewModel.setsQuantity == 0 ? "-" : $"{ string.Format("{0:n0}", viewModel.setsQuantity)} SETS", normal_font); tableHeader.AddCell(cellHeaderLeft); cellHeaderLeft.Phrase = new Phrase("Jumlah Packs", normal_font); tableHeader.AddCell(cellHeaderLeft); cellHeaderLeft.Phrase = new Phrase(viewModel.packQuantity == 0 ? "-" : $"{ string.Format("{0:n0}", viewModel.packQuantity)} PACKS", normal_font); tableHeader.AddCell(cellHeaderLeft); cellHeaderLeft.Phrase = new Phrase("Jumlah Collie", normal_font); tableHeader.AddCell(cellHeaderLeft); cellHeaderLeft.Phrase = new Phrase($"{ string.Format("{0:n0}", viewModel.cartoonQuantity)} COLLIE", normal_font); tableHeader.AddCell(cellHeaderLeft); cellHeaderLeft.Phrase = new Phrase("Invoice No.", normal_font); tableHeader.AddCell(cellHeaderLeft); cellHeaderLeft.Phrase = new Phrase(viewModel.invoiceNo, normal_font); tableHeader.AddCell(cellHeaderLeft); tableHeader.SpacingAfter = 10; document.Add(tableHeader); #endregion document.Add(new Paragraph("Dengan hormat,", normal_font)); document.Add(new Paragraph("\n", normal_font)); document.Add(new Paragraph(" Bersama ini kami kirimkan kepada Bapak sejumlah barang dengan", normal_font)); document.Add(new Paragraph("\n", normal_font)); document.Add(new Paragraph("\n", normal_font)); #region detail PdfPTable tableDetail = new PdfPTable(7); tableDetail.WidthPercentage = 100; tableDetail.SetWidths(new float[] { 1f, 1f, 1f, 1f, 1f, 1f, 1f }); PdfPCell cellDetail = new PdfPCell() { MinimumHeight = 15, Border = Rectangle.BOTTOM_BORDER | Rectangle.LEFT_BORDER | Rectangle.RIGHT_BORDER | Rectangle.TOP_BORDER, HorizontalAlignment = Element.ALIGN_LEFT }; double cbmtotal = 0; if (pl.Measurements.Count > 0) { foreach (var m in pl.Measurements) { double cbm = (m.Length * m.Width * m.Height * m.CartonsQuantity) / 1000000; cbmtotal += cbm; } } cellDetail.Phrase = new Phrase("Truck", normal_font); tableDetail.AddCell(cellDetail); cellDetail.Phrase = new Phrase("Nomor Polisi", normal_font); tableDetail.AddCell(cellDetail); cellDetail.Phrase = new Phrase("Pengemudi", normal_font); tableDetail.AddCell(cellDetail); cellDetail.Phrase = new Phrase("No Kontainer", normal_font); tableDetail.AddCell(cellDetail); cellDetail.Phrase = new Phrase("Seal Pelayaran", normal_font); tableDetail.AddCell(cellDetail); cellDetail.Phrase = new Phrase("Seal Dan Liris", normal_font); tableDetail.AddCell(cellDetail); cellDetail.Phrase = new Phrase("Jumlah Muatan", normal_font); tableDetail.AddCell(cellDetail); Paragraph Truck = new Paragraph($"EMKL : {viewModel.emkl.Name} \n\n" + $"Truk : {viewModel.truck}", normal_font); cellDetail.Phrase = Truck; cellDetail.VerticalAlignment = Element.ALIGN_TOP; tableDetail.AddCell(cellDetail); cellDetail.Phrase = new Phrase(viewModel.plateNumber, normal_font); tableDetail.AddCell(cellDetail); cellDetail.Phrase = new Phrase(viewModel.driver, normal_font); tableDetail.AddCell(cellDetail); cellDetail.Phrase = new Phrase(viewModel.containerNo, normal_font); tableDetail.AddCell(cellDetail); cellDetail.Phrase = new Phrase(viewModel.shippingSeal, normal_font); tableDetail.AddCell(cellDetail); cellDetail.Phrase = new Phrase(viewModel.dlSeal, normal_font); tableDetail.AddCell(cellDetail); Paragraph weight = new Paragraph($"GW : {string.Format("{0:n2}", pl.GrossWeight)} KGS \n\n" + $"NW : {string.Format("{0:n2}", pl.NettWeight)} KGS \n\n" + $"Volume : {string.Format("{0:n2}", Math.Round(cbmtotal, 2))} m", normal_font); Chunk chunk = new Chunk("3", small_font); chunk.SetTextRise(2); Paragraph m2 = new Paragraph(chunk); m2.Alignment = Element.ALIGN_TOP; weight.Add(m2); cellDetail.Phrase = weight; cellDetail.VerticalAlignment = Element.ALIGN_TOP; tableDetail.AddCell(cellDetail); tableDetail.SpacingAfter = 10; document.Add(tableDetail); #endregion #region marks PdfPTable tableMark = new PdfPTable(4); tableMark.WidthPercentage = 100; tableMark.SetWidths(new float[] { 1f, 3f, 1f, 3f }); PdfPCell cellMark = new PdfPCell() { MinimumHeight = 15, Border = Rectangle.BOTTOM_BORDER, HorizontalAlignment = Element.ALIGN_LEFT }; cellMark.Phrase = new Phrase("Shippig Mark :", normal_font); cellMark.Rowspan = 2; tableMark.AddCell(cellMark); cellMark.Phrase = new Phrase(pl.ShippingMark, normal_font); tableMark.AddCell(cellMark); string sealType = ""; string seal = ""; if (!string.IsNullOrEmpty(viewModel.shippingSeal)) { sealType += "Seal Pelayaran \n"; seal += ": " + viewModel.shippingSeal + "\n"; } if (!string.IsNullOrEmpty(viewModel.dlSeal)) { sealType += "Seal DL \n"; seal += ": " + viewModel.dlSeal + "\n"; } if (!string.IsNullOrEmpty(viewModel.emklSeal)) { sealType += "Seal EMKL \n"; seal += ": " + viewModel.emklSeal + "\n"; } cellMark.Phrase = new Phrase(sealType, normal_font); cellMark.Rowspan = 1; cellMark.Border = Rectangle.NO_BORDER; cellMark.HorizontalAlignment = Element.ALIGN_LEFT; tableMark.AddCell(cellMark); cellMark.Phrase = new Phrase(seal, normal_font); cellMark.Rowspan = 1; cellMark.Border = Rectangle.NO_BORDER; cellMark.HorizontalAlignment = Element.ALIGN_LEFT; tableMark.AddCell(cellMark); //cellMark.Phrase = new Phrase("SEND TO :", normal_font); //cellMark.Colspan = 1; //cellMark.HorizontalAlignment = Element.ALIGN_RIGHT; //cellMark.Border = Rectangle.BOTTOM_BORDER; //tableMark.AddCell(cellMark); //cellMark.Phrase = new Phrase($"{buyer.Name} \n" + // $"{buyer.Address} \n", normal_font); //cellMark.HorizontalAlignment = Element.ALIGN_LEFT; //tableMark.AddCell(cellMark); //tableMark.SpacingAfter = 15; //document.Add(tableMark); #endregion document.Add(new Paragraph("Demikian harap diterima dengan baik dan terima kasih.", normal_font)); document.Add(new Paragraph("\n", normal_font)); document.Add(new Paragraph("\n", normal_font)); #region sign PdfPTable tableSign = new PdfPTable(5); tableSign.WidthPercentage = 100; tableSign.SetWidths(new float[] { 1f, 1f, 1f, 1f, 1f }); PdfPCell cellSign = new PdfPCell() { MinimumHeight = 15, Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_CENTER }; cellSign.Phrase = new Phrase("Pengemudi Truck, \n\n\n\n\n\n", normal_font); cellSign.Colspan = 1; tableSign.AddCell(cellSign); cellSign.Phrase = new Phrase("Mengetahui, \n\n\n\n\n\n", normal_font); cellSign.Colspan = 2; tableSign.AddCell(cellSign); cellSign.Phrase = new Phrase(" Hormat Kami, \n\n\n\n\n\n", normal_font); cellSign.Colspan = 1; tableSign.AddCell(cellSign); cellSign.Phrase = new Phrase(" \n\n\n\n\n\n", normal_font); cellSign.Colspan = 1; tableSign.AddCell(cellSign); cellSign.Phrase = new Phrase("__________________", normal_font); tableSign.AddCell(cellSign); cellSign.Phrase = new Phrase("__________________", normal_font); tableSign.AddCell(cellSign); cellSign.Phrase = new Phrase("__________________", normal_font); tableSign.AddCell(cellSign); cellSign.Phrase = new Phrase("__________________", normal_font); tableSign.AddCell(cellSign); cellSign.Phrase = new Phrase("( " + viewModel.shippingStaff.name + " )", normal_font); tableSign.AddCell(cellSign); cellSign.Phrase = new Phrase("", normal_font); tableSign.AddCell(cellSign); cellSign.Phrase = new Phrase("Pembukuan DL", normal_font); tableSign.AddCell(cellSign); cellSign.Phrase = new Phrase("Sat Pam", normal_font); tableSign.AddCell(cellSign); cellSign.Phrase = new Phrase("Konfeksi " + $"{viewModel.unit}", normal_font); tableSign.AddCell(cellSign); cellSign.Phrase = new Phrase("Shipping Staff", normal_font); tableSign.AddCell(cellSign); cellSign.Phrase = new Phrase("\n\n\n\n\n\n\n\n\n\n\n\n\n", normal_font); tableSign.AddCell(cellSign); cellSign.Phrase = new Phrase("\n\n\n\n\n\n\n\n\n\n\n\n\n", normal_font); tableSign.AddCell(cellSign); cellSign.Phrase = new Phrase("\n\n\n\n\n\n\n\n\n\n\n\n\n", normal_font); tableSign.AddCell(cellSign); cellSign.Phrase = new Phrase("\n\n\n\n\n\n\n\n\n\n\n\n\n", normal_font); tableSign.AddCell(cellSign); cellSign.Phrase = new Phrase("\n\n\n\n\n\n\n\n\n\n\n\n\n", normal_font); tableSign.AddCell(cellSign); cellSign.Phrase = new Phrase("JAM MASUK : ______", normal_font); tableSign.AddCell(cellSign); cellSign.Phrase = new Phrase(" ", normal_font); tableSign.AddCell(cellSign); cellSign.Phrase = new Phrase(" ", normal_font); tableSign.AddCell(cellSign); cellSign.Phrase = new Phrase(" ", normal_font); tableSign.AddCell(cellSign); cellSign.Phrase = new Phrase(" ", normal_font); tableSign.AddCell(cellSign); cellSign.Phrase = new Phrase("JAM KELUAR : ______", normal_font); tableSign.AddCell(cellSign); cellSign.Phrase = new Phrase(" ", normal_font); tableSign.AddCell(cellSign); cellSign.Phrase = new Phrase(" ", normal_font); tableSign.AddCell(cellSign); cellSign.Phrase = new Phrase(" ", normal_font); tableSign.AddCell(cellSign); cellSign.Phrase = new Phrase(" ", normal_font); tableSign.AddCell(cellSign); cellSign.Phrase = new Phrase("\n\n", normal_font); tableSign.AddCell(cellSign); cellSign.Phrase = new Phrase("\n\n", normal_font); tableSign.AddCell(cellSign); cellSign.Phrase = new Phrase("\n\n", normal_font); tableSign.AddCell(cellSign); cellSign.Phrase = new Phrase("\n\n", normal_font); tableSign.AddCell(cellSign); cellSign.Phrase = new Phrase("\n\n", normal_font); tableSign.AddCell(cellSign); cellSign.Phrase = new Phrase("CATATAN : \n" + "1. Mohon bisa dikirim kembali Pengantar ini apabila barang sudah diterima \n" + "2. ....................................................", normal_font); cellSign.Colspan = 3; cellSign.HorizontalAlignment = Element.ALIGN_LEFT; tableSign.AddCell(cellSign); cellSign.Phrase = new Phrase("Diterima, \n\n\n\n\n\n", normal_font); cellSign.Rowspan = 1; cellSign.HorizontalAlignment = Element.ALIGN_CENTER; tableSign.AddCell(cellSign); cellSign.Phrase = new Phrase("", normal_font); cellSign.Colspan = 3; cellSign.HorizontalAlignment = Element.ALIGN_LEFT; tableSign.AddCell(cellSign); cellSign.Phrase = new Phrase(" (__________________)", normal_font); cellSign.Rowspan = 1; tableSign.AddCell(cellSign); cellSign.Phrase = new Phrase(" ", normal_font); cellSign.Colspan = 3; cellSign.HorizontalAlignment = Element.ALIGN_LEFT; tableSign.AddCell(cellSign); cellSign.Phrase = new Phrase(" JAM DITERIMA : ______", normal_font); cellSign.Rowspan = 1; tableSign.AddCell(cellSign); document.Add(tableSign); #endregion document.Close(); byte[] byteInfo = stream.ToArray(); stream.Write(byteInfo, 0, byteInfo.Length); stream.Position = 0; return(stream); }
public FileStreamResult printProjectForm(string PRJID) { var preBidDetails = HomeDal.getPreBidFormByProject(PRJID); // Set up the document and the MS to write it to and create the PDF writer instance MemoryStream ms = new MemoryStream(); Document document = new Document(PageSize.A4); PdfWriter writer = PdfWriter.GetInstance(document, ms); // Open the PDF document document.Open(); // Set up fonts used in the document var LightBlue = new BaseColor(14, 45, 76); var grey = new BaseColor(119, 119, 119); iTextSharp.text.Font font_heading_1 = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 17, LightBlue); iTextSharp.text.Font font_body = FontFactory.GetFont(FontFactory.HELVETICA, 12, LightBlue); iTextSharp.text.Font font_body_bold = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 12, LightBlue); iTextSharp.text.Font spanBold = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 12, grey); iTextSharp.text.Font spanNormal = FontFactory.GetFont(FontFactory.HELVETICA, 11, grey); preBidDetails.JobNumber = (string.IsNullOrWhiteSpace(preBidDetails.JobNumber) ? BusinessConstants.NA : preBidDetails.JobNumber); // Create the heading paragraph with the headig font Paragraph header; header = new Paragraph("Pre-Bid [" + Convert.ToString(Session["CommID"]) + (preBidDetails.PRJID) + "] Roll-Up", font_heading_1); iTextSharp.text.pdf.draw.VerticalPositionMark seperator = new iTextSharp.text.pdf.draw.LineSeparator(); seperator.Offset = -4f; header.Add(seperator); document.Add(header); var HeaderTable = new PdfPTable(4); HeaderTable.HorizontalAlignment = 0; HeaderTable.SpacingBefore = 5; HeaderTable.SpacingAfter = 5; HeaderTable.DefaultCell.Border = 0; HeaderTable.SetWidths(new int[] { 4, 7, 3, 4 }); HeaderTable.AddCell(new Phrase("Form Type:", spanBold)); HeaderTable.AddCell(new Phrase(preBidDetails.FormType, spanNormal)); HeaderTable.AddCell(new Phrase()); HeaderTable.AddCell(new Phrase()); HeaderTable.AddCell(new Phrase("JobNumber:", spanBold)); HeaderTable.AddCell(new Phrase(preBidDetails.JobNumber, spanNormal)); HeaderTable.AddCell(new Phrase("Job Name:", spanBold)); HeaderTable.AddCell(new Phrase(preBidDetails.JobName, spanNormal)); HeaderTable.AddCell(new Phrase("Sales Person:", spanBold)); HeaderTable.AddCell(new Phrase(Convert.ToString(preBidDetails.SalesPerson), spanNormal)); HeaderTable.AddCell(new Phrase("Company:", spanBold)); HeaderTable.AddCell(new Phrase(preBidDetails.Company, spanNormal)); HeaderTable.AddCell(new Phrase("Rate Type:", spanBold)); HeaderTable.AddCell(new Phrase(preBidDetails.RateType, spanNormal)); HeaderTable.AddCell(new Phrase()); HeaderTable.AddCell(new Phrase()); HeaderTable.TotalWidth = 100; document.Add(HeaderTable); var SectionTable = new PdfPTable(3); SectionTable.HorizontalAlignment = 0; SectionTable.SpacingBefore = 5; SectionTable.SpacingAfter = 5; SectionTable.DefaultCell.Border = 0; SectionTable.SetWidths(new int[] { 7, 4, 4 }); SectionTable.AddCell(getLabelValue("Material Cost:", font_body)); SectionTable.AddCell(getDecimalValue(preBidDetails.Material, spanNormal)); SectionTable.AddCell(getDecimalValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue("Material Handling Charge:", font_body)); SectionTable.AddCell(getDecimalValue(preBidDetails.MaterialHandling, spanNormal)); SectionTable.AddCell(getDecimalValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue("Concrete:", font_body)); SectionTable.AddCell(getDecimalValue(preBidDetails.Concrete, spanNormal)); SectionTable.AddCell(getDecimalValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue("Material Total:", font_body)); SectionTable.AddCell(getDecimalValue(" ", spanNormal)); SectionTable.AddCell(getDecimalValue(preBidDetails.MaterialTotal, font_body_bold)); SectionTable.AddCell(getLabelValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue("Onsite Labor:", font_body)); SectionTable.AddCell(getDecimalValue(preBidDetails.OnsiteLabor, spanNormal)); SectionTable.AddCell(getDecimalValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue("Load Labor:", font_body)); SectionTable.AddCell(getDecimalValue(preBidDetails.LoadLabor, spanNormal)); SectionTable.AddCell(getDecimalValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue("Drive Labor:", font_body)); SectionTable.AddCell(getDecimalValue(preBidDetails.DriveLabor, spanNormal)); SectionTable.AddCell(getDecimalValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue("Supervisor:", font_body)); SectionTable.AddCell(getDecimalValue(preBidDetails.Supervisor, spanNormal)); SectionTable.AddCell(getDecimalValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue("Labor Reserve:", font_body)); SectionTable.AddCell(getDecimalValue(preBidDetails.LaborReserve, spanNormal)); SectionTable.AddCell(getDecimalValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue("Labor Total:", font_body)); SectionTable.AddCell(getDecimalValue(" ", spanNormal)); SectionTable.AddCell(getDecimalValue(preBidDetails.LaborTotal, font_body_bold)); SectionTable.AddCell(getLabelValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue("Other Charges:", font_body)); SectionTable.AddCell(getDecimalValue(preBidDetails.OtherCharges, spanNormal)); SectionTable.AddCell(getDecimalValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue("Other Charges Markup:", font_body)); SectionTable.AddCell(getDecimalValue(preBidDetails.OtherChargesMarkup, spanNormal)); SectionTable.AddCell(getDecimalValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue("Other Charges Total:", font_body)); SectionTable.AddCell(getDecimalValue(" ", spanNormal)); SectionTable.AddCell(getDecimalValue(preBidDetails.OtherChargesTotal, font_body_bold)); SectionTable.AddCell(getLabelValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue("Equipment Cost:", font_body)); SectionTable.AddCell(getDecimalValue(" ", spanNormal)); SectionTable.AddCell(getDecimalValue(preBidDetails.EquipmentCost, font_body_bold)); SectionTable.AddCell(getLabelValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue("Benefits:", font_body)); SectionTable.AddCell(getDecimalValue(preBidDetails.Benefits, spanNormal)); SectionTable.AddCell(getDecimalValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue("Retirement:", font_body)); SectionTable.AddCell(getDecimalValue(preBidDetails.Retirement, spanNormal)); SectionTable.AddCell(getDecimalValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue("Payroll Tax:", font_body)); SectionTable.AddCell(getDecimalValue(preBidDetails.PayrollTax, spanNormal)); SectionTable.AddCell(getDecimalValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue("Workers Comp:", font_body)); SectionTable.AddCell(getDecimalValue(preBidDetails.WorkersComp, spanNormal)); SectionTable.AddCell(getDecimalValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue("Indirect Total:", font_body)); SectionTable.AddCell(getDecimalValue(" ", spanNormal)); SectionTable.AddCell(getDecimalValue(preBidDetails.IndirectTotal, font_body_bold)); SectionTable.AddCell(getLabelValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue("Job Cost:", font_body)); SectionTable.AddCell(getDecimalValue(preBidDetails.JobCost, spanNormal)); SectionTable.AddCell(getDecimalValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue("Job Markup:", font_body)); SectionTable.AddCell(getDecimalValue(" ", spanNormal)); SectionTable.AddCell(getDecimalValue(preBidDetails.JobMarkUpTotal, font_body_bold)); SectionTable.AddCell(getLabelValue("Suggested Sold For:", font_body)); SectionTable.AddCell(getDecimalValue(" ", spanNormal)); SectionTable.AddCell(getDecimalValue(preBidDetails.SuggestdSoldFor, font_body_bold)); SectionTable.AddCell(getLabelValue("Pre-Tax Sold For:", font_body)); SectionTable.AddCell(getDecimalValue(" ", spanNormal)); SectionTable.AddCell(getDecimalValue(preBidDetails.PreTaxSoldFor, font_body_bold)); SectionTable.AddCell(getLabelValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue("Sales Tax Total:", font_body)); SectionTable.AddCell(getDecimalValue(" ", spanNormal)); SectionTable.AddCell(getDecimalValue(preBidDetails.SalesTaxTotal, font_body_bold)); SectionTable.AddCell(getLabelValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue("Days On Site:", font_body)); SectionTable.AddCell(getDecimalValue(preBidDetails.DaysOnsite, spanNormal, hasBorder: false, plainText: true)); SectionTable.AddCell(getLabelValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue("Crew Labor Budget:", font_body)); SectionTable.AddCell(getDecimalValue(preBidDetails.CrewLaborBudget, spanNormal, hasBorder: false)); SectionTable.AddCell(getLabelValue(" ", spanNormal)); document.Add(SectionTable); document.Close(); byte[] file = ms.ToArray(); MemoryStream output = new MemoryStream(); output.Write(file, 0, file.Length); output.Position = 0; HttpContext.Response.AddHeader("content-disposition", "inline; filename=PreBid_RollUp_" + preBidDetails.PRJID + ".pdf"); return(File(output, "application/pdf")); }
private void btnLeftPrint_Click(object sender, EventArgs e) { distanceInMm = Math.Round(Distance(golCircle, gorCircle) * mmtoPixelRatio, 2, MidpointRounding.ToEven); Console.WriteLine("distance in mm:" + distanceInMm); distanceInMmR = Math.Round(Distance(golCircleR, gorCircleR) * mmtoPixelRatioR, 2, MidpointRounding.ToEven); Console.WriteLine("distance in mm:" + distanceInMmR); msg f2 = new msg(); f2.ShowDialog();//this way the form1 will hold untill the form 2(msg form ) is closed string savePdfFilePath = ""; SaveFileDialog sf = new SaveFileDialog(); sf.InitialDirectory = @"C:\"; sf.Title = "Save Pdf in"; sf.Filter = "Pdf files (*.pdf)|*.pdf|All files (*.*)|*.*"; if (sf.ShowDialog() == DialogResult.OK) { savePdfFilePath = System.IO.Path.GetFullPath(sf.FileName); } PdfWriter writer = new PdfWriter(savePdfFilePath); PdfDocument pdf = new PdfDocument(writer); float a4Width = PageSize.A4.GetWidth(); float a4Height = PageSize.A4.GetHeight(); PageSize pagesize = new PageSize(a4Width, a4Height); pdf.SetDefaultPageSize(pagesize); Document document = new Document(pdf); Pen p = new Pen(Color.Red); SolidBrush b = new SolidBrush(Color.Red); //Bitmap bmap = new Bitmap(picBoxLeft.Width, picBoxLeft.Height); Bitmap bmap = new Bitmap(picBoxLeft.Image, picBoxLeft.Width, picBoxLeft.Height); Bitmap bmapRight = new Bitmap(picBoxRight.Image, picBoxRight.Width, picBoxRight.Height); bmap.MakeTransparent(); bmapRight.MakeTransparent(); Graphics g = Graphics.FromImage(bmap); Graphics gr = Graphics.FromImage(bmapRight); foreach (Circle item in circleArray) { if (item != null) { g.FillEllipse(b, item._location.X, item._location.Y, item._radius, item._radius); g.DrawString(item._text, new Font(FontFamily.GenericSansSerif, 16, FontStyle.Bold), b, new Point(item._location.X, item._location.Y + item._radius - 70)); //g.Dispose(); } } foreach (Circle item in circleArrayR) { if (item != null) { gr.FillEllipse(b, item._location.X, item._location.Y, item._radius, item._radius); gr.DrawString(item._text, new Font(FontFamily.GenericSansSerif, 16, FontStyle.Bold), b, new Point(item._location.X, item._location.Y + item._radius - 70)); //g.Dispose(); } } MemoryStream ms = new MemoryStream(); MemoryStream msR = new MemoryStream(); bmap.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); bmapRight.Save(msR, System.Drawing.Imaging.ImageFormat.Jpeg); byte[] buff = ms.GetBuffer(); byte[] buffR = msR.GetBuffer(); Paragraph header = new Paragraph("Created From Facial Mark App") .SetTextAlignment(TextAlignment.CENTER) .SetFontSize(20).SetMarginBottom(5); PdfImage img = new PdfImage(iText.IO.Image.ImageDataFactory .Create(buff)).SetTextAlignment(TextAlignment.LEFT); PdfImage imgR = new PdfImage(iText.IO.Image.ImageDataFactory .Create(buffR)).SetTextAlignment(TextAlignment.RIGHT); Table table = new Table(1).SetTextAlignment(TextAlignment.CENTER); Paragraph p1 = new Paragraph(); img.Scale(0.3f, 0.3f); imgR.Scale(0.3f, 0.3f); p1.Add(img); p1.Add(imgR); table.AddCell(p1); // Line separator LineSeparator ls = new LineSeparator(new SolidLine()).SetMarginBottom(10);; Paragraph subheader = new Paragraph("Answers") .SetTextAlignment(TextAlignment.LEFT) .SetFontSize(15).SetMarginBottom(10); Paragraph answerAssym = new Paragraph("Degree of asymmetry:-" + Form1.answerAssym) .SetTextAlignment(TextAlignment.LEFT) .SetFontSize(10); Paragraph answerSupport = new Paragraph("Degree of undereye support :-" + Form1.answerSupport) .SetTextAlignment(TextAlignment.LEFT) .SetFontSize(10); //"Distance(Side)" + Math.Round(distanceInMm / 10,2,MidpointRounding.ToEven) + "cm" + " Paragraph distancePara = new Paragraph("Distance(Frontal)" + Math.Round(distanceInMmR / 10, 2, MidpointRounding.ToEven) + "cm") .SetTextAlignment(TextAlignment.LEFT) .SetFontSize(10); Paragraph anglePara = new Paragraph("The angle created by the line from “Tr to Go” and “Go to Gn’”") .SetTextAlignment(TextAlignment.LEFT) .SetFontSize(12).SetBold().SetMarginBottom(15); if (angleLeft <= 0.0) { double answer = calculateAngle(circleArray); answer = Math.Round(answer, 2, MidpointRounding.ToEven); angleLeft = answer; } if (angleRight <= 0.0) { double answer = calculateAngle(circleArrayR); answer = Math.Round(answer, 2, MidpointRounding.ToEven); angleRight = answer; } Paragraph angleParaLeft = new Paragraph("Angle(Side):" + angleLeft + "\u00B0") .SetTextAlignment(TextAlignment.LEFT) .SetFontSize(10).SetMarginBottom(10); //Paragraph angleParaRight = new Paragraph("Angle(Front):" + angleRight + "\u00B0") // .SetTextAlignment(TextAlignment.LEFT) // .SetFontSize(10).SetMarginBottom(10); document.Add(header); document.Add(ls); document.Add(table); document.Add(subheader); document.Add(answerAssym); document.Add(answerSupport); document.Add(distancePara); document.Add(anglePara); document.Add(angleParaLeft); //document.Add(angleParaRight); //document.Add(img); //document.Add(imgR); document.Close(); MessageBox.Show("Successfully Saved Pdf"); }
/// <summary> /// PDF作成 /// </summary> /// <param name="dayStr">作成指定日時</param> /// <param name="classificationStr">分類文字列</param> /// <param name="periodTypeStr">期間指定文字列</param> /// <param name="originTable">表のオリジナルデータ</param> public void Create(string dayStr, string classificationStr, string periodTypeStr, DataTable originTable, string imgDataStr) { try { var doc = new Document(SizeRect); var stream = new MemoryStream(); //ファイルの出力先を設定 var pw = PdfWriter.GetInstance(doc, stream); //ドキュメントを開く doc.Open(); // A4 595x842 pt = 210x297 Paragraph prgTitle = new Paragraph(); Font titleFont = new Font(PdfFont, 24, 1, BaseColor.BLACK); prgTitle.Alignment = Element.ALIGN_LEFT; prgTitle.Add(new Chunk(dayStr + "の統計確認データ", titleFont)); doc.Add(prgTitle); Paragraph p = new Paragraph(new Chunk(new LineSeparator(0.0f, 100.0f, BaseColor.BLACK, Element.ALIGN_LEFT, 0.0f))); doc.Add(p); Paragraph prgCreateDate = new Paragraph(); Font createDateFont = new Font(PdfFont, 11, 1, BaseColor.BLACK); prgCreateDate.Alignment = Element.ALIGN_LEFT; prgCreateDate.Add(new Chunk("作成日時: " + DateTime.Now.ToString(AppConst.DTP_DAY_TIMESTR) + " " + DateTime.Now.ToShortTimeString(), createDateFont)); doc.Add(prgCreateDate); doc.Add(new Chunk("\n", titleFont)); Paragraph prgClassification = new Paragraph(); Paragraph prgPeriodType = new Paragraph(); Font classificationFont = new Font(PdfFont, 18, 1, BaseColor.BLACK); prgClassification.Alignment = Element.ALIGN_LEFT; prgClassification.Add(new Chunk("分類: " + classificationStr, createDateFont)); doc.Add(prgClassification); prgPeriodType.Alignment = Element.ALIGN_LEFT; prgPeriodType.Add(new Chunk("期間種類: " + periodTypeStr, createDateFont)); doc.Add(prgPeriodType); //グラフ画像を表示 string fileName = GetImageFile(imgDataStr); if (fileName != null && !string.IsNullOrEmpty(fileName)) { Image image = Image.GetInstance(fileName); image.ScalePercent(75.0f); // WindowsとPDFのサイズ共通化のため image.Alignment = Element.ALIGN_CENTER; doc.Add(image); doc.Add(new Chunk("\n", titleFont)); } //表を作成 PdfPTable table = new PdfPTable(originTable.Columns.Count) { HorizontalAlignment = Element.ALIGN_CENTER }; Font fntColumnHeader = new Font(PdfFont, 18, 1, BaseColor.WHITE); for (int i = 0; i < originTable.Columns.Count; i++) { PdfPCell cell = new PdfPCell { BackgroundColor = BaseColor.GRAY }; cell.AddElement(new Chunk(originTable.Columns[i].ColumnName.ToUpper(), fntColumnHeader)); table.AddCell(cell); } Font fntRowHeader = new Font(PdfFont, 18, 1, BaseColor.BLACK); for (int i = 0; i < originTable.Rows.Count; i++) { for (int j = 0; j < originTable.Columns.Count; j++) { PdfPCell cell = new PdfPCell { BackgroundColor = BaseColor.WHITE }; cell.AddElement(new Chunk(originTable.Rows[i][j].ToString(), fntRowHeader)); table.AddCell(cell); } } doc.Add(table); //ドキュメントを閉じる doc.Close(); //PDF作成 using (BinaryWriter w = new BinaryWriter(File.OpenWrite(FileName))) { w.Write(stream.ToArray()); } Console.WriteLine("See the " + FileName); } catch (Exception e) { string s = e.Message; OriginMBox.MBoxErrorOK(AppConst.PDF_FAILURE_MESSAGE); } }
/** * Imports the Cell properties into the RtfCell * * @param cell The PdfPCell to import * @since 2.1.3 */ private void ImportCell(PdfPCell cell) { this.content = new ArrayList(); if (cell == null) { this.borders = new RtfBorderGroup(this.document, RtfBorder.CELL_BORDER, this.parentRow.GetParentTable().GetBorders()); return; } // padding this.cellPadding = (int) this.parentRow.GetParentTable().GetCellPadding(); this.cellPaddingBottom = cell.PaddingBottom; this.cellPaddingTop = cell.PaddingTop; this.cellPaddingRight = cell.PaddingRight; this.cellPaddingLeft = cell.PaddingLeft; // BORDERS this.borders = new RtfBorderGroup(this.document, RtfBorder.CELL_BORDER, cell.Border, cell.BorderWidth, cell.BorderColor); // border colors this.border = cell.Border; this.borderColor = cell.BorderColor; this.borderColorBottom = cell.BorderColorBottom; this.borderColorTop = cell.BorderColorTop; this.borderColorLeft = cell.BorderColorLeft; this.borderColorRight = cell.BorderColorRight; // border widths this.borderWidth = cell.BorderWidth; this.borderWidthBottom = cell.BorderWidthBottom; this.borderWidthTop = cell.BorderWidthTop; this.borderWidthLeft = cell.BorderWidthLeft; this.borderWidthRight = cell.BorderWidthRight; this.colspan = cell.Colspan; this.rowspan = 1; //cell.GetRowspan(); // if (cell.GetRowspan() > 1) { // this.mergeType = MERGE_VERT_PARENT; // } this.verticalAlignment = cell.VerticalAlignment; if (cell.BackgroundColor == null) { this.backgroundColor = new RtfColor(this.document, 255, 255, 255); } else { this.backgroundColor = new RtfColor(this.document, cell.BackgroundColor); } // does it have column composite info? ArrayList compositeElements = cell.CompositeElements; if (compositeElements != null) { // does it have column info? Paragraph container = null; foreach (IElement element in compositeElements) { try { // should we wrap it in a paragraph if (!(element is Paragraph) && !(element is Legacy.Text.List)) { if (container != null) { container.Add(element); } else { container = new Paragraph(); container.Alignment = cell.HorizontalAlignment; container.Add(element); } } else { IRtfBasicElement[] rtfElements = null; if (container != null) { rtfElements = this.document.GetMapper().MapElement(container); for (int i = 0; i < rtfElements.Length; i++) { rtfElements[i].SetInTable(true); this.content.Add(rtfElements[i]); } container = null; } // if horizontal alignment is undefined overwrite // with that of enclosing cell if (element is Paragraph && ((Paragraph) element).Alignment == Element.ALIGN_UNDEFINED) { ((Paragraph) element).Alignment = cell.HorizontalAlignment; } rtfElements = this.document.GetMapper().MapElement(element); for (int i = 0; i < rtfElements.Length; i++) { rtfElements[i].SetInTable(true); this.content.Add(rtfElements[i]); } } } catch (DocumentException) { } } if (container != null) { try { IRtfBasicElement[] rtfElements = this.document.GetMapper().MapElement(container); for (int i = 0; i < rtfElements.Length; i++) { rtfElements[i].SetInTable(true); this.content.Add(rtfElements[i]); } } catch (DocumentException) { } } } // does it have image info? Image img = cell.Image; if (img != null) { try { IRtfBasicElement[] rtfElements = this.document.GetMapper().MapElement(img); for (int i = 0; i < rtfElements.Length; i++) { rtfElements[i].SetInTable(true); this.content.Add(rtfElements[i]); } } catch (DocumentException) { } } // does it have phrase info? Phrase phrase = cell.Phrase; if (phrase != null) { try { IRtfBasicElement[] rtfElements = this.document.GetMapper().MapElement(phrase); for (int i = 0; i < rtfElements.Length; i++) { rtfElements[i].SetInTable(true); this.content.Add(rtfElements[i]); } } catch (DocumentException) { } } // does it have table info? PdfPTable table = cell.Table; if (table != null) { this.Add(table); // try { // RtfBasicElement[] rtfElements = this.document.GetMapper().MapElement(table); // for (int i = 0; i < rtfElements.length; i++) { // rtfElements[i].SetInTable(true); // this.content.Add(rtfElements[i]); // } // } catch (DocumentException e) { // // TODO Auto-generated catch block // e.PrintStackTrace(); // } } }
/** * Imports the Cell properties into the RtfCell * * @param cell The Cell to import */ private void ImportCell(Cell cell) { this.content = new ArrayList(); if (cell == null) { this.borders = new RtfBorderGroup(this.document, RtfBorder.CELL_BORDER, this.parentRow.GetParentTable().GetBorders()); return; } this.colspan = cell.Colspan; this.rowspan = cell.Rowspan; if (cell.Rowspan > 1) { this.mergeType = MERGE_VERT_PARENT; } if (cell is RtfCell) { this.borders = new RtfBorderGroup(this.document, RtfBorder.CELL_BORDER, ((RtfCell) cell).GetBorders()); } else { this.borders = new RtfBorderGroup(this.document, RtfBorder.CELL_BORDER, cell.Border, cell.BorderWidth, cell.BorderColor); } this.verticalAlignment = cell.VerticalAlignment; if (cell.BackgroundColor == null) { this.backgroundColor = new RtfColor(this.document, 255, 255, 255); } else { this.backgroundColor = new RtfColor(this.document, cell.BackgroundColor); } this.cellPadding = (int) this.parentRow.GetParentTable().GetCellPadding(); Paragraph container = null; foreach (IElement element in cell.Elements) { try { // should we wrap it in a paragraph if (!(element is Paragraph) && !(element is Legacy.Text.List)) { if (container != null) { container.Add(element); } else { container = new Paragraph(); container.Alignment = cell.HorizontalAlignment; container.Add(element); } } else { if (container != null) { IRtfBasicElement[] rtfElements = this.document.GetMapper().MapElement(container); for (int i = 0; i < rtfElements.Length; i++) { rtfElements[i].SetInTable(true); this.content.Add(rtfElements[i]); } container = null; } // if horizontal alignment is undefined overwrite // with that of enclosing cell if (element is Paragraph && ((Paragraph) element).Alignment == Element.ALIGN_UNDEFINED) { ((Paragraph) element).Alignment = cell.HorizontalAlignment; } IRtfBasicElement[] rtfElements2 = this.document.GetMapper().MapElement(element); for (int i = 0; i < rtfElements2.Length; i++) { rtfElements2[i].SetInTable(true); this.content.Add(rtfElements2[i]); } } } catch (DocumentException) { } } if (container != null) { try { IRtfBasicElement[] rtfElements = this.document.GetMapper().MapElement(container); for (int i = 0; i < rtfElements.Length; i++) { rtfElements[i].SetInTable(true); this.content.Add(rtfElements[i]); } } catch (DocumentException) { } } }
private void OnSortByButtonClick(object sender, RoutedEventArgs e) { if (SortByWordsCountRadioButton.IsChecked.Value) { var sortedSentences = _text.GetSentences().OrderBy(sentence => sentence.Count); var text = new Text(); foreach(var sentence in sortedSentences) { var paragraph = new Paragraph(); paragraph.Add(sentence); text.Add(paragraph); } TextContainer.ItemsSource = text; } else if (SortBySentenceCountRadioButton.IsChecked.Value) { var sortedParagraphs = _text.OrderBy(paragraph => paragraph.Count); var text = new Text(); foreach(var paragraph in sortedParagraphs) { text.Add(paragraph); text.Add(new Paragraph()); } TextContainer.ItemsSource = text; } }
public void createReport(IEnumerable <DisplayComplaintViewModel> complaintData, FilterViewModel filterViewData) { try { System.IO.File.Delete(System.Web.HttpContext.Current.Server.MapPath("~/Content/PDF/complaints.pdf")); } catch { } String[] dateReceive = null, dateEntry = null; Document doc = new Document(PageSize.LEGAL.Rotate()); var output = new FileStream(System.Web.HttpContext.Current.Server.MapPath("~/Content/PDF/complaints.pdf"), FileMode.Create); var writer = PdfWriter.GetInstance(doc, output); doc.Open(); PdfPTable header = new PdfPTable(2); header.WidthPercentage = 80f; float[] _columnWidths = { 10, 80 }; header.SetWidths(_columnWidths); header.HorizontalAlignment = Element.ALIGN_LEFT; Image logo2 = Image.GetInstance(System.Web.HttpContext.Current.Server.MapPath("~/Content/PDF/doh.png")); logo2.ScaleAbsolute(60f, 60f); header.AddCell(new PdfPCell(logo2) { HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_LEFT, Rowspan = 4, Border = 0 }); header.AddCell(new PdfPCell(new Paragraph("REPUBLIC OF THE PHILIPPINES")) { HorizontalAlignment = Element.ALIGN_CENTER, Border = 0 }); header.AddCell(new PdfPCell(new Paragraph("Department of Health")) { HorizontalAlignment = Element.ALIGN_CENTER, Border = 0 }); header.AddCell(new PdfPCell(new Paragraph("HEALTH FACILITIES AND SERVICES REGULATORY BUREAU/REGIONAL OFFICE VII")) { HorizontalAlignment = Element.ALIGN_CENTER, Border = 0 }); header.AddCell(new PdfPCell(new Paragraph("LOGSHEET OF COMPLAINTS")) { HorizontalAlignment = Element.ALIGN_CENTER, Border = 0 }); doc.Add(header); PdfPTable sheet_num = new PdfPTable(1); sheet_num.WidthPercentage = 100f; float[] sheet_num_withs = { 100 }; sheet_num.SetWidths(sheet_num_withs); DateTime date_from = Convert.ToDateTime(filterViewData); DateTime date_to = Convert.ToDateTime(filterViewData.date_to); String month = ""; if (date_from.Month == date_to.Month) { month = date_to.ToString("MMMM"); } else { month = date_to.ToString("MMMM"); } sheet_num.AddCell(new PdfPCell(new Paragraph("Month of : " + month, new Font(Font.FontFamily.HELVETICA, 10f, Font.BOLD))) { HorizontalAlignment = Element.ALIGN_RIGHT, Border = 0, Padding = 5f }); sheet_num.AddCell(new PdfPCell(new Paragraph("Year : " + date_to.ToString("yyyy"), new Font(Font.FontFamily.HELVETICA, 10f, Font.BOLD))) { HorizontalAlignment = Element.ALIGN_RIGHT, Border = 0, Padding = 5f }); doc.Add(sheet_num); PdfPTable _thead_page_break = new PdfPTable(16); _thead_page_break.WidthPercentage = 100f; float[] main = { 40, 40, 40, 40, 40, 40, 50, 50, 40, 40, 40, 40, 40, 40, 40, 40 }; _thead_page_break.SetWidths(main); _thead_page_break.AddCell(new PdfPCell(new Paragraph("Date Received", new Font(Font.FontFamily.HELVETICA, 7f, Font.BOLD))) { HorizontalAlignment = Element.ALIGN_CENTER, Rowspan = 4, VerticalAlignment = Element.ALIGN_CENTER }); _thead_page_break.AddCell(new PdfPCell(new Paragraph("Code Number", new Font(Font.FontFamily.HELVETICA, 7f, Font.BOLD))) { HorizontalAlignment = Element.ALIGN_CENTER, Rowspan = 4, VerticalAlignment = Element.ALIGN_CENTER }); _thead_page_break.AddCell(new PdfPCell(new Paragraph("Name of Health Facility Being Complained", new Font(Font.FontFamily.HELVETICA, 7f, Font.BOLD))) { HorizontalAlignment = Element.ALIGN_CENTER, Rowspan = 4, VerticalAlignment = Element.ALIGN_CENTER }); _thead_page_break.AddCell(new PdfPCell(new Paragraph("Address", new Font(Font.FontFamily.HELVETICA, 7f, Font.BOLD))) { HorizontalAlignment = Element.ALIGN_CENTER, Rowspan = 4, VerticalAlignment = Element.ALIGN_CENTER }); _thead_page_break.AddCell(new PdfPCell(new Paragraph("Ownership", new Font(Font.FontFamily.HELVETICA, 7f, Font.BOLD))) { HorizontalAlignment = Element.ALIGN_CENTER, Rowspan = 4, VerticalAlignment = Element.ALIGN_CENTER }); _thead_page_break.AddCell(new PdfPCell(new Paragraph("Name of Complainant", new Font(Font.FontFamily.HELVETICA, 7f, Font.BOLD))) { HorizontalAlignment = Element.ALIGN_CENTER, Rowspan = 4, VerticalAlignment = Element.ALIGN_CENTER }); _thead_page_break.AddCell(new PdfPCell(new Paragraph("Types of Complaint", new Font(Font.FontFamily.HELVETICA, 7f, Font.BOLD))) { HorizontalAlignment = Element.ALIGN_CENTER, Rowspan = 4, VerticalAlignment = Element.ALIGN_CENTER }); _thead_page_break.AddCell(new PdfPCell(new Paragraph("Assistance Needed", new Font(Font.FontFamily.HELVETICA, 7f, Font.BOLD))) { HorizontalAlignment = Element.ALIGN_CENTER, Rowspan = 4, VerticalAlignment = Element.ALIGN_CENTER }); _thead_page_break.AddCell(new PdfPCell(new Paragraph("Form of Communication", new Font(Font.FontFamily.HELVETICA, 7f, Font.BOLD))) { HorizontalAlignment = Element.ALIGN_CENTER, Rowspan = 4, VerticalAlignment = Element.ALIGN_CENTER }); _thead_page_break.AddCell(new PdfPCell(new Paragraph("Action Taken", new Font(Font.FontFamily.HELVETICA, 7f, Font.BOLD))) { HorizontalAlignment = Element.ALIGN_CENTER, Rowspan = 4, VerticalAlignment = Element.ALIGN_CENTER }); _thead_page_break.AddCell(new PdfPCell(new Paragraph("Date Informed the HF/concerned office", new Font(Font.FontFamily.HELVETICA, 7f, Font.BOLD))) { HorizontalAlignment = Element.ALIGN_CENTER, Rowspan = 4, VerticalAlignment = Element.ALIGN_CENTER }); _thead_page_break.AddCell(new PdfPCell(new Paragraph("Date HF/concerned office submitted reply", new Font(Font.FontFamily.HELVETICA, 7f, Font.BOLD))) { HorizontalAlignment = Element.ALIGN_CENTER, Rowspan = 4, VerticalAlignment = Element.ALIGN_CENTER }); _thead_page_break.AddCell(new PdfPCell(new Paragraph("Date released to records section", new Font(Font.FontFamily.HELVETICA, 7f, Font.BOLD))) { HorizontalAlignment = Element.ALIGN_CENTER, Rowspan = 4, VerticalAlignment = Element.ALIGN_CENTER }); _thead_page_break.AddCell(new PdfPCell(new Paragraph("Date Resolution of the complaint released to records/client", new Font(Font.FontFamily.HELVETICA, 7f, Font.BOLD))) { HorizontalAlignment = Element.ALIGN_CENTER, Rowspan = 4, VerticalAlignment = Element.ALIGN_CENTER }); _thead_page_break.AddCell(new PdfPCell(new Paragraph("Status", new Font(Font.FontFamily.HELVETICA, 7f, Font.BOLD))) { HorizontalAlignment = Element.ALIGN_CENTER, Rowspan = 4, VerticalAlignment = Element.ALIGN_CENTER }); _thead_page_break.AddCell(new PdfPCell(new Paragraph("Staff Assigned", new Font(Font.FontFamily.HELVETICA, 7f, Font.BOLD))) { HorizontalAlignment = Element.ALIGN_CENTER, Rowspan = 4, VerticalAlignment = Element.ALIGN_CENTER }); doc.Add(_thead_page_break); PdfPTable complaints_table = new PdfPTable(16); complaints_table.WidthPercentage = 100f; complaints_table.SetWidths(main); PageEvent pe = new PageEvent(); writer.PageEvent = pe; foreach (DisplayComplaintViewModel c in complaintData) { complaints_table.AddCell(new PdfPCell(new Paragraph(c.dateCreated.ToShortDateString(), new Font(Font.FontFamily.HELVETICA, 7f))) { HorizontalAlignment = Element.ALIGN_CENTER, Rowspan = 4, VerticalAlignment = Element.ALIGN_CENTER }); complaints_table.AddCell(new PdfPCell(new Paragraph(c.codeNumber, new Font(Font.FontFamily.HELVETICA, 7f))) { HorizontalAlignment = Element.ALIGN_CENTER, Rowspan = 4, VerticalAlignment = Element.ALIGN_CENTER }); complaints_table.AddCell(new PdfPCell(new Paragraph(c.hospitalName, new Font(Font.FontFamily.HELVETICA, 7f))) { HorizontalAlignment = Element.ALIGN_LEFT, Rowspan = 4, VerticalAlignment = Element.ALIGN_CENTER }); complaints_table.AddCell(new PdfPCell(new Paragraph(c.hospitalAddress, new Font(Font.FontFamily.HELVETICA, 7f))) { HorizontalAlignment = Element.ALIGN_LEFT, Rowspan = 4, VerticalAlignment = Element.ALIGN_CENTER }); complaints_table.AddCell(new PdfPCell(new Paragraph(c.ownership == "P" ? "Private" : "Government", new Font(Font.FontFamily.HELVETICA, 7f))) { HorizontalAlignment = Element.ALIGN_CENTER, Rowspan = 4, VerticalAlignment = Element.ALIGN_CENTER }); complaints_table.AddCell(new PdfPCell(new Paragraph(c.annonymos == true ? c.nameOfComplainant : "Anonymous", new Font(Font.FontFamily.HELVETICA, 7f))) { HorizontalAlignment = Element.ALIGN_CENTER, Rowspan = 4, VerticalAlignment = Element.ALIGN_CENTER }); Paragraph complaint_type = new Paragraph(); if (c.complaint_type != null && c.complaint_type.Count() > 0) { foreach (string complaintType in c.complaint_type) { complaint_type.Add(new Chunk(complaintType + "\n", new Font(Font.FontFamily.HELVETICA, 7f))); } if (c.other_complaint != null) { complaint_type.Add(new Chunk("Others : " + c.other_complaint, new Font(Font.FontFamily.HELVETICA, 7f, Font.NORMAL))); } complaints_table.AddCell(new PdfPCell(complaint_type) { HorizontalAlignment = Element.ALIGN_LEFT, Rowspan = 4, VerticalAlignment = Element.ALIGN_CENTER }); } else { if (c.other_complaint != null) { Chunk otherComplaint = new Chunk("Others : " + c.other_complaint, new Font(Font.FontFamily.HELVETICA, 7f, Font.NORMAL)); complaint_type.Add(otherComplaint); complaints_table.AddCell(new PdfPCell(complaint_type) { HorizontalAlignment = Element.ALIGN_LEFT, Rowspan = 4, VerticalAlignment = Element.ALIGN_CENTER }); } else { complaints_table.AddCell(new PdfPCell(new Paragraph("-")) { HorizontalAlignment = Element.ALIGN_CENTER, Rowspan = 4, VerticalAlignment = Element.ALIGN_CENTER }); } } Paragraph complaint_assistance = new Paragraph(); if (c.assistanceNeeded != null && c.assistanceNeeded.Count() > 0) { foreach (string complaintAssistance in c.assistanceNeeded) { complaint_assistance.Add(new Chunk(complaintAssistance + "\n", new Font(Font.FontFamily.HELVETICA, 7f))); } if (c.otherAssistanceNeed != null) { complaint_assistance.Add(new Chunk("Others : " + c.otherAssistanceNeed, new Font(Font.FontFamily.HELVETICA, 7f, Font.NORMAL))); } complaints_table.AddCell(new PdfPCell(complaint_assistance) { HorizontalAlignment = Element.ALIGN_LEFT, Rowspan = 4, VerticalAlignment = Element.ALIGN_CENTER }); } else { if (c.otherAssistanceNeed != null) { Chunk otherAssistance = new Chunk("Others : " + c.otherAssistanceNeed, new Font(Font.FontFamily.HELVETICA, 7f, Font.NORMAL)); complaint_assistance.Add(otherAssistance); complaints_table.AddCell(new PdfPCell(complaint_assistance) { HorizontalAlignment = Element.ALIGN_LEFT, Rowspan = 4, VerticalAlignment = Element.ALIGN_CENTER }); } else { complaints_table.AddCell(new PdfPCell(new Paragraph("-")) { HorizontalAlignment = Element.ALIGN_CENTER, Rowspan = 4, VerticalAlignment = Element.ALIGN_CENTER }); } } complaints_table.AddCell(new PdfPCell(new Paragraph(c.pccCheck == true ? "PCC No. " + c.pccNumber : c.communication_form, new Font(Font.FontFamily.HELVETICA, 7f))) { HorizontalAlignment = Element.ALIGN_CENTER, Rowspan = 4, VerticalAlignment = Element.ALIGN_CENTER }); if (c._complaintActionDates != null && c._complaintActionDates.Count() > 0) { Paragraph complaint_action_dates = new Paragraph(); foreach (complaint_action_dates acd in c._complaintActionDates) { complaint_action_dates.Add(new Chunk("(" + acd.Date.ToShortDateString() + ") " + acd.Action + "\n", new Font(Font.FontFamily.HELVETICA, 7f))); } complaints_table.AddCell(new PdfPCell(complaint_action_dates) { HorizontalAlignment = Element.ALIGN_LEFT, Rowspan = 4, VerticalAlignment = Element.ALIGN_CENTER }); } else { complaints_table.AddCell(new PdfPCell(new Paragraph("-", new Font(Font.FontFamily.HELVETICA, 7f))) { HorizontalAlignment = Element.ALIGN_CENTER, Rowspan = 4, VerticalAlignment = Element.ALIGN_CENTER }); } if (c.date_informed_the_hf != null && c.date_informed_the_hf.Count() > 0) { Paragraph p_date_informed_the_hf = new Paragraph(); foreach (String s in c.date_informed_the_hf) { p_date_informed_the_hf.Add(new Chunk(s + "\n", new Font(Font.FontFamily.HELVETICA, 7f))); } complaints_table.AddCell(new PdfPCell(p_date_informed_the_hf) { HorizontalAlignment = Element.ALIGN_CENTER, Rowspan = 4, VerticalAlignment = Element.ALIGN_CENTER }); } else { complaints_table.AddCell(new PdfPCell(new Paragraph("-", new Font(Font.FontFamily.HELVETICA, 7f))) { HorizontalAlignment = Element.ALIGN_CENTER, Rowspan = 4, VerticalAlignment = Element.ALIGN_CENTER }); } if (c.date_hf_submitted_reply != null && c.date_hf_submitted_reply.Count() > 0) { Paragraph p_date_hf_submitted_reply = new Paragraph(); foreach (String s in c.date_hf_submitted_reply) { p_date_hf_submitted_reply.Add(new Chunk(s + "\n", new Font(Font.FontFamily.HELVETICA, 7f))); } complaints_table.AddCell(new PdfPCell(p_date_hf_submitted_reply) { HorizontalAlignment = Element.ALIGN_CENTER, Rowspan = 4, VerticalAlignment = Element.ALIGN_CENTER }); } else { complaints_table.AddCell(new PdfPCell(new Paragraph("-", new Font(Font.FontFamily.HELVETICA, 7f))) { HorizontalAlignment = Element.ALIGN_CENTER, Rowspan = 4, VerticalAlignment = Element.ALIGN_CENTER }); } if (c.date_release_to_records != null && c.date_release_to_records.Count() > 0) { Paragraph p_date_release_to_records = new Paragraph(); foreach (String s in c.date_release_to_records) { p_date_release_to_records.Add(new Chunk(s + "\n", new Font(Font.FontFamily.HELVETICA, 7f))); } complaints_table.AddCell(new PdfPCell(p_date_release_to_records) { HorizontalAlignment = Element.ALIGN_CENTER, Rowspan = 4, VerticalAlignment = Element.ALIGN_CENTER }); } else { complaints_table.AddCell(new PdfPCell(new Paragraph("-", new Font(Font.FontFamily.HELVETICA, 7f))) { HorizontalAlignment = Element.ALIGN_CENTER, Rowspan = 4, VerticalAlignment = Element.ALIGN_CENTER }); } if (c.date_final_resolution != null && c.date_final_resolution.Count() > 0) { Paragraph p_date_final_resolution = new Paragraph(); foreach (String s in c.date_final_resolution) { p_date_final_resolution.Add(new Chunk(s + "\n", new Font(Font.FontFamily.HELVETICA, 7f))); } complaints_table.AddCell(new PdfPCell(p_date_final_resolution) { HorizontalAlignment = Element.ALIGN_CENTER, Rowspan = 4, VerticalAlignment = Element.ALIGN_CENTER }); } else { complaints_table.AddCell(new PdfPCell(new Paragraph("-", new Font(Font.FontFamily.HELVETICA, 7f))) { HorizontalAlignment = Element.ALIGN_CENTER, Rowspan = 4, VerticalAlignment = Element.ALIGN_CENTER }); } complaints_table.AddCell(new PdfPCell(new Paragraph(c.status == 1 ? "On Going" : "Resolved", new Font(Font.FontFamily.HELVETICA, 7f))) { HorizontalAlignment = Element.ALIGN_CENTER, Rowspan = 4, VerticalAlignment = Element.ALIGN_CENTER }); complaints_table.AddCell(new PdfPCell(new Paragraph(c.staff, new Font(Font.FontFamily.HELVETICA, 7f))) { HorizontalAlignment = Element.ALIGN_CENTER, Rowspan = 4, VerticalAlignment = Element.ALIGN_CENTER }); } doc.Add(complaints_table); doc.Close(); }
private void buttonCetak_Click(object sender, EventArgs e) { var boldFont = FontFactory.GetFont(FontFactory.TIMES_BOLD, 12); var boldBig = FontFactory.GetFont(FontFactory.TIMES_BOLD, 14); var normalFont = FontFactory.GetFont(FontFactory.TIMES_ROMAN, 12); var pdfDoc = new Document(PageSize.A4, 40f, 40f, 60f, 60f); string path = "E:\\"; PdfWriter.GetInstance(pdfDoc, new FileStream(path + "/NotaLunasLayanan.pdf", FileMode.OpenOrCreate)); pdfDoc.Open(); var imagepath = @Directory.GetCurrentDirectory() + "\\KPS.PNG"; var png = iTextSharp.text.Image.GetInstance(imagepath); png.ScalePercent(87f); pdfDoc.Add(png); var spacer = new Paragraph("") { SpacingAfter = 10f, SpacingBefore = 10f, }; pdfDoc.Add(spacer); Paragraph p = new Paragraph(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(0.0F, 100.0F, BaseColor.BLACK, Element.ALIGN_LEFT, 1))); pdfDoc.Add(p); Paragraph title = new Paragraph("Nota Lunas", boldBig); title.Alignment = Element.ALIGN_CENTER; pdfDoc.Add(title); pdfDoc.Add(p); pdfDoc.Add(spacer); Paragraph tgl = new Paragraph(Convert.ToString(DateTime.Now)); tgl.Alignment = Element.ALIGN_RIGHT; pdfDoc.Add(tgl); Paragraph nomorTransaksi = new Paragraph(txtNomorTransaksi.Text); nomorTransaksi.Alignment = Element.ALIGN_LEFT; pdfDoc.Add(nomorTransaksi); pdfDoc.Add(spacer); Chunk c1 = new Chunk("Member : " + NamaPelanggan + " (" + NamaHewan + " - " + Jenis_Hewan + ")", normalFont); Chunk c2 = new Chunk("\nTelepon : " + NoTelp, normalFont); Phrase p1 = new Phrase(); p1.Add(c1); p1.Add(c2); Chunk c3 = new Chunk("\n\nNama CS : " + NamaCS, normalFont); Chunk c4 = new Chunk("\nNama Kasir : " + NamaKasir, normalFont); Phrase p2 = new Phrase(); p2.Add(c3); p2.Add(c4); Paragraph dataPembeli = new Paragraph(); dataPembeli.Add(p1); dataPembeli.Add(p2); pdfDoc.Add(dataPembeli); pdfDoc.Add(spacer); pdfDoc.Add(p); Paragraph subtitle = new Paragraph("Jasa Layanan", boldBig); subtitle.Alignment = Element.ALIGN_CENTER; pdfDoc.Add(subtitle); pdfDoc.Add(p); pdfDoc.Add(spacer); PdfPTable table = new PdfPTable(5); //actual width of table in points table.TotalWidth = 500f; //fix the absolute width of the table table.LockedWidth = true; //relative col widths in proportions - 1/3 and 2/3 float[] widths = new float[] { 3f, 12f, 12f, 8f, 12f }; table.SetWidths(widths); table.HorizontalAlignment = 1; //leave a gap before and after the table table.SpacingBefore = 20f; table.SpacingAfter = 30f; PdfPCell cell = new PdfPCell(); cell.Colspan = 5; cell.Border = 0; cell.HorizontalAlignment = 1; table.AddCell(cell); table.AddCell("No"); table.AddCell("Nama Jasa Layanan"); table.AddCell("Harga"); table.AddCell("Jumlah"); table.AddCell("Sub Total"); string connect = "datasource=127.0.0.1;port=3306;username=root;password=;database=kouvee;Convert Zero Datetime=True;"; using (MySqlConnection conn = new MySqlConnection(connect)) { string query = "SELECT L.NAMA_LAYANAN, L.HARGA_LAYANAN, P.JUMLAH_DETIL_LAYANAN , P.SUB_TOTAL_LAYANAN " + "FROM detil_transaksi_layanan P " + "JOIN layanan L ON (P.ID_LAYANAN = L.ID_LAYANAN) " + "WHERE ID_TRANSAKSI_LAYANAN = '" + txtCari.Text + "'"; MySqlCommand cmd = new MySqlCommand(query, conn); try { int i = 0; conn.Open(); using (MySqlDataReader rdr = cmd.ExecuteReader()) { while (rdr.Read()) { i++; table.AddCell(Convert.ToString(i)); table.AddCell(rdr[0].ToString()); table.AddCell("Rp. " + rdr[1].ToString()); table.AddCell(rdr[2].ToString()); table.AddCell("Rp. " + rdr[3].ToString()); } } conn.Close(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } } pdfDoc.Add(table); Chunk c5 = new Chunk("Sub Total : Rp. " + Convert.ToString(txtSubtotal.Text), normalFont); Chunk c6 = new Chunk("\n\nDiskon : Rp. " + Convert.ToString(txtDiskon.Text), normalFont); Chunk c7 = new Chunk("\n\nTotal : Rp. " + Convert.ToString(txtTotalHarga.Text), boldFont); Phrase p3 = new Phrase(); p3.Add(c5); p3.Add(c6); p3.Add(c7); Paragraph datapembayaran = new Paragraph(); datapembayaran.Add(p3); datapembayaran.Alignment = Element.ALIGN_RIGHT; pdfDoc.Add(datapembayaran); pdfDoc.Add(spacer); pdfDoc.Close(); MessageBox.Show("Nota Pembayaran telah dicetak!"); }
private void GeneratePDF() { rand[0] = (Convert.ToInt32(textbox.Text) * 1103515245) & 0x7fffffff; for (int i = 0; i < 49; i++) { rand[i + 1] = (rand[i] * 1103515245) & 0x7fffffff; } var paper1 = new Document(PageSize.A4, 60, 60, 80, 50); PdfWriter pdf = PdfWriter.GetInstance(paper1, new FileStream("paper1.pdf", FileMode.Create)); PageEventHelper pageEventHelper = new PageEventHelper(); pdf.PageEvent = pageEventHelper; paper1.Open(); Font roman = new Font(Font.FontFamily.TIMES_ROMAN, 10f); PdfPTable table = new PdfPTable(1); table.TotalWidth = 480f; table.LockedWidth = true; var p = new Paragraph(); p.Add(new Phrase("SECTION A(1) (35 marks)\n\n\n", new Font(Font.FontFamily.TIMES_ROMAN, 10f, Font.BOLD))); //Question 1 p.Add(new Phrase("\n1. Simplify ", roman)); string strquestion1 = GenerateQuestion(1); iTextSharp.text.Image png = iTextSharp.text.Image.GetInstance(new Uri(GenerateImage(strquestion1, "img1.png"))); label.Content = strquestion1; png.ScalePercent(10f); p.Add(new Chunk(png, 0, -9f)); p.Add(new Phrase(" and express your answer with positive indices.", roman)); //p.TabSettings = new TabSettings(); //p.Add(Chunk.TABBING); p.Add(new Chunk(new VerticalPositionMark())); p.Add(new Phrase("(3 marks)", roman)); p.Add(new Phrase("_\n\n\n", FontFactory.GetFont("Times New Roman", 10, Font.BOLD, new iTextSharp.text.BaseColor(255, 255, 255)))); for (int i = 0; i < 11; i++) { p.Add(new Phrase(" ____________________________________________________________________\n\n", new Font(Font.FontFamily.TIMES_ROMAN, 13f))); } //Question 2 p.Add(new Phrase("\n2. Make ", roman)); string strquestion2 = GenerateQuestion(2); png = iTextSharp.text.Image.GetInstance(new Uri(GenerateImage(strquestion2, "img2.png"))); png.ScalePercent(10f); if (strquestion2.Contains("y")) { p.Add(new Chunk(png, 0, -2f)); } else { p.Add(new Chunk(png, 0, 0)); } p.Add(new Phrase(" the subject of the formula ", roman)); string strquestion3 = GenerateQuestion(3); png = iTextSharp.text.Image.GetInstance(new Uri(GenerateImage(strquestion3, "img3.png"))); png.ScalePercent(10f); if (strquestion3.Contains("\\frac{")) { p.Add(new Chunk(png, 0, -7f)); } else { p.Add(new Chunk(png, 0, -2f)); } p.Add(new Phrase(" .", roman)); p.Add(new Chunk(new VerticalPositionMark())); p.Add(new Phrase("(3 marks)", roman)); p.Add(new Phrase("_\n\n\n", FontFactory.GetFont("Times New Roman", 10, Font.BOLD, new iTextSharp.text.BaseColor(255, 255, 255)))); for (int i = 0; i < 11; i++) { p.Add(new Phrase(" ____________________________________________________________________\n\n", new Font(Font.FontFamily.TIMES_ROMAN, 13f))); } PdfPCell content = new PdfPCell(new Phrase(p)); //content.Colspan = 4; table.AddCell(content); paper1.Add(table); Paragraph para = new Paragraph(new Phrase("Answers written in the margins will not be marked.", roman)); para.Add(new Chunk(new VerticalPositionMark())); para.Add(new Phrase("Seed: " + textbox.Text.ToString(), roman)); paper1.Add(para); //Paragraph password = new Paragraph(new Phrase("Password: "******"3. Factorize\n\n (a) ", roman)); string strquestion4 = GenerateQuestion(4); png = iTextSharp.text.Image.GetInstance(new Uri(GenerateImage(strquestion4, "img4.png"))); png.ScalePercent(10f); p.Add(new Chunk(png, 0, -2f)); p.Add(new Phrase(" ,\n\n (b) ", roman)); string strquestion5 = GenerateQuestion(5); png = iTextSharp.text.Image.GetInstance(new Uri(GenerateImage(strquestion5, "img5.png"))); png.ScalePercent(10f); p.Add(new Chunk(png, 0, -2f)); p.Add(new Phrase(" .", roman)); //p.TabSettings = new TabSettings(); //p.Add(Chunk.TABBING); p.Add(new Chunk(new VerticalPositionMark())); p.Add(new Phrase("(3 marks)", roman)); p.Add(new Phrase("_\n\n\n", FontFactory.GetFont("Times New Roman", 10, Font.BOLD, new iTextSharp.text.BaseColor(255, 255, 255)))); for (int i = 0; i < 11; i++) { p.Add(new Phrase(" ____________________________________________________________________\n\n", new Font(Font.FontFamily.TIMES_ROMAN, 13f))); } content = new PdfPCell(new Phrase(p)); //content.Colspan = 4; table.AddCell(content); paper1.Add(table); paper1.Add(para); paper1.Close(); pdfWebViewer.Navigate(System.AppDomain.CurrentDomain.BaseDirectory + "paper1.pdf"); }
/// <summary> /// This method deals with the starting tags. /// </summary> /// <param name="name">the name of the tag</param> public void HandleEndingTags(string name) { //System.err.Println("Stop: " + name); if (ElementTags.IGNORE.Equals(name)) { Ignore = false; return; } if (Ignore) { return; } // tags that don't have any content if (isNewpage(name) || ElementTags.ANNOTATION.Equals(name) || ElementTags.IMAGE.Equals(name) || isNewline(name)) { return; } // titles of sections and chapters if (ElementTags.TITLE.Equals(name)) { var current = (Paragraph)Stack.Pop(); if (CurrentChunk != null) { current.Add(CurrentChunk); CurrentChunk = null; } var previous = (Section)Stack.Pop(); previous.Title = current; Stack.Push(previous); return; } // all other endtags if (CurrentChunk != null) { ITextElementArray current; try { current = (ITextElementArray)Stack.Pop(); } catch { current = new Paragraph(); } current.Add(CurrentChunk); Stack.Push(current); CurrentChunk = null; } // chunks if (ElementTags.CHUNK.Equals(name)) { return; } // phrases, anchors, lists, tables if (ElementTags.PHRASE.Equals(name) || ElementTags.ANCHOR.Equals(name) || ElementTags.LIST.Equals(name) || ElementTags.PARAGRAPH.Equals(name)) { var current = (IElement)Stack.Pop(); try { var previous = (ITextElementArray)Stack.Pop(); previous.Add(current); Stack.Push(previous); } catch { Document.Add(current); } return; } // listitems if (ElementTags.LISTITEM.Equals(name)) { var listItem = (ListItem)Stack.Pop(); var list = (List)Stack.Pop(); list.Add(listItem); Stack.Push(list); } // tables if (ElementTags.TABLE.Equals(name)) { var table = (Table)Stack.Pop(); try { var previous = (ITextElementArray)Stack.Pop(); previous.Add(table); Stack.Push(previous); } catch { Document.Add(table); } return; } // rows if (ElementTags.ROW.Equals(name)) { var cells = new ArrayList(); var columns = 0; Table table; Cell cell; while (true) { var element = (IElement)Stack.Pop(); if (element.Type == Element.CELL) { cell = (Cell)element; columns += cell.Colspan; cells.Add(cell); } else { table = (Table)element; break; } } if (table.Columns < columns) { table.AddColumns(columns - table.Columns); } cells.Reverse(0, cells.Count); string width; var cellWidths = new float[columns]; var cellNulls = new bool[columns]; for (var i = 0; i < columns; i++) { cellWidths[i] = 0; cellNulls[i] = true; } float total = 0; var j = 0; foreach (Cell c in cells) { cell = c; width = cell.GetWidthAsString(); if (cell.Width.ApproxEquals(0)) { if (cell.Colspan == 1 && cellWidths[j].ApproxEquals(0)) { try { cellWidths[j] = 100f / columns; total += cellWidths[j]; } catch { // empty on purpose } } else if (cell.Colspan == 1) { cellNulls[j] = false; } } else if (cell.Colspan == 1 && width.EndsWith("%")) { try { cellWidths[j] = float.Parse(width.Substring(0, width.Length - 1), System.Globalization.NumberFormatInfo.InvariantInfo); total += cellWidths[j]; } catch { // empty on purpose } } j += cell.Colspan; table.AddCell(cell); } var widths = table.ProportionalWidths; if (widths.Length == columns) { var left = 0.0f; for (var i = 0; i < columns; i++) { if (cellNulls[i] && widths[i].ApproxNotEqual(0)) { left += widths[i]; cellWidths[i] = widths[i]; } } if (100.0 >= total) { for (var i = 0; i < widths.Length; i++) { if (cellWidths[i].ApproxEquals(0) && widths[i].ApproxNotEqual(0)) { cellWidths[i] = (widths[i] / left) * (100.0f - total); } } } table.Widths = cellWidths; } Stack.Push(table); } // registerfont if (name.Equals("registerfont")) { return; } // header if (ElementTags.HEADER.Equals(name)) { Document.Header = (HeaderFooter)Stack.Pop(); return; } // footer if (ElementTags.FOOTER.Equals(name)) { Document.Footer = (HeaderFooter)Stack.Pop(); return; } // before if (name.Equals("before")) { return; } // after if (name.Equals("after")) { return; } // cells if (ElementTags.CELL.Equals(name)) { return; } // sections if (ElementTags.SECTION.Equals(name)) { Stack.Pop(); return; } // chapters if (ElementTags.CHAPTER.Equals(name)) { Document.Add((IElement)Stack.Pop()); return; } // the documentroot if (IsDocumentRoot(name)) { try { while (true) { var element = (IElement)Stack.Pop(); try { var previous = (ITextElementArray)Stack.Pop(); previous.Add(element); Stack.Push(previous); } catch { Document.Add(element); } } } catch { // empty on purpose } if (ControlOpenClose) { Document.Close(); } return; } }
protected void ExporttoPDF_Click(object sender, EventArgs e) { ShowMessage("Successfully Export to PDF File", MessageType.success); int columnsCount = DoctorsView.HeaderRow.Cells.Count; // Create the PDF Table specifying the number of columns PdfPTable pdfTable = new PdfPTable(columnsCount); // Loop thru each cell in GrdiView header row foreach (TableCell gridViewHeaderCell in DoctorsView.HeaderRow.Cells) { // Create the Font Object for PDF document Font font66 = new Font(Font.FontFamily.TIMES_ROMAN, 10.5f, Font.BOLD | Font.NORMAL, BaseColor.WHITE); // Set the font color to GridView header row font color PdfPCell pdfCell = new PdfPCell(new Phrase(gridViewHeaderCell.Text, font66)); pdfCell.PaddingTop = 7; pdfCell.MinimumHeight = 30; pdfCell.HorizontalAlignment = 1; pdfCell.BackgroundColor = new BaseColor(61, 60, 65); // Add the cell to PDF table pdfTable.AddCell(pdfCell); } // Loop thru each datarow in GrdiView foreach (GridViewRow gridViewRow in DoctorsView.Rows) { if (gridViewRow.RowType == DataControlRowType.DataRow) { // Loop thru each cell in GrdiView data row foreach (TableCell gridViewCell in gridViewRow.Cells) { Font font55 = new Font(Font.FontFamily.TIMES_ROMAN, 10f, Font.NORMAL | Font.NORMAL, BaseColor.BLACK); // Set the font color to GridView header row font color PdfPCell pdfCell = new PdfPCell(new Phrase(gridViewCell.Text, font55)); pdfCell.HorizontalAlignment = 1; pdfCell.PaddingTop = 7; pdfCell.MinimumHeight = 30; //pdfCell.Width = 70; pdfCell.BackgroundColor = new BaseColor(DoctorsView.RowStyle.BackColor); pdfTable.AddCell(pdfCell); } } } // Create the PDF document specifying page size and margins Document pdfDocument = new Document(PageSize.A4, 5f, 15f, 5f, 5f); pdfDocument.SetPageSize(PageSize.A4.Rotate()); PdfWriter.GetInstance(pdfDocument, Response.OutputStream); pdfDocument.Open(); //Report Header Font font22 = new Font(Font.FontFamily.TIMES_ROMAN, 12f, Font.NORMAL | Font.NORMAL, BaseColor.BLACK); Font font = new Font(Font.FontFamily.TIMES_ROMAN, 20f, Font.NORMAL | Font.NORMAL, BaseColor.BLACK); Paragraph prgHeading = new Paragraph(); prgHeading.Alignment = Element.ALIGN_CENTER; prgHeading.Add(new Chunk("\nHEALTH BRIDGE\n", font)); prgHeading.Add(new Chunk("Digital Medical Service Platform Between Patients And Doctors", font22)); pdfDocument.Add(prgHeading); //Filters Paragraph prgAuthor = new Paragraph(); Font font1 = new Font(Font.FontFamily.TIMES_ROMAN, 11f, Font.NORMAL | Font.NORMAL, BaseColor.BLACK); prgAuthor.Alignment = Element.ALIGN_RIGHT; prgAuthor.Add(new Chunk("Reported by : Ragiri Rajasekhar\n", font1)); prgAuthor.Add(new Chunk("Report Date : " + DateTime.Now.ToShortDateString(), font1)); pdfDocument.Add(prgAuthor); //Add a line seperation Paragraph p = new Paragraph(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(0.0F, 100.0F, BaseColor.BLACK, Element.ALIGN_LEFT, 1))); pdfDocument.Add(p); //Add line break pdfDocument.Add(new Chunk("\n")); pdfDocument.Add(pdfTable); pdfDocument.Close(); Response.ContentType = "application/pdf"; Response.AppendHeader("content-disposition", "attachment;filename=DoctorsList.pdf"); Response.Write(pdfDocument); Response.Flush(); Response.End(); }
public void xuatBaoCao(GunaDataGridView dgv) { if (dgv.Rows.Count > 0) { SaveFileDialog sfd = new SaveFileDialog { Filter = "PDF (*.pdf)|*.pdf", FileName = "Output.pdf" }; bool fileError = false; if (sfd.ShowDialog() == DialogResult.OK) { if (File.Exists(sfd.FileName)) { try { File.Delete(sfd.FileName); } catch (IOException ex) { fileError = true; frm.capNhatLoiNhan("Đang có chương trình mở file này!!!"); frm.ShowDialog(); } } if (!fileError) { try { PdfPTable pdfTable = new PdfPTable(dgv.Columns.Count); pdfTable.DefaultCell.Padding = 3; pdfTable.WidthPercentage = 100; pdfTable.HorizontalAlignment = Element.ALIGN_LEFT; BaseFont bf = BaseFont.CreateFont(@"C:\WINDOWS\Fonts\TIMES.TTF", BaseFont.IDENTITY_H, true); iTextSharp.text.Font fonttitle = new iTextSharp.text.Font(bf, 15); iTextSharp.text.Font font = new iTextSharp.text.Font(bf, 10); iTextSharp.text.Font fonttext = new iTextSharp.text.Font(bf, 12); Paragraph header = new Paragraph { Alignment = Element.ALIGN_CENTER }; Paragraph text = new Paragraph(); Chunk c1 = new Chunk("BÁO CÁO THỐNG KÊ TRÌNH ĐỘ CHUYÊN MÔN \n", fonttitle); Chunk c2 = new Chunk(DateTime.Now.ToShortDateString() + "\n\n", font); header.Add(c1); header.Add(c2); foreach (DataGridViewColumn column in dgv.Columns) { PdfPCell cell = new PdfPCell(new Phrase(column.HeaderText, fonttext)); pdfTable.AddCell(cell); } foreach (DataGridViewRow row in dgv.Rows) { foreach (DataGridViewCell cell in row.Cells) { PdfPCell cell1 = new PdfPCell(new Phrase(cell.Value.ToString(), fonttext)); pdfTable.AddCell(cell1); } } using (FileStream stream = new FileStream(sfd.FileName, FileMode.Create)) { Document pdfDoc = new Document(PageSize.A4, 10f, 20f, 20f, 10f); PdfWriter.GetInstance(pdfDoc, stream); pdfDoc.Open(); pdfDoc.Add(header); pdfDoc.Add(pdfTable); pdfDoc.Close(); stream.Close(); } frm.capNhatLoiNhan("Xuất dữ liệu thành công!!!"); frm.ShowDialog(); } catch (Exception ex) { frm.capNhatLoiNhan("Có lỗi xảy ra!!!"); frm.ShowDialog(); } } } } else { frm.capNhatLoiNhan("Không có bản ghi nào được xuất!!!"); frm.ShowDialog(); } }
public ActionResult MultiplePDF(string[] files, string[] custNo, string[] custName) { try { //string[] files = collection["files"]; // , int[] custNo, string[] custName var fName = string.Format(DateTime.Now.ToString() + "- .pdf", DateTime.Now.ToString("s")); using (MemoryStream stream = new System.IO.MemoryStream()) { //Initialize the PDF document object. using (Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 10f)) { PdfWriter writer = PdfWriter.GetInstance(pdfDoc, stream); pdfDoc.Open(); int tableColumns = 3; int col = 3; PdfPTable table = new PdfPTable(3); for (int i = 0; i < files.Length; i++) { PdfPCell cell = new PdfPCell(); Paragraph p = new Paragraph(); var file = files[i].Split(',')[1]; var bytes = Convert.FromBase64String(file); //Add the Image file to the PDF document object. iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(bytes); img.ScalePercent(28); img.Border = iTextSharp.text.Rectangle.BOX; img.BorderColor = BaseColor.BLACK; img.BorderWidth = 2f; img.PaddingTop = 6f; cell.AddElement(img); BaseFont bfTimes = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false); iTextSharp.text.Font times = new iTextSharp.text.Font(bfTimes, 9, iTextSharp.text.Font.BOLD, BaseColor.BLACK); p.Add(new Paragraph(Convert.ToString(custNo[i]), times)); p.Add(new Paragraph(custName[i], times)); p.Alignment = Element.ALIGN_CENTER; p.Add(" "); p.Add(" "); p.Add(" "); cell.AddElement(p); table.AddCell(cell); } pdfDoc.Add(table); pdfDoc.Close(); //Download the PDF file. //return File(stream.ToArray(), "application/pdf", "ImageExport.pdf"); } var bytes1 = stream.ToArray(); Session[fName] = bytes1; for (var i = 0; i < custNo.Length; i++) { var cid = custNo[i].Split('-'); int intcid = Convert.ToInt32(cid[0].Trim()); var singlecustomer = db.Customers.Where(x => x.Cid == intcid).SingleOrDefault(); if (singlecustomer != null) { singlecustomer.QRCode = 1; db.Entry(singlecustomer).State = EntityState.Modified; db.SaveChanges(); } } } return(Json(new { success = true, pdf = true, fName }, JsonRequestBehavior.AllowGet)); } catch (Exception e) { throw e; } }
} // Add information about Client to Offer Form private void button2_Click(object sender, EventArgs e) { PdfPCell getCell(String text, int alignment) { string ss = @"C:\Windows\Fonts\micross.ttf"; BaseFont aa = BaseFont.CreateFont(ss, BaseFont.IDENTITY_H, BaseFont.EMBEDDED); iTextSharp.text.Font bb = new iTextSharp.text.Font(aa, 8, iTextSharp.text.Font.NORMAL); PdfPCell cell = new PdfPCell(new Phrase(text, bb)); cell.Padding = (0); cell.HorizontalAlignment = alignment; cell.Border = PdfPCell.NO_BORDER; return(cell); } string My_Info = ""; string Client_info = ""; using (zlecenieEntities db = new zlecenieEntities()) { int My_ID = 20; int Client_ID = _o.ID; if (_o != null) { Client_ID = _o.Id_zleceniodawca; } else { Client_ID = client_id; } My_Info = db.kontrahent.Find(My_ID).Imie + " " + db.kontrahent.Find(My_ID).Nazwisko + "\n" + db.kontrahent.Find(My_ID).Nazwa_Firmy + "\nul. " + db.adres.Find(db.kontrahent.Find(My_ID).Adres).Nazwa_ulicy + " " + db.adres.Find(db.kontrahent.Find(My_ID).Adres).Numer_budynku + "/" + db.adres.Find(db.kontrahent.Find(My_ID).Adres).Numer_mieszkania + "\n" + db.adres.Find(db.kontrahent.Find(My_ID).Adres).Kod_pocztowy.Remove(2, 3) + "-" + db.adres.Find(db.kontrahent.Find(My_ID).Adres).Kod_pocztowy.Remove(0, 2) + " " + db.adres.Find(db.kontrahent.Find(My_ID).Adres).Miasto + "\nNIP: " + db.kontrahent.Find(My_ID).NIP + "\nPESEL: " + db.kontrahent.Find(My_ID).Pesel + "\nEmail: " + db.kontrahent.Find(My_ID).E_mail + "\nTel: " + db.kontrahent.Find(My_ID).Telefon_1 + "\nTel: " + db.kontrahent.Find(My_ID).Telefon_2 + "\nPaństwo: " + db.adres.Find(db.kontrahent.Find(My_ID).Adres).Państwo; Client_info = db.kontrahent.Find(Client_ID).Imie + " " + db.kontrahent.Find(Client_ID).Nazwisko + "\n" + db.kontrahent.Find(Client_ID).Nazwa_Firmy + "\nul. " + db.adres.Find(db.kontrahent.Find(Client_ID).Adres).Nazwa_ulicy + " " + db.adres.Find(db.kontrahent.Find(Client_ID).Adres).Numer_budynku + "/" + db.adres.Find(db.kontrahent.Find(Client_ID).Adres).Numer_mieszkania + "\n" + db.adres.Find(db.kontrahent.Find(Client_ID).Adres).Kod_pocztowy.Remove(2, 3) + "-" + db.adres.Find(db.kontrahent.Find(Client_ID).Adres).Kod_pocztowy.Remove(0, 2) + " " + db.adres.Find(db.kontrahent.Find(Client_ID).Adres).Miasto + "\nNIP: " + db.kontrahent.Find(Client_ID).NIP + "\nPESEL: " + db.kontrahent.Find(Client_ID).Pesel + "\nEmail: " + db.kontrahent.Find(Client_ID).E_mail + "\nTel: " + db.kontrahent.Find(Client_ID).Telefon_1 + "\nTel: " + db.kontrahent.Find(Client_ID).Telefon_2 + "\nPaństwo: " + db.adres.Find(db.kontrahent.Find(Client_ID).Adres).Państwo; } Document document = new Document(); PdfWriter.GetInstance(document, new FileStream(@"E:\E-elektryk oferty\" + _o.ID + "_" + DateTime.Now.Month + "_" + DateTime.Now.Year + ".pdf", FileMode.Create)); document.Open(); #region font string myFont = @"C:\Windows\Fonts\micross.ttf"; BaseFont bf = BaseFont.CreateFont(myFont, BaseFont.IDENTITY_H, BaseFont.EMBEDDED); iTextSharp.text.Font Font_Table_Headers = new iTextSharp.text.Font(bf, 8, iTextSharp.text.Font.BOLD); iTextSharp.text.Font Font_Table_Cells = new iTextSharp.text.Font(bf, 6, iTextSharp.text.Font.NORMAL); iTextSharp.text.Font Title_Font = new iTextSharp.text.Font(bf, 12, iTextSharp.text.Font.BOLD); #endregion #region Client_info PdfPTable headers = new PdfPTable(2); headers.HorizontalAlignment = Element.ALIGN_LEFT; headers.AddCell(getCell(My_Info, Element.ALIGN_LEFT)); headers.AddCell(getCell(Client_info, Element.ALIGN_RIGHT)); document.Add(headers); #endregion #region Title Paragraph title = new Paragraph(); Chunk c1 = new Chunk("Oferta nr: " + _o.ID + "/" + DateTime.Now.Month + "/" + DateTime.Now.Year, Title_Font); title.Add(c1); title.Alignment = Element.ALIGN_CENTER; document.Add(title); Paragraph pause = new Paragraph(); Chunk c2 = new Chunk(" ", Title_Font); pause.Add(c2); pause.Alignment = Element.ALIGN_CENTER; document.Add(pause); #endregion #region date Paragraph date = new Paragraph(); Chunk c3 = new Chunk("Oferta ważna od: " + dateTimePicker1.Value.ToString().Remove(10, 9) + "\r", Font_Table_Cells); Chunk c4 = new Chunk("Oferta ważna do: " + dateTimePicker2.Value.ToString().Remove(10, 9), Font_Table_Cells); date.Add(c3); date.Add(c4); date.Alignment = Element.ALIGN_LEFT; document.Add(date); document.Add(pause); #endregion #region tabela int columns = dataGridView1.Columns.Count; PdfPTable table = new PdfPTable(columns); float[] widths = new float[] { 10, 45, 25, 10, 15, 15, 15, 10, 15, 30 }; table.SetWidths(widths); table.AddCell(new PdfPCell(new Phrase("ID", Font_Table_Headers))); table.AddCell(new PdfPCell(new Phrase("Nazwa", Font_Table_Headers))); table.AddCell(new PdfPCell(new Phrase("Producent", Font_Table_Headers))); table.AddCell(new PdfPCell(new Phrase("JM", Font_Table_Headers))); table.AddCell(new PdfPCell(new Phrase("Ilość", Font_Table_Headers))); table.AddCell(new PdfPCell(new Phrase("C.j", Font_Table_Headers))); table.AddCell(new PdfPCell(new Phrase("Netto", Font_Table_Headers))); table.AddCell(new PdfPCell(new Phrase("Vat", Font_Table_Headers))); table.AddCell(new PdfPCell(new Phrase("Brutto", Font_Table_Headers))); table.AddCell(new PdfPCell(new Phrase("Kategoria", Font_Table_Headers))); for (int j = 0; j < dataGridView1.Rows.Count; j++) { for (int i = 0; i < dataGridView1.Columns.Count; i++) { table.AddCell(new PdfPCell(new Phrase(dataGridView1.Rows[j].Cells[i].Value.ToString(), Font_Table_Cells))); } } document.Add(table); #endregion document.Close(); MessageBox.Show("Utworzono ofertę " + _o.ID + "." + DateTime.Now.Month + "." + DateTime.Now.Year + ".pdf"); Process myProcess = new Process(); myProcess.StartInfo.FileName = "acroRd32.exe"; //not the full application path myProcess.StartInfo.Arguments = "\"" + @"E:\E-elektryk oferty\" + _o.ID + "_" + DateTime.Now.Month + "_" + DateTime.Now.Year + ".pdf" + "\""; myProcess.Start(); } // Generate offer pdf using itextsharp
public void GERARELATORIO(int tipo) { //CRIA O PDF Document relatorio = new Document(PageSize.A4.Rotate()); relatorio.SetMargins(30, 20, 30, 20); relatorio.AddCreationDate(); //CAMINHO ONDE O PDF É SALVO E O NOME DO PDF string caminho = @"C:\Users\defar\Desktop\relatoriopr.pdf"; PdfWriter writer = PdfWriter.GetInstance(relatorio, new FileStream(caminho, FileMode.Create)); //ABRI O PDF relatorio.Open(); //----------------------------------------------------------------------------------- SqlDataReader leitor; SqlCommand selecionafilme = new SqlCommand(); SqlConnection conexao = new SqlConnection(); //------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------- conexao = new SqlConnection("Data Source = DESKTOP-L0FTKI7; Initial Catalog = ALTERNATIVA; Integrated Security=SSPI"); conexao.Open(); selecionafilme = new SqlCommand("SELECT NOMEFAN AS NOME, ENDERECO, NUMERO, COMPLEMENTO, BARRIO AS BAIRRO, CEP, CIDADE, ESTADO, TELEFONE, CELULAR, EMAIL, VINCULAR FROM EMPRESA", conexao); //------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------- Paragraph paragrafo = new Paragraph(); leitor = selecionafilme.ExecuteReader(); if (leitor.Read() != false) { if (leitor["VINCULAR"].ToString() == "S") { paragrafo.Alignment = Element.ALIGN_CENTER; paragrafo.Add(leitor["NOME"].ToString()); relatorio.Add(paragrafo); if (leitor["COMPLEMENTO"].ToString() == "") { paragrafo = new Paragraph(); paragrafo.Alignment = Element.ALIGN_CENTER; paragrafo.Add(leitor["ENDERECO"].ToString() + ", " + leitor["NUMERO"].ToString() + " - " + leitor["BAIRRO"].ToString()); relatorio.Add(paragrafo); } else { paragrafo = new Paragraph(); paragrafo.Alignment = Element.ALIGN_CENTER; paragrafo.Add(leitor["ENDERECO"].ToString() + ", " + leitor["NUMERO"].ToString() + ", " + leitor["COMPLEMENTO"].ToString() + " - " + leitor["BAIRRO"].ToString()); relatorio.Add(paragrafo); } paragrafo = new Paragraph(); paragrafo.Alignment = Element.ALIGN_CENTER; paragrafo.Add("CEP " + leitor["CEP"].ToString() + " - " + leitor["CIDADE"].ToString() + " - " + leitor["ESTADO"].ToString()); relatorio.Add(paragrafo); if ((leitor["TELEFONE"].ToString() == "( ) -") && (leitor["CELULAR"].ToString() != "( ) -")) { paragrafo = new Paragraph(); paragrafo.Alignment = Element.ALIGN_CENTER; paragrafo.Add("FONE: " + leitor["CELULAR"].ToString()); relatorio.Add(paragrafo); } else if ((leitor["TELEFONE"].ToString() != "( ) -") && (leitor["CELULAR"].ToString() == "( ) -")) { paragrafo = new Paragraph(); paragrafo.Alignment = Element.ALIGN_CENTER; paragrafo.Add("FONE: " + leitor["TELEFONE"].ToString()); relatorio.Add(paragrafo); } else { paragrafo = new Paragraph(); paragrafo.Alignment = Element.ALIGN_CENTER; paragrafo.Add("FONE: " + leitor["TELEFONE"].ToString() + " / " + leitor["CELULAR"].ToString()); relatorio.Add(paragrafo); } paragrafo = new Paragraph(); paragrafo.Alignment = Element.ALIGN_CENTER; paragrafo.Add("E-MAIL: " + leitor["EMAIL"].ToString()); relatorio.Add(paragrafo); paragrafo = new Paragraph(); paragrafo.Alignment = Element.ALIGN_CENTER; paragrafo.Add(" "); relatorio.Add(paragrafo); paragrafo = new Paragraph(); paragrafo.Alignment = Element.ALIGN_CENTER; paragrafo.Add("RELATÓRIO DE PRODUTOS - MÍNIMO"); relatorio.Add(paragrafo); paragrafo = new Paragraph(); paragrafo.Alignment = Element.ALIGN_CENTER; paragrafo.Add(" "); relatorio.Add(paragrafo); } else { //----------------------------------------------------------------------------------- //PARAGRAFOS DE INICIO paragrafo.Alignment = Element.ALIGN_CENTER; paragrafo.Add("ALTERNATIVA MOTOS"); relatorio.Add(paragrafo); paragrafo = new Paragraph(); paragrafo.Alignment = Element.ALIGN_CENTER; paragrafo.Add("RELATÓRIO DE PRODUTOS"); relatorio.Add(paragrafo); for (int I = 0; I < 3; I++) { paragrafo = new Paragraph(); paragrafo.Alignment = Element.ALIGN_CENTER; paragrafo.Add(" "); relatorio.Add(paragrafo); } } leitor.Close(); conexao.Close(); if (tipo == 2) { //TABELA COM OS DADOS DO CLIENTE PdfPTable CABECALHO = new PdfPTable(7); CABECALHO.TotalWidth = 650f; CABECALHO.LockedWidth = true; float[] widths = new float[] { 75f, 85f, 150f, 100f, 100f, 70f, 70f }; CABECALHO.SetWidths(widths); conexao = new SqlConnection("Data Source = DESKTOP-L0FTKI7; Initial Catalog = ALTERNATIVA; Integrated Security=SSPI"); conexao.Open(); selecionafilme = new SqlCommand("SELECT CODIGO, CBARRAS,DESCRICAO,MARCA,MODELO,QUANTIDADE,ESTOQUEMIN FROM PRODUTOS where quantidade <= estoquemin and tipo = 'Produto'", conexao); Phrase item1 = new Phrase("Código"); var cel = new PdfPCell(item1); CABECALHO.AddCell(cel); Phrase item2 = new Phrase("Cód. de Barras"); cel = new PdfPCell(item2); CABECALHO.AddCell(cel); Phrase item3 = new Phrase("Descrição"); cel = new PdfPCell(item3); cel.Colspan = 1; CABECALHO.AddCell(cel); Phrase item4 = new Phrase("Marca"); cel = new PdfPCell(item4); CABECALHO.AddCell(cel); Phrase item5 = new Phrase("Modelo"); cel = new PdfPCell(item5); CABECALHO.AddCell(cel); Phrase item6 = new Phrase("Quantidade"); cel = new PdfPCell(item6); CABECALHO.AddCell(cel); Phrase item7 = new Phrase("Mínimo"); cel = new PdfPCell(item7); CABECALHO.AddCell(cel); item1 = new Phrase(" "); item1.Font.Size = 2; cel = new PdfPCell(item1); cel.Colspan = 7; cel.BackgroundColor = iTextSharp.text.BaseColor.DARK_GRAY; CABECALHO.AddCell(cel); leitor = selecionafilme.ExecuteReader(); while (leitor.Read() != false) { item1 = new Phrase(leitor["CODIGO"].ToString()); cel = new PdfPCell(item1); CABECALHO.AddCell(cel); item2 = new Phrase(leitor["CBARRAS"].ToString()); cel = new PdfPCell(item2); CABECALHO.AddCell(cel); item3 = new Phrase(leitor["DESCRICAO"].ToString()); cel = new PdfPCell(item3); cel.Colspan = 1; CABECALHO.AddCell(cel); item4 = new Phrase(leitor["MARCA"].ToString()); cel = new PdfPCell(item4); CABECALHO.AddCell(cel); item5 = new Phrase(leitor["MODELO"].ToString()); cel = new PdfPCell(item5); CABECALHO.AddCell(cel); item6 = new Phrase(leitor["QUANTIDADE"].ToString()); cel = new PdfPCell(item6); CABECALHO.AddCell(cel); item7 = new Phrase(leitor["ESTOQUEMIN"].ToString()); cel = new PdfPCell(item7); CABECALHO.AddCell(cel); } conexao.Close(); leitor.Close(); item1 = new Phrase(" "); item1.Font.Size = 2; cel = new PdfPCell(item1); cel.Colspan = 7; cel.BackgroundColor = iTextSharp.text.BaseColor.DARK_GRAY; CABECALHO.AddCell(cel); relatorio.Add(CABECALHO); paragrafo = new Paragraph(); paragrafo.Alignment = Element.ALIGN_CENTER; paragrafo.Add(" "); relatorio.Add(paragrafo); paragrafo = new Paragraph(); paragrafo.Alignment = Element.ALIGN_CENTER; paragrafo.Add(" "); relatorio.Add(paragrafo); } else if (tipo == 1) { //TABELA COM OS DADOS DO CLIENTE PdfPTable CABECALHO = new PdfPTable(7); CABECALHO.TotalWidth = 650f; CABECALHO.LockedWidth = true; float[] widths = new float[] { 75f, 85f, 150f, 100f, 100f, 70f, 70f }; CABECALHO.SetWidths(widths); conexao = new SqlConnection("Data Source = DESKTOP-L0FTKI7; Initial Catalog = ALTERNATIVA; Integrated Security=SSPI"); conexao.Open(); selecionafilme = new SqlCommand("SELECT CODIGO, CBARRAS,DESCRICAO,MARCA,MODELO,PVENDA,QUANTIDADE FROM PRODUTOS", conexao); Phrase item1 = new Phrase("Código"); var cel = new PdfPCell(item1); CABECALHO.AddCell(cel); Phrase item2 = new Phrase("Cód. de Barras"); cel = new PdfPCell(item2); CABECALHO.AddCell(cel); Phrase item3 = new Phrase("Descrição"); cel = new PdfPCell(item3); cel.Colspan = 1; CABECALHO.AddCell(cel); Phrase item4 = new Phrase("Marca"); cel = new PdfPCell(item4); CABECALHO.AddCell(cel); Phrase item5 = new Phrase("Modelo"); cel = new PdfPCell(item5); CABECALHO.AddCell(cel); Phrase item6 = new Phrase("Preço de Venda"); cel = new PdfPCell(item6); CABECALHO.AddCell(cel); Phrase item7 = new Phrase("Quantidade"); cel = new PdfPCell(item7); CABECALHO.AddCell(cel); item1 = new Phrase(" "); item1.Font.Size = 2; cel = new PdfPCell(item1); cel.Colspan = 7; cel.BackgroundColor = iTextSharp.text.BaseColor.DARK_GRAY; CABECALHO.AddCell(cel); double pvenda; leitor = selecionafilme.ExecuteReader(); while (leitor.Read() != false) { item1 = new Phrase(leitor["CODIGO"].ToString()); cel = new PdfPCell(item1); CABECALHO.AddCell(cel); item2 = new Phrase(leitor["CBARRAS"].ToString()); cel = new PdfPCell(item2); CABECALHO.AddCell(cel); item3 = new Phrase(leitor["DESCRICAO"].ToString()); cel = new PdfPCell(item3); cel.Colspan = 1; CABECALHO.AddCell(cel); item4 = new Phrase(leitor["MARCA"].ToString()); cel = new PdfPCell(item4); CABECALHO.AddCell(cel); item5 = new Phrase(leitor["MODELO"].ToString()); cel = new PdfPCell(item5); CABECALHO.AddCell(cel); pvenda = double.Parse(leitor["PVENDA"].ToString()); item6 = new Phrase(pvenda.ToString("0.00")); cel = new PdfPCell(item6); CABECALHO.AddCell(cel); item7 = new Phrase(leitor["QUANTIDADE"].ToString()); cel = new PdfPCell(item7); CABECALHO.AddCell(cel); } conexao.Close(); leitor.Close(); item1 = new Phrase(" "); item1.Font.Size = 2; cel = new PdfPCell(item1); cel.Colspan = 7; cel.BackgroundColor = iTextSharp.text.BaseColor.DARK_GRAY; CABECALHO.AddCell(cel); relatorio.Add(CABECALHO); paragrafo = new Paragraph(); paragrafo.Alignment = Element.ALIGN_CENTER; paragrafo.Add(" "); relatorio.Add(paragrafo); paragrafo = new Paragraph(); paragrafo.Alignment = Element.ALIGN_CENTER; paragrafo.Add(" "); relatorio.Add(paragrafo); } } //TEM QUE FECHAR O PDF PARA QUE CONSIGA VIZUALIZAR relatorio.Close(); //APRESENTA O PDF System.Diagnostics.Process.Start(@"C:\Users\defar\Desktop\relatoriopr.pdf"); }
public MemoryStream GeneratePdfTemplate(ExternalPurchaseOrderViewModel viewModel, int clientTimeZoneOffset) { 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, 9); Font small_font = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 8); Font smaller_font = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 7); Font bold_font = FontFactory.GetFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 7); Font bold_font2 = FontFactory.GetFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 8); Font bold_font3 = FontFactory.GetFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 9); Font bold_font4 = FontFactory.GetFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 10); Document document = new Document(PageSize.A5, 25, 25, 25, 25); MemoryStream stream = new MemoryStream(); PdfWriter writer = PdfWriter.GetInstance(document, stream); document.Open(); #region Header PdfPTable tableHeader = new PdfPTable(2); tableHeader.SetWidths(new float[] { 4f, 4f }); PdfPCell cellHeaderContentLeft = new PdfPCell() { Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT }; PdfPCell cellHeaderContentRight = new PdfPCell() { Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_RIGHT }; cellHeaderContentLeft.Phrase = new Phrase("PT. EFRATA RETAILINDO", bold_font4); tableHeader.AddCell(cellHeaderContentLeft); cellHeaderContentRight.Phrase = new Phrase("FM-PB-00-06-009/R1", bold_font); tableHeader.AddCell(cellHeaderContentRight); //cellHeaderContentLeft.Phrase = new Phrase("Head Office: Kelurahan Banaran", bold_font2); //tableHeader.AddCell(cellHeaderContentLeft); //cellHeaderContentRight.Phrase = new Phrase("FM-PB-00-06-009/R1" + "\n" + "Nomor PO: " + viewModel.no, bold_font2); //tableHeader.AddCell(cellHeaderContentRight); //cellHeaderContentRight.Phrase = new Phrase("FM-PB-00-06-009/R1", bold_font2); //tableHeader.AddCell(cellHeaderContentRight); cellHeaderContentLeft.Phrase = new Phrase("Head Office:" + "\n" + "Kelurahan Banaran" + "\n" + "Kecamatan Grogol" + "\n" + "Sukoharjo 57552" + "\n" + "JAWA TENGAH" + "\n" + "Telp. (0271) ) 740888, 719911" + "\n" + "Fax. (0271) ) 735222, 740777", bold_font); tableHeader.AddCell(cellHeaderContentLeft); cellHeaderContentRight.Phrase = new Phrase("Nomor PO: " + viewModel.no, bold_font2); tableHeader.AddCell(cellHeaderContentRight); PdfPCell cellHeader = new PdfPCell(tableHeader); // dont remove tableHeader.ExtendLastRow = false; tableHeader.SpacingAfter = 10f; document.Add(tableHeader); string titleString = "ORDER PEMBELIAN"; bold_font3.SetStyle(Font.UNDERLINE); Paragraph title = new Paragraph(titleString, bold_font3) { Alignment = Element.ALIGN_CENTER }; document.Add(title); bold_font.SetStyle(Font.NORMAL); #endregion #region Identity PdfPTable tableIdentity = new PdfPTable(3); tableIdentity.SetWidths(new float[] { 1.2f, 2.5f, 2.9f }); PdfPCell cellIdentityContentLeft = new PdfPCell() { Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT }; PdfPCell cellIdentityContentRight = new PdfPCell() { Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_RIGHT }; cellIdentityContentLeft.Phrase = new Phrase("Kepada Yth", small_font); tableIdentity.AddCell(cellIdentityContentLeft); cellIdentityContentLeft.Phrase = new Phrase(": " + viewModel.supplier.name, small_font); tableIdentity.AddCell(cellIdentityContentLeft); cellIdentityContentRight.Phrase = new Phrase("Sukoharjo, " + viewModel.orderDate.ToOffset(new TimeSpan(clientTimeZoneOffset, 0, 0)).ToString("dd MMMM yyyy", new CultureInfo("id-ID")), small_font); tableIdentity.AddCell(cellIdentityContentRight); cellIdentityContentLeft.Phrase = new Phrase(" ", small_font); tableIdentity.AddCell(cellIdentityContentLeft); cellIdentityContentLeft.Phrase = new Phrase(" " + "Attn. \n Telp.", small_font); tableIdentity.AddCell(cellIdentityContentLeft); cellIdentityContentRight.Phrase = new Phrase("Mohon di-fax kembali setelah ditandatangani dan distempel perusahaan. Terima Kasih.", small_font); tableIdentity.AddCell(cellIdentityContentRight); //cellIdentityContentLeft.Phrase = new Phrase(" ", normal_font); //tableIdentity.AddCell(cellIdentityContentLeft); //cellIdentityContentLeft.Phrase = new Phrase(" " + "Telp.", normal_font); //tableIdentity.AddCell(cellIdentityContentLeft); //cellIdentityContentRight.Phrase = new Phrase("ditandatangani dan distempel", normal_font); //tableIdentity.AddCell(cellIdentityContentRight); //cellIdentityContentLeft.Phrase = new Phrase(" ", normal_font); //tableIdentity.AddCell(cellIdentityContentLeft); //cellIdentityContentLeft.Phrase = new Phrase(" " + " ", normal_font); //tableIdentity.AddCell(cellIdentityContentLeft); //cellIdentityContentRight.Phrase = new Phrase("perusahaan. Terima Kasih.", normal_font); //tableIdentity.AddCell(cellIdentityContentRight); PdfPCell cellIdentity = new PdfPCell(tableIdentity); // dont remove tableIdentity.ExtendLastRow = false; tableIdentity.SpacingBefore = 5f; document.Add(tableIdentity); #endregion document.Add(new Paragraph("Dengan Hormat,", normal_font) { Alignment = Element.ALIGN_LEFT }); string firstParagraphString = "Yang bertanda tangan di bawah ini, PT. EFRATA RETAILINDO (selanjutnya disebut sebagai pihak Pembeli) dan " + viewModel.supplier.name + "(selanjutnya disebut sebagai pihak Penjual) saling menyetujui untuk mengadaan kontrak jual beli dengan ketentuan sebagai berikut : "; Paragraph firstParagraph = new Paragraph(firstParagraphString, small_font) { Alignment = Element.ALIGN_LEFT }; firstParagraph.SpacingAfter = 10f; document.Add(firstParagraph); #region Items PdfPCell cellCenter = new PdfPCell() { Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE, Padding = 5 }; PdfPCell cellCenter2 = new PdfPCell() { Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE, Padding = 0 }; PdfPCell cellRight = new PdfPCell() { Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_RIGHT, VerticalAlignment = Element.ALIGN_MIDDLE, Padding = 5 }; PdfPCell cellLeft = new PdfPCell() { Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, Padding = 5 }; PdfPCell cellRightMerge = new PdfPCell() { Border = Rectangle.NO_BORDER | Rectangle.NO_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_RIGHT, VerticalAlignment = Element.ALIGN_TOP, Padding = 5 }; PdfPCell cellLeftMerge = new PdfPCell() { Border = Rectangle.NO_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_TOP, Padding = 5 }; PdfPTable tableContent = new PdfPTable(6); tableContent.SetWidths(new float[] { 6.5f, 3f, 1.5f, 3.6f, 1.5f, 4.1f }); cellCenter.Phrase = new Phrase("NAMA DAN JENIS BARANG", bold_font); tableContent.AddCell(cellCenter); cellCenter.Phrase = new Phrase("JUMLAH", bold_font); tableContent.AddCell(cellCenter); cellCenter.Phrase = new Phrase("HARGA SATUAN", bold_font); cellCenter.Colspan = 2; tableContent.AddCell(cellCenter); cellCenter.Phrase = new Phrase("SUB TOTAL", bold_font); cellCenter.Colspan = 2; tableContent.AddCell(cellCenter); double total = 0; //for (int a = 0; a < 20; a++) // coba kalau banyak baris ^_^ foreach (ExternalPurchaseOrderItemViewModel item in viewModel.items) { for (int indexItem = 0; indexItem < item.details.Count; indexItem++) { ExternalPurchaseOrderDetailViewModel detail = item.details[indexItem]; string line1 = detail.product.name + "\n"; string line2 = detail.productRemark + "\n"; string line3 = item.prNo; Paragraph p1 = new Paragraph(); Phrase ph1 = new Phrase(line1, smaller_font); Phrase ph2 = new Phrase(line2, smaller_font); Phrase ph3 = new Phrase(line3, smaller_font); p1.Add(ph1); p1.Add(ph2); p1.Add(ph3); tableContent.AddCell(p1); cellCenter2.Phrase = new Phrase(string.Format("{0:n2}", detail.dealQuantity) + " " + $"{detail.dealUom.unit}", smaller_font); tableContent.AddCell(cellCenter2); cellLeftMerge.Phrase = new Phrase($"{viewModel.currency.code}", smaller_font); tableContent.AddCell(cellLeftMerge); cellRightMerge.Phrase = new Phrase($"{detail.pricePerDealUnit.ToString("N", new CultureInfo("id-ID"))}", smaller_font); tableContent.AddCell(cellRightMerge); double subtotalPrice = detail.pricePerDealUnit * detail.dealQuantity; cellLeftMerge.Phrase = new Phrase($"{viewModel.currency.code}", smaller_font); tableContent.AddCell(cellLeftMerge); cellRightMerge.Phrase = new Phrase($"{subtotalPrice.ToString("N", new CultureInfo("id-ID"))}", smaller_font); tableContent.AddCell(cellRightMerge); total += subtotalPrice; } } cellRight.Colspan = 4; cellRight.Phrase = new Phrase("Total", bold_font); tableContent.AddCell(cellRight); cellLeftMerge.Phrase = new Phrase($"{viewModel.currency.code}", smaller_font); tableContent.AddCell(cellLeftMerge); cellRightMerge.Phrase = new Phrase($"{total.ToString("N", new CultureInfo("id-ID"))}", smaller_font); tableContent.AddCell(cellRightMerge); cellRight.Colspan = 4; //cellRight.Phrase = new Phrase("PPN 11%", bold_font); cellRight.Phrase = new Phrase($"PPN {viewModel.vatRate}%", bold_font); tableContent.AddCell(cellRight); cellLeftMerge.Phrase = new Phrase($"{viewModel.currency.code}", smaller_font); tableContent.AddCell(cellLeftMerge); string ppn = "0.00"; double ppnNominal = 0; if (viewModel.useVat) { //ppnNominal = total * 11 / 100; ppnNominal = total * viewModel.vatRate / 100; ppn = $"{ppnNominal.ToString("N", new CultureInfo("id-ID"))}"; } cellRightMerge.Phrase = new Phrase(ppn, smaller_font); tableContent.AddCell(cellRightMerge); cellRight.Colspan = 4; cellRight.Phrase = new Phrase("Grand Total", bold_font); tableContent.AddCell(cellRight); cellLeftMerge.Phrase = new Phrase($"{viewModel.currency.code}", smaller_font); tableContent.AddCell(cellLeftMerge); cellRightMerge.Phrase = new Phrase($"{(total+ ppnNominal).ToString("N", new CultureInfo("id-ID"))}", smaller_font); tableContent.AddCell(cellRightMerge); PdfPCell cellContent = new PdfPCell(tableContent); // dont remove tableContent.ExtendLastRow = false; tableContent.SpacingAfter = 20f; document.Add(tableContent); #endregion #region Footer PdfPTable tableFooter = new PdfPTable(4); tableFooter.SetWidths(new float[] { 3.3f, 5.5f, 2f, 4.8f }); //PdfPCell cellFooterContentLeft = new PdfPCell() { Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT }; //PdfPCell cellFooterContentRight = new PdfPCell() { Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_RIGHT }; PdfPCell cellFooterContent = new PdfPCell() { Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT }; cellFooterContent.Phrase = new Phrase("Ongkos Kirim", smaller_font); tableFooter.AddCell(cellFooterContent); cellFooterContent.Phrase = new Phrase(": " + viewModel.freightCostBy, smaller_font); tableFooter.AddCell(cellFooterContent); cellFooterContent.Phrase = new Phrase("Delivery", smaller_font); tableFooter.AddCell(cellFooterContent); cellFooterContent.Phrase = new Phrase(": " + (viewModel.deliveryDate.ToOffset(new TimeSpan(clientTimeZoneOffset, 0, 0)).ToString("dd MMMM yyyy", new CultureInfo("id-ID"))), smaller_font); tableFooter.AddCell(cellFooterContent); string duedays = ""; if (Convert.ToInt32(viewModel.paymentDueDays) > 0) { duedays = viewModel.paymentDueDays + " hari setelah terima barang"; } cellFooterContent.Phrase = new Phrase("Pembayaran", smaller_font); tableFooter.AddCell(cellFooterContent); cellFooterContent.Phrase = new Phrase(": " + viewModel.paymentMethod + "\n" + " " + duedays, smaller_font); tableFooter.AddCell(cellFooterContent); cellFooterContent.Phrase = new Phrase("Lain-lain", smaller_font); tableFooter.AddCell(cellFooterContent); cellFooterContent.Phrase = new Phrase(": " + viewModel.remark, smaller_font); tableFooter.AddCell(cellFooterContent); PdfPCell cellFooter = new PdfPCell(tableFooter); // dont remove tableFooter.ExtendLastRow = false; tableContent.SpacingAfter = 20f; document.Add(tableFooter); #endregion #region TableSignature PdfPTable tableSignature = new PdfPTable(2); PdfPCell cellSignatureContent = new PdfPCell() { Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_CENTER }; cellSignatureContent.Phrase = new Phrase("Pembeli\n\n\n\n\n\n\n( " + viewModel.CreatedBy + " )", bold_font); tableSignature.AddCell(cellSignatureContent); cellSignatureContent.Phrase = new Phrase("Menyetujui\n\n\n\n\n\n\n( " + "Adi Nugroho" + " )", bold_font); tableSignature.AddCell(cellSignatureContent); //cellSignatureContent.Phrase = new Phrase("Penjual\n\n\n\n\n\n\n( " + viewModel.supplier.name + " )", bold_font); //tableSignature.AddCell(cellSignatureContent); PdfPCell cellSignature = new PdfPCell(tableSignature); // dont remove tableSignature.ExtendLastRow = false; tableSignature.SpacingBefore = 20f; tableSignature.SpacingAfter = 20f; document.Add(tableSignature); #endregion document.Close(); byte[] byteInfo = stream.ToArray(); stream.Write(byteInfo, 0, byteInfo.Length); stream.Position = 0; return(stream); }
private void xuatThe_xuat_Click(object sender, EventArgs e) { if (xuatThe_ten != null) { try { Document The = new Document(iTextSharp.text.PageSize.HALFLETTER); PdfWriter TheWriter = PdfWriter.GetInstance(The, new FileStream($@"{xuatThe_duongdan.Text + xuatThe_ten.Text}.pdf", FileMode.Create)); System.Drawing.Image img1 = global::QLDG.Properties.Resources.rsz_npl; System.Drawing.Image img2 = global::QLDG.Properties.Resources._121616142_697353817797998_5539481938901508229_n; iTextSharp.text.Image text_img1 = iTextSharp.text.Image.GetInstance(img1, System.Drawing.Imaging.ImageFormat.Png); iTextSharp.text.Image Info_img2 = iTextSharp.text.Image.GetInstance(img2, System.Drawing.Imaging.ImageFormat.Png); Info_img2.SetAbsolutePosition(The.PageSize.Width - 280f - 60f, The.PageSize.Height - 50f - 190f); text_img1.SetAbsolutePosition(The.PageSize.Width - 280f - 60f, The.PageSize.Height - 30f - 75f); // The.Add(text_img); iTextSharp.text.Font f1 = FontFactory.GetFont(iTextSharp.text.Font.FontFamily.TIMES_ROMAN.ToString(), 20, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLUE); string exeFile = (new System.Uri(Assembly.GetEntryAssembly().CodeBase)).AbsolutePath; string exeDir = Path.GetDirectoryName(exeFile); string fullPath0 = Path.Combine(exeDir, @"VietFontsWeb1_ttf\vuTimesBold.ttf"); string fullPath1 = Path.Combine(exeDir, @"VietFontsWeb1_ttf\vuTimes.ttf"); BaseFont bf0 = BaseFont.CreateFont(fullPath0, BaseFont.IDENTITY_H, BaseFont.EMBEDDED); BaseFont bf1 = BaseFont.CreateFont(fullPath1, BaseFont.IDENTITY_H, BaseFont.EMBEDDED); iTextSharp.text.Font f2 = new iTextSharp.text.Font(bf0, 15, iTextSharp.text.Font.ITALIC, iTextSharp.text.BaseColor.RED); iTextSharp.text.Font f3 = new iTextSharp.text.Font(bf1, 10, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK); iTextSharp.text.Font f4 = new iTextSharp.text.Font(bf1, 8, iTextSharp.text.Font.ITALIC, iTextSharp.text.BaseColor.BLUE); /*Paragraph p1 = new Paragraph(" LM_PROJECT.EC", f1); * Paragraph p2 = new Paragraph($" Mã số: {MS}", f3); * Paragraph p3 = new Paragraph($" Họ và tên: {Ten}", f3); * Paragraph p4 = new Paragraph($" Ngày sinh: {NgaySinh}", f3); * Paragraph p5 = new Paragraph($" Ngày lập thẻ: {NgayLapThe}", f3); * Paragraph p6 = new Paragraph($" Loai: {Loai}", f3); * Paragraph Enter=new Paragraph(" "); * * p1.Alignment = Element.ALIGN_CENTER; * p2.Alignment = Element.LISTITEM; * p3.Alignment = Element.LISTITEM; * p4.Alignment = Element.LISTITEM; * p5.Alignment = Element.LISTITEM; * p6.Alignment = Element.LISTITEM; * * * The.Add(p1); * The.Add(text_img1); * * The.Add(Info_img2); * The.Add(Enter); * The.Add(p2); * The.Add(p3); * The.Add(p4); * The.Add(p5); * The.Add(p6); */ // iTextSharp.text.Font f = new iTextSharp.text.Font(); PdfPTable table = new PdfPTable(1); table.DefaultCell.Padding = 3; table.DefaultCell.MinimumHeight = 20; table.WidthPercentage = 100; table.HorizontalAlignment = Element.ALIGN_CENTER; table.DefaultCell.BorderWidth = 1; PdfPCell cellHoTen = new PdfPCell(new Phrase($" ooo000ooo", f3)); cellHoTen.BackgroundColor = new BaseColor(195, 195, 195); Paragraph p1 = new Paragraph(" LM-PROJECT.EC\n", f1); p1.Alignment = Element.ALIGN_CENTER; Paragraph Enter = new Paragraph(" \n"); Paragraph p7 = new Paragraph($" THẺ ĐỘC GIẢ - {MS}\n", f2); Paragraph p8 = new Paragraph($" (Thẻ có giá trị sử dụng 180 ngày kể từ ngày lập thẻ)\n", f4); p7.Alignment = Element.ALIGN_CENTER; p8.Alignment = Element.ALIGN_CENTER; table.AddCell(cellHoTen); p1.Add(p7); p1.Add(p8); Paragraph p2 = new Paragraph($"\n\n Họ và tên: {Ten}\n\n" + $" Loại độc giả: {Loai}\n\n" + $" Ngày sinh: {NgaySinh}\n\n" + $" Địa chỉ: {DiaChi}\n\n" + $" Email: {Email}\n\n" + $" Ngày lập thẻ : {NgayLapThe}\n\n" + $" Người lập thẻ : {NgLap}\n\n", f3); p1.Add(p2); p1.PaddingTop = 10; table.AddCell(p1); The.Open(); //The.Add(p1); The.Add(text_img1); //The.Add(p7); //The.Add(p8); //The.Add(Enter); The.Add(table); The.Add(Info_img2); The.Close(); TheWriter.Close(); MessageBox.Show("Thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch { MessageBox.Show("Thất bại", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error); } } else { MessageBox.Show("Thất bại", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
private void criarPDF(string path) { Document doc = new Document(PageSize.A4); doc.SetMargins(40, 40, 40, 80); doc.AddCreationDate(); PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(path, FileMode.Create)); doc.Open(); iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(@"C:\Users\GONIME\source\repos\Econobuy\Econobuy.Views\Repositório\Logo.png"); img.ScaleAbsolute(50, 50); img.Alignment = Element.ALIGN_TOP; doc.Add(img); Paragraph titulo = new Paragraph(); titulo.Font = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 40); titulo.Alignment = Element.ALIGN_CENTER; titulo.Add("\n\nRelatório Econobuy\n\n\n"); doc.Add(titulo); Paragraph subtitulo = new Paragraph(); subtitulo.Font = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 30); subtitulo.Alignment = Element.ALIGN_CENTER; if (content == 1 && type == 0) { subtitulo.Add("Relatório de produtos cadastrados\n\n\n\n\n"); } else if (content == 1 && type == 1) { subtitulo.Add("Relatório de produtos Vendidos\n\n\n\n\n"); } else if (content == 1 && type == 2) { subtitulo.Add("Relatório de produtos a serem entregues\n\n\n\n\n"); } else if (content == 2 && type == 0) { subtitulo.Add("Relatório de pedidos em aguardo\n\n\n\n\n"); } else if (content == 2 && type == 1) { subtitulo.Add("Relatório de pedidos entregues\n\n\n\n\n"); } else if (content == 2 && type == 2) { subtitulo.Add("Relatório de todos os pedidos\n\n\n\n\n"); } else if (content == 3 && type == 0) { subtitulo.Add("Relatório de clientes aguardando aprovação\n\n\n\n\n"); } else if (content == 3 && type == 1) { subtitulo.Add("Relatório de clientes com pedido entregue\n\n\n\n\n"); } else if (content == 3 && type == 0) { subtitulo.Add("Relatório de todos os clientes\n\n\n\n\n"); } doc.Add(subtitulo); PdfPTable table = new PdfPTable(dt.Columns.Count); table.WidthPercentage = 100; PdfPCell cell = new PdfPCell(new Phrase("Products")); iTextSharp.text.Font fnt = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 8); cell.Colspan = dt.Columns.Count; foreach (DataColumn c in dt.Columns) { table.AddCell(new Phrase(c.ColumnName, fnt)); } foreach (DataRow r in dt.Rows) { for (int i = 0; i <= cell.Colspan - 1; i++) { table.AddCell(new Phrase(r[i].ToString(), fnt)); } } doc.Add(table); PrintDialog dialogPrint = new PrintDialog(); doc.Close(); }
protected void btnExportar_Click(object sender, EventArgs e) { PdfPTable pdfTable = new PdfPTable(gvPlanes.HeaderRow.Cells.Count); foreach (TableCell headerCell in gvPlanes.HeaderRow.Cells) { PdfPCell pdfCell = new PdfPCell(new Phrase(headerCell.Text)); pdfTable.AddCell(pdfCell); } foreach (GridViewRow gridViewRow in gvPlanes.Rows) { foreach (TableCell tableCell in gridViewRow.Cells) { PdfPCell pdfCell = new PdfPCell(new Phrase(tableCell.Text)); pdfTable.AddCell(pdfCell); } } Document pdfDoc = new Document(PageSize.A4, 20f, 20f, 20f, 20f); PdfWriter.GetInstance(pdfDoc, Response.OutputStream); pdfDoc.Open(); //Inserto titulo Paragraph paragraph = new Paragraph(); //se crea el parrafo Paragraph separador = new Paragraph(); separador.Add("\n\n"); paragraph.Font = new iTextSharp.text.Font(FontFactory.GetFont("Arial", 25, BaseColor.BLACK)); paragraph.Alignment = Element.ALIGN_CENTER; paragraph.Add("Reporte de Planes"); //Inserto titulo de reporte paragraph.Add("\n\n"); paragraph.Font = new iTextSharp.text.Font(FontFactory.GetFont("Arial", 10, BaseColor.BLACK)); paragraph.Alignment = Element.ALIGN_CENTER; paragraph.Add(this.ListadoTittleLabel.Text.ToString()); // Creamos la imagen y le ajustamos el tamaño iTextSharp.text.Image imagen = iTextSharp.text.Image.GetInstance(@"C:\Users\Nicolás\Documents\UtnRosario.png"); imagen.BorderWidth = 0; imagen.Alignment = Element.ALIGN_RIGHT; float percentage = 0.0f; percentage = 150 / imagen.Width; imagen.ScalePercent(percentage * 100); // Insertamos la imagen en el documento pdfDoc.Add(imagen); pdfDoc.Add(separador); pdfDoc.Add(paragraph); pdfDoc.Add(separador); pdfDoc.Add(pdfTable); pdfDoc.Close(); Response.ContentType = "application/pdf"; Response.AppendHeader("content-disposition", "attachment;filename=ReportePlan.pdf"); Response.Write(pdfDoc); Response.Flush(); Response.End(); }
public MemoryStream GeneratePDF(AsInfoViewModel asInfoViewModel) { System.IO.MemoryStream fs = new MemoryStream(); Document document = new Document(); document.SetPageSize(iTextSharp.text.PageSize.A4); PdfWriter writer = PdfWriter.GetInstance(document, fs); document.Open(); var rootPath = _hostingEnvironment.WebRootPath; //Korean Font var gulim = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "ARIALUNI.TTF"); //Report Header iTextSharp.text.pdf.BaseFont bfntHead = iTextSharp.text.pdf.BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); //iTextSharp.text.Font fntHead = new iTextSharp.text.Font(bfntHead, 16, 1, iTextSharp.text.BaseColor.GRAY); BaseFont fntHead = BaseFont.CreateFont(gulim, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); Font f = new Font(fntHead, 12, Font.NORMAL); Paragraph prgHeading = new Paragraph(); prgHeading.Alignment = Element.ALIGN_CENTER; prgHeading.Add(new Chunk("A/S 신청안내", f)); 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", f)); //Write the table PdfPTable table = new PdfPTable(2); ////Table header //BaseFont btnColumnHeader = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); //Font fntColumnHeader = new Font(btnColumnHeader, 10, 1, iTextSharp.text.BaseColor.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 table.AddCell(new Phrase("업체명", f)); table.AddCell(new Phrase(asInfoViewModel.CompanyName, f)); table.AddCell(new Phrase("담당자", f)); table.AddCell(new Phrase(asInfoViewModel.Manager, f)); table.AddCell(new Phrase("연락처", f)); table.AddCell(new Phrase(asInfoViewModel.Contact, f)); table.AddCell(new Phrase("FAX", f)); table.AddCell(new Phrase(asInfoViewModel.Fax, f)); table.AddCell(new Phrase("휴대전화", f)); table.AddCell(new Phrase(asInfoViewModel.CellPhone, f)); table.AddCell(new Phrase("이메일", f)); table.AddCell(new Phrase(asInfoViewModel.Email, f)); table.AddCell(new Phrase("제품명", f)); table.AddCell(new Phrase(asInfoViewModel.ProductName, f)); table.AddCell(new Phrase("Serial No.", f)); table.AddCell(new Phrase(asInfoViewModel.SerialNumber, f)); table.AddCell(new Phrase("증상", f)); table.AddCell(new Phrase(asInfoViewModel.Symptom, f)); table.AddCell(new Phrase("내용", f)); table.AddCell(new Phrase(asInfoViewModel.Content, f)); document.Add(table); document.Close(); //writer.Close(); //fs.Close(); return(fs); }
private void btn_excluirHorario_Click(object sender, EventArgs e) { string nomeArquino = Globais.caminho + @"\turmas.pdf"; FileStream arquivoPDF = new FileStream(nomeArquino, FileMode.Create); Document doc = new Document(PageSize.A4); PdfWriter escritorPDF = PdfWriter.GetInstance(doc, arquivoPDF); //Inserindo uma imagem iTextSharp.text.Image logo = iTextSharp.text.Image.GetInstance(Globais.caminho + @"\logo1.PNG"); logo.ScaleToFit(112, 96); /* * um desses * logo.Alignment = Element.ALIGN_LEFT; * ou */ logo.SetAbsolutePosition(35, 720f); // X , -Y(com 0 ele fica na base da pagina) //Inserindo uma imagem*/ string dados = ""; Paragraph paragrafo1 = new Paragraph(dados, new iTextSharp.text.Font(iTextSharp.text.Font.NORMAL, 25, (int)System.Drawing.FontStyle.Bold)); paragrafo1.Alignment = Element.ALIGN_CENTER; paragrafo1.Add("Estudo PDF\n"); paragrafo1.Font = new iTextSharp.text.Font(iTextSharp.text.Font.NORMAL, 14, (int)System.Drawing.FontStyle.Italic); paragrafo1.Add("Curso em C#\n"); string texto = "\nRelatório de turmas"; paragrafo1.Font = new iTextSharp.text.Font(iTextSharp.text.Font.NORMAL, 20, (int)System.Drawing.FontStyle.Bold); paragrafo1.Add(texto + "\n\n"); Paragraph paragrafo2 = new Paragraph(dados, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 25, (int)System.Drawing.FontStyle.Bold)); paragrafo2.Alignment = Element.ALIGN_LEFT; paragrafo2.Add("\n\nParagrago 2\n"); string texto2 = "esse é o texto do segundo aparagrafo\n Loollllaaaaaaaaaaaaaaaaaaaaaaaaaa.\n\n"; paragrafo2.Font = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12, (int)System.Drawing.FontStyle.Italic); paragrafo2.Add(texto2 + "\n"); //Inserindo Tabela PdfPTable tabela = new PdfPTable(3);//3Colunas tabela.DefaultCell.FixedHeight = 20; PdfPCell celula1 = new PdfPCell(); celula1.Colspan = 3; //Linha 1 mescleda // celula1.AddElement(logo); celula1.HorizontalAlignment = Element.ALIGN_CENTER; celula1.VerticalAlignment = Element.ALIGN_CENTER; celula1.HorizontalAlignment = Element.ALIGN_CENTER; tabela.AddCell(celula1); tabela.AddCell("ID Turma"); tabela.AddCell("Turma"); tabela.AddCell("Horário"); string vquery = @"SELECT tbt.N_IDTURMA as 'ID' ,tbt.T_DSCTURMA as 'Turma',tbh.T_DSCHORARIO as 'Horário da turma' FROM tb_turmas as tbt INNER JOIN tb_horarios as tbh on tbh.N_IDHORARIO = tbt.N_IDHORARIO"; DataTable dtTurma = Banco.dql(vquery); for (int i = 0; i < dtTurma.Rows.Count; i++) { tabela.AddCell(dtTurma.Rows[i].Field <Int64>("ID").ToString()); tabela.AddCell(dtTurma.Rows[i].Field <string>("Turma")); tabela.AddCell(dtTurma.Rows[i].Field <string>("Horário da turma")); } PdfPCell celula2 = new PdfPCell(new Phrase("Tabela 2 AQUI!")); celula2.Colspan = 3; //Linha 1 mescla celula2.FixedHeight = 40; celula2.Rotation = 0; celula2.HorizontalAlignment = Element.ALIGN_CENTER; celula2.VerticalAlignment = Element.ALIGN_MIDDLE; // tabela.AddCell(celula2); doc.Open(); doc.Add(logo); doc.Add(paragrafo1); doc.Add(tabela); // doc.Add(paragrafo2); doc.Close(); DialogResult res = MessageBox.Show("Desejsa abrir o Relatório", "Relatório", MessageBoxButtons.YesNo); if (res == DialogResult.Yes) { System.Diagnostics.Process.Start(Globais.caminho + @"\turmas.pdf"); } }
static Document CreateDocument(Result result) { // Create a new MigraDoc document Document document = new Document(); #region Introduction Section Section introductionSection = document.AddSection(); // Page Title Paragraph titleParagraph = introductionSection.AddParagraph(); titleParagraph.Format.Alignment = ParagraphAlignment.Center; titleParagraph.AddFormattedText(Properties.Resources.ProductDescription, StyleLibrary.BlackTitleFont); titleParagraph.AddFormattedText(" (" + Properties.Resources.ProductName + ")", StyleLibrary.BlackTitleFont); // Introductory paragraph Title Paragraph introParagraphTitle = introductionSection.AddParagraph(); introParagraphTitle.AddLineBreak(); introParagraphTitle.AddLineBreak(); introParagraphTitle.AddFormattedText("Introduction", StyleLibrary.HeadingFont); // Introductory paragraph Paragraph introParagraph = introductionSection.AddParagraph(); introParagraph.AddLineBreak(); introParagraph.AddFormattedText("VIQET is an easy to use no-reference photo quality evaluation tool. In order to perform photo quality evaluation, VIQET requires a set of photos " + "from a test device. It computes an overall image MOS score for a device based on the individual computed photo qualities of each image in the set. " + "The overall MOS is computed based on a number of features extracted from each image. The mapping from extracted features to MOS is based on a " + "psychophysics study that was conducted to create a large dataset of photos and associated subjective mean opinion ratings. The study was used to learn " + "a mapping from features to scores. The predicted quality score falls in the range of 1 to 5, where 1 corresponds to a low quality score and 5 corresponds to excellent quality", StyleLibrary.TextFont); Paragraph overallParagraphTitle = introductionSection.AddParagraph(); overallParagraphTitle.AddLineBreak(); overallParagraphTitle.AddLineBreak(); overallParagraphTitle.AddFormattedText("Test Results", StyleLibrary.HeadingFont); // Overall Scores Paragraph overallScoreTitle = introductionSection.AddParagraph(); overallScoreTitle.AddLineBreak(); overallScoreTitle.AddFormattedText("Device Name: " + result.Name, StyleLibrary.TextFont); overallScoreTitle.AddLineBreak(); overallScoreTitle.AddFormattedText("Total number of photos: " + result.PhotoList.Count, StyleLibrary.TextFont); overallScoreTitle.AddLineBreak(); overallScoreTitle.AddFormattedText("Tool Version: " + Properties.Resources.VersionName + " " + Constants.Version, StyleLibrary.TextFont); FeatureDetail overallMOSDetail = result.GetOverallMOS(); string overallMOS = double.IsNaN(overallMOSDetail.Value) ? "N/A" : overallMOSDetail.Value.ToString("0.0") + " +/-" + overallMOSDetail.StandardError.ToString("0.0"); overallScoreTitle.AddLineBreak(); overallScoreTitle.AddLineBreak(); overallScoreTitle.AddFormattedText("Overall Score: " + overallMOS, StyleLibrary.HeadingFont); #endregion #region Summary for Categories // Categories Summary Section Section categoriesSummarySection = document.AddSection(); // Introductory paragraph Paragraph categoriesSummaryParagraphTitle = categoriesSummarySection.AddParagraph(); categoriesSummaryParagraphTitle.AddFormattedText("Photo Category Results", StyleLibrary.HeadingFont); foreach (Category outputCategory in result.outputCategoryList) { Paragraph categoriesSummaryParagraph = categoriesSummarySection.AddParagraph(); categoriesSummaryParagraph.AddLineBreak(); categoriesSummaryParagraph.AddLineBreak(); categoriesSummaryParagraph.AddFormattedText("Category Name: " + outputCategory.Name, StyleLibrary.TextFontBold); categoriesSummaryParagraph.AddLineBreak(); foreach (FeatureDetail featureDetail in outputCategory.FeatureDetails) { if (featureDetail.DisplayPreference == Constants.DisplayPreference.RESULT_PAGE || featureDetail.DisplayPreference == Constants.DisplayPreference.RESULT_AND_DETAIL_PAGE) { categoriesSummaryParagraph.AddLineBreak(); if (outputCategory.MOSValue.Equals(Properties.Resources.NA)) { categoriesSummaryParagraph.AddFormattedText(featureDetail.ParameterName + ": " + Properties.Resources.NA, StyleLibrary.TextFont); } else { categoriesSummaryParagraph.AddFormattedText(featureDetail.ParameterName + ": " + featureDetail.Value.ToString("0.00") + " +/- " + featureDetail.StandardError.ToString("0.00"), StyleLibrary.TextFont); } } } } #endregion #region Photo Details Section foreach (Category category in result.outputCategoryList) { bool firstLine = true; foreach (Photo photo in category.PhotoList) { // Category Details Section Section categoryDetailsSection = document.AddSection(); if (firstLine) { // Introductory paragraph Paragraph categoryDetailsParagraphTitle = categoryDetailsSection.AddParagraph(); categoryDetailsParagraphTitle.AddFormattedText("Photos in " + category.Name + " Category (" + category.PhotoList.Count + " photos)", StyleLibrary.HeadingFont); firstLine = false; } // Introductory paragraph Paragraph paragraphTitle = categoryDetailsSection.AddParagraph(); paragraphTitle.AddLineBreak(); paragraphTitle.AddFormattedText("Details for " + photo.Filename, StyleLibrary.TextFontBold); paragraphTitle.AddLineBreak(); paragraphTitle.AddLineBreak(); //Add the source photo Image sourceImage = new Image(photo.SourceFilePath); sourceImage.Height = 200; sourceImage.Width = 400; Paragraph sourceImageParagraph = categoryDetailsSection.AddParagraph(); sourceImageParagraph.Format.Alignment = ParagraphAlignment.Center; sourceImageParagraph.Add(sourceImage); sourceImageParagraph.AddLineBreak(); sourceImageParagraph.AddFormattedText("Source Photo", StyleLibrary.TextFont); sourceImageParagraph.AddLineBreak(); sourceImageParagraph.AddLineBreak(); //Table with values for this photo Table photoDetailsTable = categoryDetailsSection.AddTable(); Column photoParameterColumn = photoDetailsTable.AddColumn(Unit.FromCentimeter(6)); photoParameterColumn.Format.Alignment = ParagraphAlignment.Left; Column photoValueColumn = photoDetailsTable.AddColumn(Unit.FromCentimeter(3)); photoValueColumn.Format.Alignment = ParagraphAlignment.Right; //Add Header Row Row photoHeaderRow = photoDetailsTable.AddRow(); photoHeaderRow.Cells[0].AddParagraph().AddFormattedText("Parameter", StyleLibrary.TextFontBold); photoHeaderRow.Cells[1].AddParagraph().AddFormattedText("Value", StyleLibrary.TextFontBold); //Add the details foreach (PhotoDetail photoDetail in photo.PhotoDetails) { if (photoDetail.DisplayPreference == Constants.DisplayPreference.DETAIL_PAGE || photoDetail.DisplayPreference == Constants.DisplayPreference.RESULT_AND_DETAIL_PAGE) { Row detailRow = photoDetailsTable.AddRow(); detailRow.Cells[0].AddParagraph().AddFormattedText(photoDetail.ParameterName, StyleLibrary.TextFont); detailRow.Cells[1].AddParagraph().AddFormattedText(photoDetail.Value.ToString("0.00"), StyleLibrary.TextFont); } } //Add the visualization images Section visualizationSection = document.AddSection(); foreach (VisualizationImage visualizationImage in photo.VisualizationImages) { Image image = new Image(visualizationImage.FilePath); image.Height = 200; image.Width = 400; Paragraph visualizationImageParagraph = visualizationSection.AddParagraph(); visualizationImageParagraph.AddLineBreak(); visualizationImageParagraph.Format.Alignment = ParagraphAlignment.Center; visualizationImageParagraph.Add(image); visualizationImageParagraph.AddLineBreak(); visualizationImageParagraph.AddFormattedText(visualizationImage.Visualization, StyleLibrary.TextFont); } } } #endregion return(document); }
/** * Adds currentContent list to a paragraph element. If addNewLines is true a * Paragraph object is returned, else a NoNewLineParagraph object is * returned. * * @param currentContent IList<IElement> of the current elements to be added. * @param addNewLines bool to declare which paragraph element should be * returned, true if new line should be added or not. * @param applyCSS true if CSS should be applied on the paragraph * @param tag the relevant tag * @return a List with paragraphs */ public virtual IList <IElement> CurrentContentToParagraph(IList <IElement> currentContent, bool addNewLines, bool applyCSS, Tag tag, IWorkerContext ctx) { try { int direction = GetRunDirection(tag); IList <IElement> list = new List <IElement>(); if (currentContent.Count > 0) { if (addNewLines) { Paragraph p = CreateParagraph(); p.MultipliedLeading = 1.2f; foreach (IElement e in currentContent) { if (e is LineSeparator) { try { HtmlPipelineContext htmlPipelineContext = GetHtmlPipelineContext(ctx); Chunk newLine = (Chunk)GetCssAppliers().Apply(new Chunk(Chunk.NEWLINE), tag, htmlPipelineContext); p.Add(newLine); } catch (NoCustomContextException exc) { throw new RuntimeWorkerException( LocaleMessages.GetInstance().GetMessage(LocaleMessages.NO_CUSTOM_CONTEXT), exc); } } p.Add(e); } if (p.Trim()) { if (applyCSS) { p = (Paragraph)GetCssAppliers().Apply(p, tag, GetHtmlPipelineContext(ctx)); } if (direction.Equals(PdfWriter.RUN_DIRECTION_RTL)) { DoRtlIndentCorrections(p); InvertTextAlignForParagraph(p); } list.Add(p); } } else { NoNewLineParagraph p = new NoNewLineParagraph(float.NaN); p.MultipliedLeading = 1.2f; foreach (IElement e in currentContent) { UpdateParagraphFontIfNeeded(p, e); p.Add(e); } p = (NoNewLineParagraph)GetCssAppliers().Apply(p, tag, GetHtmlPipelineContext(ctx)); if (direction.Equals(PdfWriter.RUN_DIRECTION_RTL)) { DoRtlIndentCorrections(p); InvertTextAlignForParagraph(p); } list.Add(p); } } return(list); } catch (NoCustomContextException e) { throw new RuntimeWorkerException( LocaleMessages.GetInstance().GetMessage(LocaleMessages.NO_CUSTOM_CONTEXT), e); } }
private void bgworker_DoWork(object sender, DoWorkEventArgs e) { String query = "", empid = "", date_from = "", date_to = "", pay_code = "", table = "hr_other_earnings_files", filename = "", code = "", col = "", val = "", date_in = ""; DataTable pay_period = null; Double total_earnings = 0.00; query = "SELECT empid, firstname, lastname FROM rssys.hr_employee"; cbo_employee.Invoke(new Action(() => { if (cbo_employee.SelectedIndex != -1) { empid = cbo_employee.SelectedValue.ToString(); query += " WHERE empid='" + empid + "'"; } })); query += " ORDER BY empid ASC"; DataTable employees = db.QueryBySQLCode(query); cbo_payollperiod.Invoke(new Action(() => { pay_code = cbo_payollperiod.SelectedValue.ToString(); })); pay_period = get_date(pay_code); if (pay_period.Rows.Count > 0) { date_from = gm.toDateString(pay_period.Rows[0]["date_from"].ToString(), "yyyy-MM-dd"); date_to = gm.toDateString(pay_period.Rows[0]["date_to"].ToString(), "yyyy-MM-dd"); } filename = RandomString(5) + "_" + DateTime.Now.ToString("yyyy-MM-dd"); filename += ".pdf"; //System.IO.FileStream fs = new FileStream("\\\\RIGHTAPPS\\RightApps\\Eastland\\payroll_reports\\other_earnings\\" + filename, FileMode.Create); System.IO.FileStream fs = new FileStream(fileloc_dtr + "\\ViewController\\RPT\\Payroll\\other_earnings\\" + filename, FileMode.Create); Document document = new Document(PageSize.LEGAL, 25, 25, 30, 30); PdfWriter.GetInstance(document, fs); document.Open(); BaseFont bf = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); iTextSharp.text.Font font = new iTextSharp.text.Font(bf, 9, iTextSharp.text.Font.NORMAL); Paragraph paragraph = new Paragraph(); paragraph.Alignment = Element.ALIGN_CENTER; paragraph.Font = FontFactory.GetFont("Arial", 12); paragraph.SetLeading(1, 1); paragraph.Add("OTHER EARNINGS/INCOME SUMMARY"); Phrase line_break = new Phrase("\n"); document.Add(paragraph); document.Add(line_break); Paragraph paragraph_2 = new Paragraph(); paragraph_2.Alignment = Element.ALIGN_CENTER; paragraph_2.Font = FontFactory.GetFont("Arial", 12); paragraph_2.SetLeading(1, 1); paragraph_2.Add("For the payroll period " + date_from + " to " + date_to); Phrase line_break_2 = new Phrase("\n"); document.Add(paragraph_2); document.Add(line_break_2); PdfPTable t = new PdfPTable(1); float[] widths = new float[] { 100 }; t.WidthPercentage = 100; t.SetWidths(widths); PdfPTable dis_earnings = new PdfPTable(2); float[] _w2 = new float[] { 50, 50 }; dis_earnings.SetWidths(_w2); foreach (DataRow _employees in employees.Rows) { total_earnings = 0.00; String fname = _employees["firstname"].ToString(); String lname = _employees["lastname"].ToString(); String empno = _employees["empid"].ToString(); try { DataTable has_earnings = db.QueryBySQLCode("SELECT emp_no FROM rssys.hr_earning_entry WHERE emp_no = '" + empno + "'"); if (has_earnings != null && has_earnings.Rows.Count > 0) { dis_earnings.AddCell(new PdfPCell(new Paragraph(fname + " " + lname)) { Colspan = 2, Border = 2 }); DataTable hoe = db.QueryBySQLCode("SELECT DISTINCT(oe.code) as code,oe.description FROM rssys.hr_earning_entry ee LEFT JOIN rssys.hr_other_earnings oe ON oe.code = ee.earning_code WHERE ee.emp_no = '" + empno + "'"); foreach (DataRow _hoe in hoe.Rows) { dis_earnings.AddCell(new PdfPCell(new Paragraph(_hoe["description"].ToString())) { PaddingLeft = 30f, Colspan = 2, Border = 0 }); DataTable hee = db.QueryBySQLCode("SELECT * FROM rssys.hr_earning_entry WHERE earning_code = '" + _hoe["code"].ToString() + "' AND payroll_period = '" + pay_code + "' AND emp_no = '" + empno + "'"); foreach (DataRow _hee in hee.Rows) { dis_earnings.AddCell(new PdfPCell(new Paragraph(_hee["amount"].ToString())) { PaddingLeft = 40f, Colspan = 2, Border = 0 }); total_earnings += Convert.ToDouble(_hee["amount"].ToString()); } } dis_earnings.AddCell(new PdfPCell(new Paragraph("Total Earnings : " + total_earnings.ToString("0.00"))) { Colspan = 2, Border = 0 }); } }catch (Exception ex) { MessageBox.Show(ex.Message); } } document.Add(dis_earnings); document.Add(t); document.Close(); code = db.get_pk("earning_id"); col = "earning_id,filename,date_added"; val = "'" + code + "','" + filename + "','" + DateTime.Now.ToShortDateString() + "'"; if (db.InsertOnTable(table, col, val)) { db.set_pkm99("earning_id", db.get_nextincrementlimitchar(code, 8)); //changes from 'hr_empid' MessageBox.Show("New Other Earnings Summary added."); } else { MessageBox.Show("Failed on saving."); } pic_loading.Invoke(new Action(() => { pic_loading.Visible = false; btn_submit.Enabled = true; })); display_list(); }
public void imprimir(List <Cliente> lista) { Document doc = new Document(); PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(Application.StartupPath + @"\ListadoDeClientes.pdf", FileMode.Create)); doc.Open(); Font _standardFont = new Font(Font.FontFamily.HELVETICA, 10, iTextSharp.text.Font.NORMAL, BaseColor.BLACK); Font _standardFont2 = new Font(Font.FontFamily.HELVETICA, 10, iTextSharp.text.Font.NORMAL, BaseColor.WHITE); Paragraph salto = new Paragraph("\n"); doc.Add(salto); PdfPTable tableHeader = new PdfPTable(2); tableHeader.WidthPercentage = 100; PdfPCell cell = new PdfPCell(new Phrase("Bigons hnos")); cell.Border = 0; cell.BorderWidthBottom = 0.5f; cell.HorizontalAlignment = 0; PdfPCell cell1 = new PdfPCell(new Phrase(DateTime.Now.ToString())); cell1.Border = 0; cell1.BorderWidthBottom = 0.5f; cell1.HorizontalAlignment = 2; tableHeader.AddCell(cell); tableHeader.AddCell(cell1); doc.Add(tableHeader); doc.Add(salto); doc.Add(salto); Paragraph title = new Paragraph(); title.Font = FontFactory.GetFont(FontFactory.TIMES, 24f); title.Add("Listado de clientes"); title.Alignment = 1; doc.Add(title); PdfPTable tblPrueba = new PdfPTable(4); tblPrueba.WidthPercentage = 90; PdfPCell clDniHeader = new PdfPCell(new Phrase("Dni", _standardFont2)); clDniHeader.BorderWidth = 0; clDniHeader.BorderWidthBottom = 0.75f; clDniHeader.BackgroundColor = BaseColor.GRAY; PdfPCell clApellidoHeader = new PdfPCell(new Phrase("Apellido", _standardFont2)); clApellidoHeader.BorderWidth = 0; clApellidoHeader.BorderWidthBottom = 0.75f; clApellidoHeader.BackgroundColor = BaseColor.GRAY; PdfPCell clNombreHeader = new PdfPCell(new Phrase("Nombre", _standardFont2)); clNombreHeader.BorderWidth = 0; clNombreHeader.BorderWidthBottom = 0.75f; clNombreHeader.BackgroundColor = BaseColor.GRAY; PdfPCell clTelefonoHeader = new PdfPCell(new Phrase("Telefono", _standardFont2)); clTelefonoHeader.BorderWidth = 0; clTelefonoHeader.BorderWidthBottom = 0.75f; clTelefonoHeader.BackgroundColor = BaseColor.GRAY; // Añadimos las celdas a la tabla tblPrueba.AddCell(clDniHeader); tblPrueba.AddCell(clApellidoHeader); tblPrueba.AddCell(clNombreHeader); tblPrueba.AddCell(clTelefonoHeader); foreach (Cliente unCliente in lista) { PdfPCell clDni = new PdfPCell(new Phrase(unCliente.Dni, _standardFont)); clDni.BorderWidth = 0; PdfPCell clApellido = new PdfPCell(new Phrase(unCliente.Apellido, _standardFont)); clApellido.BorderWidth = 0; PdfPCell clNombre = new PdfPCell(new Phrase(unCliente.Nombre, _standardFont)); clNombre.BorderWidth = 0; PdfPCell clTel = new PdfPCell(new Phrase(unCliente.Telefonos[0].Numero, _standardFont)); clTel.BorderWidth = 0; // Añadimos las celdas a la tabla tblPrueba.AddCell(clDni); tblPrueba.AddCell(clApellido); tblPrueba.AddCell(clNombre); tblPrueba.AddCell(clTel); } doc.Add(new Paragraph("\n")); doc.Add(tblPrueba); doc.Close(); writer.Close(); System.Diagnostics.Process.Start(Application.StartupPath + @"\ListadoDeClientes.pdf"); }
private void ExportDataTableToPdf(DataTable dtbl, String pdfPath, string header) { try { FileStream fs = new FileStream(pdfPath, FileMode.Create, FileAccess.Write, FileShare.None); Document document = new Document(); document.SetPageSize(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, iTextSharp.text.BaseColor.GRAY); Paragraph prgHeading = new Paragraph(); prgHeading.Alignment = Element.ALIGN_CENTER; prgHeading.Add(new Chunk(header.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, BaseColor.GRAY); prgAuthor.Alignment = Element.ALIGN_LEFT; prgAuthor.Add(new Chunk("Fecha de reporte: " + DateTime.Now.ToShortDateString(), fntAuthor)); document.Add(prgAuthor); //Img iTextSharp.text.Image logo = iTextSharp.text.Image.GetInstance(@"C:\Users\orell\Desktop\Actividades 1er Semestre 2018\Portafolio\Portafolio web\PortafolioNet\PortafolioNet.View\images\Logo.png"); logo.ScaleAbsoluteHeight(50); logo.ScaleAbsoluteWidth(180); logo.Alignment = Element.ALIGN_RIGHT; document.Add(logo); //Separador de Linea. Paragraph p = new Paragraph(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(0.0F, 100.0F, BaseColor.BLACK, Element.ALIGN_LEFT, 0.0F))); document.Add(p); document.Add(new Chunk("\n", fntHead)); //EScribir la tabla: PdfPTable table = new PdfPTable(dtbl.Columns.Count); //Header de tabla. BaseFont btnColumnHeader = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); Font fntColumnHeader = new Font(btnColumnHeader, 10, 1, BaseColor.WHITE); for (int i = 0; i < dtbl.Columns.Count; i++) { PdfPCell cell = new PdfPCell(); cell.BackgroundColor = BaseColor.GRAY; cell.AddElement(new Chunk(dtbl.Columns[i].ColumnName.ToUpper(), fntColumnHeader)); table.AddCell(cell); } //Datos de table. for (int i = 0; i < dtbl.Rows.Count; i++) { for (int j = 0; j < dtbl.Columns.Count; j++) { table.AddCell(dtbl.Rows[i][j].ToString()); } } document.Add(table); document.Close(); writer.Close(); fs.Close(); } catch (Exception e) { string val = e.Message; } }
public void Report1ExportToPdf(DataTable dataTable) { string path = HttpContext.Current.Server.MapPath("PDF-Files"); string filename = path + "/Report1_" + HttpContext.Current.Session["UserID"].ToString().Trim().Substring(0, 4) + ".pdf"; Document document = new Document(new Rectangle(288f, 144f), 30, 20, 20, 20); document.SetPageSize(iTextSharp.text.PageSize.A4.Rotate()); try { PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(filename, FileMode.Create)); document.Open(); BaseFont header = iTextSharp.text.pdf.BaseFont.CreateFont("C:\\windows\\fonts\\timesbd.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED); FontSelector selector = new FontSelector(); Font f1 = FontFactory.GetFont(FontFactory.TIMES_BOLD, 12); f1.Color = BaseColor.MAGENTA; Font f2 = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 16); f1.Color = BaseColor.RED; iTextSharp.text.Font fontHeader = new iTextSharp.text.Font(header, 18, iTextSharp.text.Font.BOLD); DataTable dt = new DataTable(); dt = VPCRMSBAL.GetCompanyName(Convert.ToDecimal(HttpContext.Current.Session["UserID"].ToString().Trim().Substring(0, 4))); if (dt.Rows.Count > 0) { Paragraph para1 = new Paragraph(dt.Rows[0]["clientname"].ToString().Trim(), f2); para1.Alignment = Element.ALIGN_CENTER; document.Add(para1); para1.SpacingAfter = 50f; } Paragraph para2 = new Paragraph(); Phrase phrase1 = new Phrase("DAILY SALES STATISTICS", f1); para2.Alignment = Element.ALIGN_LEFT; para2.Add(phrase1); document.Add(para2); Paragraph para3 = new Paragraph(); Phrase phrase2 = new Phrase("Sales Person: "); Phrase phrase3 = new Phrase(HttpContext.Current.Session["UserFirstName"].ToString().Trim() + HttpContext.Current.Session["UserLastName"].ToString().Trim()); para3.Add(phrase2); para3.Add(phrase3); para3.Alignment = Element.ALIGN_RIGHT; para3.SpacingAfter = 50f; document.Add(para3); PdfPTable table = new PdfPTable(dataTable.Columns.Count); table.WidthPercentage = 100; //Set columns names in the pdf file for (int k = 0; k < dataTable.Columns.Count; k++) { PdfPCell cell = new PdfPCell(new Phrase(dataTable.Columns[k].ColumnName)); cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER; cell.VerticalAlignment = PdfPCell.ALIGN_CENTER; cell.BackgroundColor = new iTextSharp.text.BaseColor(51, 102, 102); table.AddCell(cell); } //Add values of DataTable in pdf file for (int i = 0; i < dataTable.Rows.Count; i++) { for (int j = 0; j < dataTable.Columns.Count; j++) { PdfPCell cell = new PdfPCell(new Phrase(dataTable.Rows[i][j].ToString())); //Align the cell in the center cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER; cell.VerticalAlignment = PdfPCell.ALIGN_CENTER; table.AddCell(cell); } } document.Add(table); document.Close(); } catch (Exception ex) { ILog logger = log4net.LogManager.GetLogger("ErrorLog"); logger.Error(ex.ToString()); HttpContext.Current.Response.Redirect("ErrorPage.aspx"); } }
public static Text Parse(TextReader reader) { var text = new Text(); var line = reader.ReadLine(); while(!string.IsNullOrEmpty(line)) { var paragraph = new Paragraph(); text.Add(paragraph); while (!string.IsNullOrEmpty(line)) { var sentenceString = line; var terminalPunctuationMark = line.GetFirstOrDefaultPunctuationMark(DefaultPunctuationMarks.TerminalPunctuationMarks); if (terminalPunctuationMark.HasValue) { var index = line.IndexOfPunctuationMark(terminalPunctuationMark); sentenceString = line.Substring(0, index).TrimStart(' '); line = line.Remove(0, index + terminalPunctuationMark.StringValue.Length); if(text.Count > 1) { var lastParagraph = text.Last(p => p.HasValue); if (lastParagraph.Any()) { var lastSentence = lastParagraph.Last(); if (lastSentence.IsNotFinished) { text.Remove(paragraph); paragraph = lastParagraph; lastSentence.Concat(sentenceString); continue; } } } } else { line = string.Empty; } var sentence = ParseSentenceString(sentenceString, terminalPunctuationMark); paragraph.Add(sentence); } line = reader.ReadLine(); } return text; }
public async Task <IActionResult> CreateFile(int?id) { if (id == null) { return(NotFound()); } var test = await _context.Tests .FirstOrDefaultAsync(m => m.Id == id); if (test == null) { return(NotFound()); } /* Criação de provas */ string fileName = test.Student.Name + "-test"; Document doc = new Document(PageSize.A4); doc.SetMargins(40, 40, 40, 80); doc.AddCreationDate(); string pasta = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); string dir = pasta + @"\" + fileName + ".pdf"; PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(dir, FileMode.Create)); doc.Open(); List <Paragraph> paragrafos = new List <Paragraph>(); Paragraph p1 = new Paragraph("", new Font(Font.FontFamily.HELVETICA, 12)); p1.Alignment = Element.ALIGN_CENTER; p1.Add($"FICTITOUS COLLEGE\n"); p1.Add($"MULTIDISCIPLINARY EXAM\n\n"); paragrafos.Add(p1); Paragraph p2 = new Paragraph("", new Font(Font.FontFamily.HELVETICA, 12)); p2.Alignment = Element.ALIGN_JUSTIFIED; p2.Add($"NAME: {test.Student.Name.ToUpper()} | {test.Period.Name.ToUpper()} PERIOD\n"); p2.Add($"TEACHER: ______________________________ | DATE: {test.Data.Date.ToString()}\n"); paragrafos.Add(p2); foreach (var q in test.TestQuestions) { Paragraph p = new Paragraph("", new Font(Font.FontFamily.HELVETICA, 12)); p.Alignment = Element.ALIGN_JUSTIFIED; p.Add($"\n{q.Question.Id}. {q.Question.Text}\n"); foreach (var alter in q.Question.Alternatives) { p.Add($"( ) {alter.Text}\n"); } paragrafos.Add(p); } foreach (var x in paragrafos) { doc.Add(x); } doc.Close(); return(RedirectToAction(nameof(Index))); }
/** * Gets the main appearance layer. * <p> * Consult <A HREF="http://partners.adobe.com/asn/developer/pdfs/tn/PPKAppearances.pdf">PPKAppearances.pdf</A> * for further details. * @return the main appearance layer * @throws DocumentException on error */ public PdfTemplate GetAppearance() { if (IsInvisible()) { PdfTemplate t = new PdfTemplate(writer); t.BoundingBox = new Rectangle(0, 0); writer.AddDirectTemplateSimple(t, null); return t; } if (app[0] == null && !reuseAppearance) CreateBlankN0(); if (app[1] == null && !acro6Layers) { PdfTemplate t = app[1] = new PdfTemplate(writer); t.BoundingBox = new Rectangle(100, 100); writer.AddDirectTemplateSimple(t, new PdfName("n1")); t.SetLiteral(questionMark); } if (app[2] == null) { String text; if (layer2Text == null) { StringBuilder buf = new StringBuilder(); buf.Append("Digitally signed by "); String name = null; CertificateInfo.X509Name x500name = CertificateInfo.GetSubjectFields((X509Certificate)signCertificate); if (x500name != null) { name = x500name.GetField("CN"); if (name == null) name = x500name.GetField("E"); } if (name == null) name = ""; buf.Append(name).Append('\n'); buf.Append("Date: ").Append(signDate.ToString("yyyy.MM.dd HH:mm:ss zzz")); if (reason != null) buf.Append('\n').Append(reasonCaption).Append(reason); if (location != null) buf.Append('\n').Append(locationCaption).Append(location); text = buf.ToString(); } else text = layer2Text; PdfTemplate t = app[2] = new PdfTemplate(writer); t.BoundingBox = rect; writer.AddDirectTemplateSimple(t, new PdfName("n2")); if (image != null) { if (imageScale == 0) { t.AddImage(image, rect.Width, 0, 0, rect.Height, 0, 0); } else { float usableScale = imageScale; if (imageScale < 0) usableScale = Math.Min(rect.Width / image.Width, rect.Height / image.Height); float w = image.Width * usableScale; float h = image.Height * usableScale; float x = (rect.Width - w) / 2; float y = (rect.Height - h) / 2; t.AddImage(image, w, 0, 0, h, x, y); } } Font font; if (layer2Font == null) font = new Font(); else font = new Font(layer2Font); float size = font.Size; Rectangle dataRect = null; Rectangle signatureRect = null; if (renderingMode == RenderingMode.NAME_AND_DESCRIPTION || (renderingMode == RenderingMode.GRAPHIC_AND_DESCRIPTION && this.SignatureGraphic != null)) { // origin is the bottom-left signatureRect = new Rectangle( MARGIN, MARGIN, rect.Width / 2 - MARGIN, rect.Height - MARGIN); dataRect = new Rectangle( rect.Width / 2 + MARGIN / 2, MARGIN, rect.Width - MARGIN / 2, rect.Height - MARGIN); if (rect.Height > rect.Width) { signatureRect = new Rectangle( MARGIN, rect.Height / 2, rect.Width - MARGIN, rect.Height); dataRect = new Rectangle( MARGIN, MARGIN, rect.Width - MARGIN, rect.Height / 2 - MARGIN); } } else if (renderingMode == RenderingMode.GRAPHIC) { if (signatureGraphic == null) { throw new InvalidOperationException(MessageLocalization.GetComposedMessage("a.signature.image.should.be.present.when.rendering.mode.is.graphic.only")); } signatureRect = new Rectangle( MARGIN, MARGIN, rect.Width - MARGIN, // take all space available rect.Height - MARGIN); } else { dataRect = new Rectangle( MARGIN, MARGIN, rect.Width - MARGIN, rect.Height * (1 - TOP_SECTION) - MARGIN); } if (renderingMode == RenderingMode.NAME_AND_DESCRIPTION) { string signedBy = CertificateInfo.GetSubjectFields(signCertificate).GetField("CN"); if (signedBy == null) signedBy = CertificateInfo.GetSubjectFields(signCertificate).GetField("E"); if (signedBy == null) signedBy = ""; Rectangle sr2 = new Rectangle(signatureRect.Width - MARGIN, signatureRect.Height - MARGIN ); float signedSize = ColumnText.FitText(font, signedBy, sr2, -1, runDirection); ColumnText ct2 = new ColumnText(t); ct2.RunDirection = runDirection; ct2.SetSimpleColumn(new Phrase(signedBy, font), signatureRect.Left, signatureRect.Bottom, signatureRect.Right, signatureRect.Top, signedSize, Element.ALIGN_LEFT); ct2.Go(); } else if (renderingMode == RenderingMode.GRAPHIC_AND_DESCRIPTION) { if (signatureGraphic == null) { throw new InvalidOperationException(MessageLocalization.GetComposedMessage("a.signature.image.should.be.present.when.rendering.mode.is.graphic.and.description")); } ColumnText ct2 = new ColumnText(t); ct2.RunDirection = runDirection; ct2.SetSimpleColumn(signatureRect.Left, signatureRect.Bottom, signatureRect.Right, signatureRect.Top, 0, Element.ALIGN_RIGHT); Image im = Image.GetInstance(SignatureGraphic); im.ScaleToFit(signatureRect.Width, signatureRect.Height); Paragraph p = new Paragraph(); // must calculate the point to draw from to make image appear in middle of column float x = 0; // experimentation found this magic number to counteract Adobe's signature graphic, which // offsets the y co-ordinate by 15 units float y = -im.ScaledHeight + 15; x = x + (signatureRect.Width - im.ScaledWidth) / 2; y = y - (signatureRect.Height - im.ScaledHeight) / 2; p.Add(new Chunk(im, x + (signatureRect.Width - im.ScaledWidth) / 2, y, false)); ct2.AddElement(p); ct2.Go(); } else if (renderingMode == RenderingMode.GRAPHIC) { ColumnText ct2 = new ColumnText(t); ct2.RunDirection = runDirection; ct2.SetSimpleColumn(signatureRect.Left, signatureRect.Bottom, signatureRect.Right, signatureRect.Top, 0, Element.ALIGN_RIGHT); Image im = Image.GetInstance(signatureGraphic); im.ScaleToFit(signatureRect.Width, signatureRect.Height); Paragraph p = new Paragraph(signatureRect.Height); // must calculate the point to draw from to make image appear in middle of column float x = (signatureRect.Width - im.ScaledWidth) / 2; float y = (signatureRect.Height - im.ScaledHeight) / 2; p.Add(new Chunk(im, x, y, false)); ct2.AddElement(p); ct2.Go(); } if (renderingMode != RenderingMode.GRAPHIC) { if (size <= 0) { Rectangle sr = new Rectangle(dataRect.Width, dataRect.Height); size = ColumnText.FitText(font, text, sr, 12, runDirection); } ColumnText ct = new ColumnText(t); ct.RunDirection = runDirection; ct.SetSimpleColumn(new Phrase(text, font), dataRect.Left, dataRect.Bottom, dataRect.Right, dataRect.Top, size, Element.ALIGN_LEFT); ct.Go(); } } if (app[3] == null && !acro6Layers) { PdfTemplate t = app[3] = new PdfTemplate(writer); t.BoundingBox = new Rectangle(100, 100); writer.AddDirectTemplateSimple(t, new PdfName("n3")); t.SetLiteral("% DSBlank\n"); } if (app[4] == null && !acro6Layers) { PdfTemplate t = app[4] = new PdfTemplate(writer); t.BoundingBox = new Rectangle(0, rect.Height * (1 - TOP_SECTION), rect.Right, rect.Top); writer.AddDirectTemplateSimple(t, new PdfName("n4")); Font font; if (layer2Font == null) font = new Font(); else font = new Font(layer2Font); float size = font.Size; String text = "Signature Not Verified"; if (layer4Text != null) text = layer4Text; Rectangle sr = new Rectangle(rect.Width - 2 * MARGIN, rect.Height * TOP_SECTION - 2 * MARGIN); size = ColumnText.FitText(font, text, sr, 15, runDirection); ColumnText ct = new ColumnText(t); ct.RunDirection = runDirection; ct.SetSimpleColumn(new Phrase(text, font), MARGIN, 0, rect.Width - MARGIN, rect.Height - MARGIN, size, Element.ALIGN_LEFT); ct.Go(); } int rotation = writer.reader.GetPageRotation(page); Rectangle rotated = new Rectangle(rect); int n = rotation; while (n > 0) { rotated = rotated.Rotate(); n -= 90; } if (frm == null) { frm = new PdfTemplate(writer); frm.BoundingBox = rotated; writer.AddDirectTemplateSimple(frm, new PdfName("FRM")); float scale = Math.Min(rect.Width, rect.Height) * 0.9f; float x = (rect.Width - scale) / 2; float y = (rect.Height - scale) / 2; scale /= 100; if (rotation == 90) frm.ConcatCTM(0, 1, -1, 0, rect.Height, 0); else if (rotation == 180) frm.ConcatCTM(-1, 0, 0, -1, rect.Width, rect.Height); else if (rotation == 270) frm.ConcatCTM(0, -1, 1, 0, 0, rect.Width); if (reuseAppearance) { AcroFields af = writer.GetAcroFields(); PdfIndirectReference refe = af.GetNormalAppearance(FieldName); if (refe != null) { frm.AddTemplateReference(refe, new PdfName("n0"), 1, 0, 0, 1, 0, 0); } else { reuseAppearance = false; if (app[0] == null) { CreateBlankN0(); } } } if (!reuseAppearance) { frm.AddTemplate(app[0], 0, 0); } if (!acro6Layers) frm.AddTemplate(app[1], scale, 0, 0, scale, x, y); frm.AddTemplate(app[2], 0, 0); if (!acro6Layers) { frm.AddTemplate(app[3], scale, 0, 0, scale, x, y); frm.AddTemplate(app[4], 0, 0); } } PdfTemplate napp = new PdfTemplate(writer); napp.BoundingBox = rotated; writer.AddDirectTemplateSimple(napp, null); napp.AddTemplate(frm, 0, 0); return napp; }
/** * Constructs a RtfHeaderFooter for a HeaderFooter. * * @param doc The RtfDocument this RtfHeaderFooter belongs to * @param headerFooter The HeaderFooter to base this RtfHeaderFooter on */ protected internal RtfHeaderFooter(RtfDocument doc, Legacy.Text.HeaderFooter headerFooter) : base(new Phrase(""), false) { this.document = doc; Paragraph par = new Paragraph(); par.Alignment = headerFooter.Alignment; if (headerFooter.Before != null) { par.Add(headerFooter.Before); } if (headerFooter.IsNumbered()) { par.Add(new FD.RtfPageNumber(this.document)); } if (headerFooter.After != null) { par.Add(headerFooter.After); } try { this.content = new Object[1]; this.content[0] = doc.GetMapper().MapElement(par)[0]; ((IRtfBasicElement) this.content[0]).SetInHeader(true); } catch (DocumentException) { } }