public override byte[] CreatePdf(List<PdfContentParameter> contents, string[] images, int type) { var document = new Document(); float docHeight = document.PageSize.Height - heightOffset; document.SetPageSize(iTextSharp.text.PageSize.A4.Rotate()); document.SetMargins(50, 50, 10, 40); var output = new MemoryStream(); var writer = PdfWriter.GetInstance(document, output); writer.PageEvent = new HeaderFooterHandler(type); document.Open(); document.Add(contents[0].Table); for (int i = 0; i < images.Length; i++) { document.NewPage(); float subtrahend = document.PageSize.Height - heightOffset; iTextSharp.text.Image pool = iTextSharp.text.Image.GetInstance(images[i]); pool.Alignment = 3; pool.ScaleToFit(document.PageSize.Width - (document.RightMargin * 2), subtrahend); //pool.ScaleAbsolute(document.PageSize.Width - (document.RightMargin * 2), subtrahend); document.Add(pool); } document.Close(); return output.ToArray(); }
public static void CreateHardwareReport(string fileName, IEnumerable<HardwareCountReport> hardwares) { try { Document document = new Document(PageSize.A4, 72, 72, 72, 72); PdfWriter.GetInstance(document, new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)); document.Open(); document.Add(new Paragraph(Element.ALIGN_CENTER, "Hardware Report", new Font(iTextSharp.text.Font.FontFamily.HELVETICA, 16, Font.BOLD))); document.Add(new Chunk(Chunk.NEWLINE)); var table = new PdfPTable(3); table.SetTotalWidth(new float[] { 25f, 50f, 25f }); table.WidthPercentage = 100; table.AddCell(new Phrase("Category")); table.AddCell(new Phrase("Hardware Model/Type")); table.AddCell(new Phrase("Total")); foreach (var hw in hardwares) { table.AddCell(new Phrase(hw.Category)); table.AddCell(new Phrase(hw.Model)); table.AddCell(new Phrase(hw.Count)); } document.Add(table); document.Close(); } catch (Exception x) { Log.Error("Error when creating report.", x); } }
public void Write(string outputPath, FlowDocument doc) { Document pdfDoc = new Document(PageSize.A4, 50, 50, 50, 50); Font textFont = new Font(baseFont, DEFAULT_FONTSIZE, Font.NORMAL, BaseColor.BLACK); Font headingFont = new Font(baseFont, DEFAULT_HEADINGSIZE, Font.BOLD, BaseColor.BLACK); using (FileStream stream = new FileStream(outputPath, FileMode.Create)) { PdfWriter writer = PdfWriter.GetInstance(pdfDoc, stream); pdfDoc.Open(); foreach (Block i in doc.Blocks) { if (i is System.Windows.Documents.Paragraph) { TextRange range = new TextRange(i.ContentStart, i.ContentEnd); Console.WriteLine(i.Tag); switch (i.Tag as string) { case "Paragraph": iTextSharp.text.Paragraph par = new iTextSharp.text.Paragraph(range.Text, textFont); par.Alignment = Element.ALIGN_JUSTIFIED; pdfDoc.Add(par); break; case "Heading": iTextSharp.text.Paragraph head = new iTextSharp.text.Paragraph(range.Text, headingFont); head.Alignment = Element.ALIGN_CENTER; head.SpacingAfter = 10; pdfDoc.Add(head); break; default: iTextSharp.text.Paragraph def = new iTextSharp.text.Paragraph(range.Text, textFont); def.Alignment = Element.ALIGN_JUSTIFIED; pdfDoc.Add(def); break; } } else if (i is System.Windows.Documents.List) { iTextSharp.text.List list = new iTextSharp.text.List(iTextSharp.text.List.UNORDERED, 10f); list.SetListSymbol("\u2022"); list.IndentationLeft = 15f; foreach (var li in (i as System.Windows.Documents.List).ListItems) { iTextSharp.text.ListItem listitem = new iTextSharp.text.ListItem(); TextRange range = new TextRange(li.Blocks.ElementAt(0).ContentStart, li.Blocks.ElementAt(0).ContentEnd); string text = range.Text.Substring(1); iTextSharp.text.Paragraph par = new iTextSharp.text.Paragraph(text, textFont); listitem.SpacingAfter = 10; listitem.Add(par); list.Add(listitem); } pdfDoc.Add(list); } } if (pdfDoc.PageNumber == 0) { iTextSharp.text.Paragraph par = new iTextSharp.text.Paragraph(" "); par.Alignment = Element.ALIGN_JUSTIFIED; pdfDoc.Add(par); } pdfDoc.Close(); } }
// =========================================================================== public void Write(Stream stream) { string RESOURCE = Utility.ResourcePosters; // step 1 using (Document document = new Document()) { // step 2 PdfWriter.GetInstance(document, stream); // step 3 document.Open(); Rectangle rect = new Rectangle(0, 806, 36, 842); rect.BackgroundColor = BaseColor.RED; document.Add(rect); // step 4 IEnumerable<Movie> movies = PojoFactory.GetMovies(); foreach (Movie movie in movies) { document.Add(new Paragraph(movie.MovieTitle)); // Add an image document.Add( Image.GetInstance(Path.Combine(RESOURCE, movie.Imdb + ".jpg")) ); } } }
public static void Create(string message) { // 1. Create file FileStream fileStream = new FileStream(FileName, FileMode.Create, FileAccess.Write, FileShare.None); // 2. Create iTextSharp.text.Document object Document document = new Document(); // 3. Create a iTextSharp.text.pdf.PdfWriter object. It helps to write the Document to the FileStream PdfWriter pdfWriter = PdfWriter.GetInstance(document, fileStream); // 4. Open the document document.Open(); PdfPTable table = CreateTable(); // 5. Write text var paragraph = new Paragraph(message); document.Add(paragraph); document.Add(table); // 6. Document close document.Close(); }
public void Test() { String file = "tagged_pdf_page_events.pdf"; Document document = new Document(); PdfWriter pdfWriter = PdfWriter.GetInstance(document, new FileStream(OUTPUT_FOLDER + file, FileMode.Create)); pdfWriter.SetTagged(); pdfWriter.PageEvent = new TaggedPdfPageEventsTest(); document.Open(); document.Add(new Paragraph("Hello")); document.NewPage(); document.Add(new Paragraph("World")); document.Close(); // compare CompareTool compareTool = new CompareTool(); String errorMessage = compareTool.CompareByContent(OUTPUT_FOLDER + file, TEST_RESOURCES_PATH + file, OUTPUT_FOLDER, "diff"); if (errorMessage != null) { Assert.Fail(errorMessage); } }
/// <summary> /// Costruisce e spedisce PDF con lettera corrente /// </summary> protected void buildPDF() { string fileName = "Visita " + DALRuntime.getNomePazienteConSaluto(DALRuntime.IdMQuest) + ".pdf"; fileName = fileName.Replace(' ', '_'); Document pdfDoc = new Document(); this.Response.Clear(); this.Response.AddHeader("content-disposition", string.Format("attachment;filename={0}", System.IO.Path.GetFileName(fileName))); this.Response.ContentType = "application/pdf"; PdfWriter.GetInstance(pdfDoc, Response.OutputStream); pdfDoc.Open(); // Aggiunge l'intestazione dell'utente string sIntestazione = DALRuntime.getTestata(); // Definisce un font piu' piccolo BaseFont bfTimes = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, true); Font ftTimes10Italic = new Font(bfTimes, 10, Font.ITALIC); Paragraph pIntestazione = new Paragraph(sIntestazione, ftTimes10Italic); pdfDoc.Add(pIntestazione); Font ftTimes10Normal = new Font(bfTimes, 10, Font.NORMAL); string sLettera = memLettera.Text; Paragraph pBody = new Paragraph(sLettera, ftTimes10Normal); pdfDoc.Add(pBody); pdfDoc.Close(); this.Response.Flush(); this.Response.End(); }
// =========================================================================== public void Write(Stream stream) { // step 1 using (Document document = new Document()) { // step 2 PdfWriter.GetInstance(document, stream); // step 3 document.Open(); // step 4 // Image in colorspace DeviceGray byte[] gradient = new byte[256]; for (int i = 0; i < 256; i++) { gradient[i] = (byte) i; } Image img1 = Image.GetInstance(256, 1, 1, 8, gradient); img1.ScaleAbsolute(256, 50); document.Add(img1); // Image in colorspace RGB byte[] cgradient = new byte[256 * 3]; for (int i = 0; i < 256; i++) { cgradient[i * 3] = (byte) (255 - i); cgradient[i * 3 + 1] = (byte) (255 - i); cgradient[i * 3 + 2] = (byte) i; } Image img2 = Image.GetInstance(256, 1, 3, 8, cgradient); img2.ScaleAbsolute(256, 50); document.Add(img2); Image img3 = Image.GetInstance(16, 16, 3, 8, cgradient); img3.ScaleAbsolute(64, 64); document.Add(img3); } }
// =========================================================================== public void Write(Stream stream) { // step 1 using (Document document = new Document()) { // step 2 PdfWriter.GetInstance(document, stream); // step 3 document.Open(); // step 4 PdfPTable table = CreateTable1(); document.Add(table); table = CreateTable2(); table.SpacingBefore = 5; table.SpacingAfter = 5; document.Add(table); table = CreateTable3(); document.Add(table); table = CreateTable4(); table.SpacingBefore = 5; table.SpacingAfter = 5; document.Add(table); table = CreateTable5(); document.Add(table); } }
public void CreateDocument( List< ScanDetails > info, string path ) { var doc = new Document( PageSize.A4 ); PdfWriter.GetInstance( doc, new FileStream( path, FileMode.Create ) ); doc.Open(); doc.Add( new Paragraph() ); PdfPTable table = new PdfPTable( 4 ) { WidthPercentage = 100 }; //header PdfPCell cell = new PdfPCell { BackgroundColor = BaseColor.LIGHT_GRAY, Phrase = new Phrase( "URL" ) }; table.AddCell( cell ); cell.Phrase = new Phrase( "Response" ); table.AddCell( cell ); cell.Phrase = new Phrase( "Size" ); table.AddCell( cell ); cell.Phrase = new Phrase( "Page Title" ); table.AddCell( cell ); //rows foreach( var item in info ) { table.AddCell( item.Url.ToString() ); table.AddCell( item.Response ); table.AddCell( item.Size.ToString() ); table.AddCell( item.PageTitle ); } doc.Add( table ); doc.Close(); }
public virtual void TestIncompleteTableAdd() { const String file = "incomplete_add.pdf"; Document document = new Document(PageSize.LETTER); PdfWriter.GetInstance(document, new FileStream(OUTPUT_FOLDER + file, FileMode.OpenOrCreate)); document.Open(); PdfPTable table = new PdfPTable(5); table.HeaderRows = 1; table.SplitRows = false; table.Complete = false; for (int i = 0; i < 5; i++) { table.AddCell("Header " + i); } for (int i = 0; i < 500; i++) { if (i % 5 == 0) { document.Add(table); } table.AddCell("Test " + i); } table.Complete = true; document.Add(table); document.Close(); CompareTablePdf(file); }
public virtual void TestNoChangeInSetSkipFirstHeader() { Document document = new Document(); Stream stream = new MemoryStream(); PdfWriter writer = PdfWriter.GetInstance(document, stream); document.Open(); PdfPTable table = new PdfPTable(5); table.HeaderRows = 1; table.SplitRows = false; table.Complete = false; for (int i = 0; i < 5; ++i) { table.AddCell("Header " + i); } table.AddCell("Cell 1"); document.Add(table); Assert.False(table.SkipFirstHeader); table.Complete = true; for (int i = 1; i < 5; i++) { table.AddCell("Cell " + i); } document.Add(table); document.Close(); stream.Close(); }
// --------------------------------------------------------------------------- public void Write(Stream stream) { // step 1 using (Document document = new Document()) { // step 2 PdfWriter writer = PdfWriter.GetInstance(document, stream); // step 3 document.Open(); // step 4 Phrase phrase; Chunk chunk; foreach (Movie movie in PojoFactory.GetMovies()) { phrase = new Phrase(movie.MovieTitle); chunk = new Chunk("\u00a0"); chunk.SetAnnotation(PdfAnnotation.CreateText( writer, null, movie.MovieTitle, string.Format(INFO, movie.Year, movie.Duration), false, "Comment" )); phrase.Add(chunk); document.Add(phrase); document.Add(PojoToElementFactory.GetDirectorList(movie)); document.Add(PojoToElementFactory.GetCountryList(movie)); } } }
// --------------------------------------------------------------------------- public void Write(Stream stream) { // step 1 using (Document document = new Document()) { // step 2 PdfWriter.GetInstance(document, stream); // step 3 document.Open(); // step 4 BaseFont bf; Font font; Image img = Image.GetInstance(POSTER); img.ScalePercent(50); img.BorderWidth = 18f; img.Border = Image.BOX; img.BorderColor = GrayColor.GRAYWHITE; img.Alignment = Element.ALIGN_LEFT | Image.TEXTWRAP; document.Add(img); document.Add(new Paragraph( "Movie title: Tears of the Black Tiger (Thailand)" )); document.Add(new Paragraph("directed by Wisit Sasanatieng")); for (int i = 0; i < 2; i++) { bf = BaseFont.CreateFont( FONTS[i], BaseFont.IDENTITY_H, BaseFont.EMBEDDED ); document.Add(new Paragraph("Font: " + bf.PostscriptFontName)); font = new Font(bf, 20); document.Add(new Paragraph(MOVIE, font)); } } }
// --------------------------------------------------------------------------- /** * Creates a PDF document. */ public byte[] CreatePdf() { using (MemoryStream ms = new MemoryStream()) { Image img1 = Image.GetInstance( Path.Combine(Utility.ResourceImage, RESOURCE1) ); // step 1 using (Document document = new Document()) { // step 2 PdfWriter.GetInstance(document, ms); // step 3 document.Open(); // step 4 img1.SetAbsolutePosition(0, 0); document.Add(img1); Image img2 = Image.GetInstance( Path.Combine(Utility.ResourceImage, RESOURCE2) ); img2.SetAbsolutePosition(0, 260); document.Add(img2); Image img3 = Image.GetInstance( Path.Combine(Utility.ResourceImage,RESOURCE3) ); img3.Transparency = new int[]{ 0x00, 0x10 }; img3.SetAbsolutePosition(0, 0); document.Add(img3); Image img4 = Image.GetInstance( Path.Combine(Utility.ResourceImage,RESOURCE4) ); img4.Transparency = new int[]{ 0xF0, 0xFF }; img4.SetAbsolutePosition(50, 50); document.Add(img4); } return ms.ToArray(); } }
// --------------------------------------------------------------------------- public void Write(Stream stream) { // step 1 using (Document document = new Document()) { // step 2 PdfWriter.GetInstance(document, stream); // step 3 document.Open(); // step 4 document.Add(new Paragraph( "Movies featuring River Phoenix", FilmFonts.BOLD )); document.Add(CreateParagraph( "My favorite movie featuring River Phoenix was ", "0092005" )); document.Add(CreateParagraph( "River Phoenix was nominated for an academy award for his role in ", "0096018" )); document.Add(CreateParagraph( "River Phoenix played the young Indiana Jones in ", "0097576" )); document.Add(CreateParagraph( "His best role was probably in ", "0102494" )); } }
public static void GeneratePdfReport(string filepath) { FileStream fileStream = new FileStream(filepath, FileMode.Create); Document document = new Document(); PdfWriter writer = PdfWriter.GetInstance(document, fileStream); document.SetPageSize(PageSize.A3); document.Open(); var paragraph = new Paragraph("Aggregated Sales Report", FontFactory.GetFont("Arial", 19, Font.BOLD)); paragraph.SpacingAfter = 20.0f; paragraph.Alignment = 1; document.Add(paragraph); PdfPTable mainTable = new PdfPTable(1); var reports = GetDayReports(); foreach (var dayReport in reports) { var headerCell = new PdfPCell(new Phrase("Date: " + dayReport.FormattedDate)); headerCell.BackgroundColor = new BaseColor(175, 166, 166); mainTable.AddCell(headerCell); var table = GenerateReportTable(dayReport); mainTable.AddCell(table); } document.Add(mainTable); document.Close(); }
public static void GeneratePdfSingleDataType(string filePath, string title, string content) { try { Logger.LogI("GeneratePDF -> " + filePath); var doc = new Document(PageSize.A3, 36, 72, 72, 144); using (var fs = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite)) { PdfWriter.GetInstance(doc, fs); doc.Open(); doc.AddTitle(title); doc.AddAuthor(Environment.MachineName); doc.Add( new Paragraph("Title : " + title + Environment.NewLine + "ServerName : " + Environment.MachineName + Environment.NewLine + "Author : " + Environment.UserName)); doc.NewPage(); doc.Add(new Paragraph(content)); doc.Close(); } } catch (Exception ex) { Logger.LogE(ex.Source + " -> " + ex.Message + "\n" + ex.StackTrace); } }
// =========================================================================== public void Write(Stream stream) { // step 1 using (Document document = new Document()) { // step 2 PdfWriter.GetInstance(document, stream).InitialLeading = 16; // step 3 document.Open(); // add the ID in another font Font font = new Font(Font.FontFamily.HELVETICA, 6, Font.BOLD, BaseColor.WHITE); // step 4 using (var c = AdoDB.Provider.CreateConnection()) { c.ConnectionString = AdoDB.CS; using (DbCommand cmd = c.CreateCommand()) { cmd.CommandText = "SELECT country,id FROM film_country ORDER BY country"; c.Open(); using (var r = cmd.ExecuteReader()) { while (r.Read()) { var country = r.GetString(0); var ID = r.GetString(1); document.Add(new Chunk(country)); document.Add(new Chunk(" ")); Chunk id = new Chunk(ID, font); // with a background color id.SetBackground(BaseColor.BLACK, 1f, 0.5f, 1f, 1.5f); // and a text rise id.SetTextRise(6); document.Add(id); document.Add(Chunk.NEWLINE); } } } } } }
// --------------------------------------------------------------------------- public void Write(Stream stream) { // step 1 using (Document document = new Document()) { // step 2 PdfWriter.GetInstance(document, stream); // step 3 document.Open(); // step 4 BaseFont bf; Font font; String[] names = BaseFont.EnumerateTTCNames(FONT); for (int i = 0; i < names.Length; i++) { bf = BaseFont.CreateFont( String.Format("{0}, {1}", FONT, i), BaseFont.IDENTITY_H, BaseFont.EMBEDDED ); font = new Font(bf, 12); document.Add(new Paragraph("font " + i + ": " + names[i], font)); document.Add(new Paragraph("Rash\u00f4mon", font)); document.Add(new Paragraph("Directed by Akira Kurosawa", font)); document.Add(new Paragraph("\u7f85\u751f\u9580", font)); document.Add(Chunk.NEWLINE); } } }
public void VerticalPositionTest0() { String file = "vertical_position.pdf"; Document document = new Document(); PdfWriter writer = PdfWriter.GetInstance(document, File.Create(OUTPUT_FOLDER + file)); document.Open(); writer.PageEvent = new CustomPageEvent(); PdfPTable table = new PdfPTable(2); for (int i = 0; i < 100; i++) { table.AddCell("Hello " + i); table.AddCell("World " + i); } document.Add(table); document.NewPage(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < 1000; i++) { sb.Append("some more text "); } document.Add(new Paragraph(sb.ToString())); document.Close(); // compare CompareTool compareTool = new CompareTool(); String errorMessage = compareTool.CompareByContent(OUTPUT_FOLDER + file, TEST_RESOURCES_PATH + file, OUTPUT_FOLDER, "diff"); if (errorMessage != null) { Assert.Fail(errorMessage); } }
public void TextLeadingTest() { String file = "phrases.pdf"; Document document = new Document(); PdfWriter writer = PdfWriter.GetInstance(document, File.Create(OUTPUT_FOLDER + file)); document.Open(); Phrase p1 = new Phrase("first, leading of 150"); p1.Leading = 150; document.Add(p1); document.Add(Chunk.NEWLINE); Phrase p2 = new Phrase("second, leading of 500"); p2.Leading = 500; document.Add(p2); document.Add(Chunk.NEWLINE); Phrase p3 = new Phrase(); p3.Add(new Chunk("third, leading of 20")); p3.Leading = 20; document.Add(p3); document.Close(); // compare CompareTool compareTool = new CompareTool(); String errorMessage = compareTool.CompareByContent(OUTPUT_FOLDER + file, TEST_RESOURCES_PATH + file, OUTPUT_FOLDER, "diff"); if (errorMessage != null) { Assert.Fail(errorMessage); } }
public bool TryCreatePdf(string nameBank) { try { using (FileStream file = new FileStream(String.Format(path,nameBank), FileMode.Create)) { Document document = new Document(PageSize.A7); PdfWriter writer = PdfWriter.GetInstance(document, file); /// Create metadate pdf file document.AddAuthor(""); document.AddLanguage("pl"); document.AddSubject("Payment transaction"); document.AddTitle("Transaction"); /// Create text in pdf file document.Open(); document.Add(new Paragraph(_przelew+"\n")); document.Add(new Paragraph(String.Format("Bank {0}: zaprasza\n",nameBank))); document.Add(new Paragraph(DateTime.Now.ToString())); document.Close(); writer.Close(); file.Close(); return true; } } catch (SystemException ex) { return false; } }
private void CreatePDF() { MemoryStream MStream = new MemoryStream(); Document document = new Document(PageSize.A4, 80, 50, 30, 65); try { PdfWriter writer = PdfWriter.GetInstance(document, MStream); document.Open(); document.Add(new iTextSharp.text.Paragraph("This is test and must work")); string h = "<a>dsfdfsdf</a><br><br><h1>sdfsdfsd</h1>"; TextReader sReader = new StringReader(h); List<IElement> l = HTMLWorker.ParseToList(sReader,new StyleSheet()); foreach (IElement i in l) { document.Add(i); } document.Close(); } catch (Exception e) { throw e; } //stampo pdf Response.Buffer = true; Response.ClearContent(); Response.ClearHeaders(); Response.ContentType = "application/pdf"; Response.AddHeader("Content-Disposition", "attachment;filename=myPDFNew.pdf"); Response.BinaryWrite(MStream.GetBuffer()); Response.End(); }
protected void Button1_Click(object sender, EventArgs e) { Page.Title = "Contact List"; MemoryStream PDFData = new MemoryStream(); // step 1: creation of a document-object Document document = new Document(); // step 2: // we create a writer that listens to the document // and directs a PDF-stream to a file PdfWriter.GetInstance(document, PDFData); // step 3: we open the document document.Open(); // step 4: we add a paragraph to the document document.Add(new Paragraph(DateTime.Now.ToString())); Contact oContact = new Contact(); DataTable dtContact = oContact.LoadAll(); int numRow = dtContact.Rows.Count; int numCol = 5; iTextSharp.text.Table aTable = new iTextSharp.text.Table(numCol, numRow); aTable.AutoFillEmptyCells = true; aTable.Padding = 1; aTable.Spacing = 1; Cell cell = new Cell(new Phrase("Contact List", FontFactory.GetFont(FontFactory.TIMES, 14, Font.BOLD))); cell.Header = true; cell.Colspan = numCol; cell.BackgroundColor = Color.LIGHT_GRAY; cell.HorizontalAlignment = Element.ALIGN_CENTER; aTable.AddCell(cell); for (int i = 0; i < dtContact.Rows.Count; i++) { for (int n = 1; n <= numCol; n++) aTable.AddCell(dtContact.Rows[i][n].ToString()); } document.Add(aTable); // step 5: we close the document document.Close(); Response.Clear(); Response.ClearContent(); Response.ClearHeaders(); Response.ContentType = "application/pdf"; Response.Charset = string.Empty; Response.Cache.SetCacheability(System.Web.HttpCacheability.Public); Response.AddHeader("Content-Disposition", "attachment; filename=" + Title.Replace(" ", "").Replace(":", "-") + ".pdf"); Response.OutputStream.Write(PDFData.GetBuffer(), 0, PDFData.GetBuffer().Length); Response.OutputStream.Flush(); Response.OutputStream.Close(); Response.End(); }
// --------------------------------------------------------------------------- /** * Creates a PDF document. * @param stream Stream for the new PDF document */ public void CreatePdf(Stream stream) { string RESOURCE = Utility.ResourcePosters; // step 1 using (Document document = new Document()) { // step 2 PdfWriter writer = PdfWriter.GetInstance(document, stream); // step 3 document.Open(); // step 4 Phrase phrase; Chunk chunk; PdfAnnotation annotation; foreach (Movie movie in PojoFactory.GetMovies()) { phrase = new Phrase(movie.MovieTitle); chunk = new Chunk("\u00a0\u00a0"); annotation = PdfAnnotation.CreateFileAttachment( writer, null, movie.MovieTitle, null, Path.Combine(RESOURCE, movie.Imdb + ".jpg"), string.Format("img_{0}.jpg", movie.Imdb) ); annotation.Put(PdfName.NAME, new PdfString("Paperclip")); chunk.SetAnnotation(annotation); phrase.Add(chunk); document.Add(phrase); document.Add(PojoToElementFactory.GetDirectorList(movie)); document.Add(PojoToElementFactory.GetCountryList(movie)); } } }
// --------------------------------------------------------------------------- public virtual void Write(Stream stream) { var SQL = @"SELECT name, given_name FROM film_director ORDER BY name, given_name"; // step 1 using (Document document = new Document()) { // step 2 PdfWriter.GetInstance(document, stream); // step 3 document.Open(); // step 4 using (var c = AdoDB.Provider.CreateConnection()) { c.ConnectionString = AdoDB.CS; using (DbCommand cmd = c.CreateCommand()) { cmd.CommandText = SQL; c.Open(); using (var r = cmd.ExecuteReader()) { while (r.Read()) { document.Add(CreateDirectorPhrase(r)); document.Add(Chunk.NEWLINE); } } } } } }
// --------------------------------------------------------------------------- public void Write(Stream stream) { // step 1 using (Document document = new Document()) { // step 2 PdfWriter.GetInstance(document, stream); // step 3 document.Open(); // step 4 BaseFont bf; Font font; for (int i = 0; i < 3; i++) { bf = BaseFont.CreateFont( MOVIES[i][0], MOVIES[i][1], BaseFont.NOT_EMBEDDED ); font = new Font(bf, 12); document.Add(new Paragraph(bf.PostscriptFontName, font)); for (int j = 2; j < 5; j++) { document.Add(new Paragraph(MOVIES[i][j], font)); } document.Add(Chunk.NEWLINE); } } }
// =========================================================================== public void Write(Stream stream) { // step 1 using (Document document = new Document()) { // step 2 PdfWriter.GetInstance(document, stream); document.SetPageSize(PageSize.A5); document.SetMargins(36, 72, 108, 180); document.SetMarginMirroring(true); // step 3 document.Open(); // step 4 document.Add(new Paragraph( "The left margin of this odd page is 36pt (0.5 inch); " + "the right margin 72pt (1 inch); " + "the top margin 108pt (1.5 inch); " + "the bottom margin 180pt (2.5 inch).") ); Paragraph paragraph = new Paragraph(); paragraph.Alignment = Element.ALIGN_JUSTIFIED; for (int i = 0; i < 20; i++) { paragraph.Add("Hello World! Hello People! " + "Hello Sky! Hello Sun! Hello Moon! Hello Stars!" ); } document.Add(paragraph); document.Add(new Paragraph( "The right margin of this even page is 36pt (0.5 inch); " + "the left margin 72pt (1 inch).") ); } }
private void LoadClinicRegistrationToBrowser(string htmlText) { //create a PDF document in MemoryStream System.IO.MemoryStream m = new System.IO.MemoryStream(); iTextSharp.text.Document document = new iTextSharp.text.Document(iTextSharp.text.PageSize.LETTER); iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, m); document.Open(); //make an arraylist ....with STRINGREADER since its not reading file... List <iTextSharp.text.IElement> htmlarraylist = iTextSharp.text.html.simpleparser.HTMLWorker.ParseToList(new StringReader(htmlText), null); //add the collection to the document for (int k = 0; k < htmlarraylist.Count; k++) { document.Add((iTextSharp.text.IElement)htmlarraylist[k]); } document.Close(); //Stream PDF document back to browser Response.ContentType = "Application/pdf"; Response.BinaryWrite(m.GetBuffer()); Response.Flush(); Response.SuppressContent = true; Response.End(); }
public static void Departmentalreport(iTextSharp.text.Document pdfDoc, DataSet dt, List <string> columns, string level, int direclevel, List <ColumnTotals> Totals) { if (level == "4") { GetPDfTable(pdfDoc, dt.Tables[2], 0, true, Totals); pdfDoc.Add(new iTextSharp.text.Paragraph(" ")); if (direclevel != 1) { GetPDfTable(pdfDoc, dt.Tables[direclevel + 2], 1, false, Totals); } else { GetEXTPDFTable(pdfDoc, dt.Tables[0], dt.Tables[3], Totals); } } else { if (direclevel == 1) { GetPDfTable(pdfDoc, dt.Tables[3], 0, true, Totals); pdfDoc.Add(new iTextSharp.text.Paragraph(" ")); } else if (direclevel == 2) { GetPDfTable(pdfDoc, dt.Tables[2], 0, true, Totals); pdfDoc.Add(new iTextSharp.text.Paragraph(" ")); GetPDfTable(pdfDoc, dt.Tables[4], 0, false, Totals); pdfDoc.Add(new iTextSharp.text.Paragraph(" ")); GetEXTPDFTable(pdfDoc, dt.Tables[0], dt.Tables[3], Totals); } else if (direclevel == 3) { GetPDfTable(pdfDoc, dt.Tables[2], 0, true, Totals); pdfDoc.Add(new iTextSharp.text.Paragraph(" ")); GetPDfTable(pdfDoc, dt.Tables[5], 1, false, Totals); pdfDoc.Add(new iTextSharp.text.Paragraph(" ")); GetPDfTable(pdfDoc, dt.Tables[4], 1, false, Totals); pdfDoc.Add(new iTextSharp.text.Paragraph(" ")); GetEXTPDFTable(pdfDoc, dt.Tables[0], dt.Tables[3], Totals); } else if (direclevel == 4) { GetPDfTable(pdfDoc, dt.Tables[2], 0, true, Totals); pdfDoc.Add(new iTextSharp.text.Paragraph(" ")); GetPDfTable(pdfDoc, dt.Tables[6], 1, false, Totals); pdfDoc.Add(new iTextSharp.text.Paragraph(" ")); GetPDfTable(pdfDoc, dt.Tables[5], 1, false, Totals); pdfDoc.Add(new iTextSharp.text.Paragraph(" ")); GetPDfTable(pdfDoc, dt.Tables[4], 1, false, Totals); pdfDoc.Add(new iTextSharp.text.Paragraph(" ")); GetEXTPDFTable(pdfDoc, dt.Tables[0], dt.Tables[3], Totals); } } }
public static void BindPDFdataWithKPIIndication(iTextSharp.text.Document pdfDoc, DataTable dt, List <string> columns, List <ColumnTotals> Totals, string targetcolumn, string colourcode) { PdfPTable pdfTable = new PdfPTable(columns.Count); pdfTable.TotalWidth = 100; //creating header columns foreach (string colu in columns) { PdfPCell cell = new PdfPCell(new Phrase(colu, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 6, iTextSharp.text.Font.BOLD, BaseColor.BLACK))); pdfTable.AddCell(cell); } //creating rows foreach (DataRow row in dt.Rows) { foreach (string col in columns) { if (col == targetcolumn) { PdfPCell cell = new PdfPCell(new Phrase(row[col].ToString().Replace("<b>", string.Empty).Replace("</b>", string.Empty), new iTextSharp.text.Font(iTextSharp.text.Font.NORMAL, 6, 0))); BaseColor myColor = new BaseColor(255, 255, 255); switch (row[colourcode].ToString()) { case "Table_Rows_Green": myColor = new BaseColor(141, 203, 42); break; case "Table_Rows_orange": myColor = new BaseColor(255, 122, 0); break; case "Table_Rows_Red": myColor = new BaseColor(194, 0, 0); break; } cell.BackgroundColor = myColor; pdfTable.AddCell(cell); } else { PdfPCell cell = new PdfPCell(new Phrase(row[col].ToString().Replace("<b>", string.Empty).Replace("</b>", string.Empty), new iTextSharp.text.Font(iTextSharp.text.Font.NORMAL, 6, 0))); pdfTable.AddCell(cell); } } } // This code is for totals................ foreach (string col in columns) { // double footer = 0; if (Totals.Where(t => t.ColumnName == col).Any()) { string s = Getvalue(Totals.Where(t => t.ColumnName == col).Select(g => g.Totaltype).SingleOrDefault(), dt, col); PdfPCell cell = new PdfPCell(new Phrase(s, new iTextSharp.text.Font(iTextSharp.text.Font.NORMAL, 8, 0))); pdfTable.AddCell(cell); } else { PdfPCell cell = new PdfPCell(new Phrase(" ", new iTextSharp.text.Font(iTextSharp.text.Font.NORMAL, 8, 0))); pdfTable.AddCell(cell); } } pdfDoc.Add(pdfTable); }
public bool CreateReport(DataTable dt) { _dataTable = dt; _ReportTitle = "Shop to Shop Cash Transfer Details"; _ReportTitleSecondLine = "Transfer # " + _dataTable.Rows[0]["TRANSFERNUMBER"].ToString(); bool isSuccessful = false; iTextSharp.text.Document document = new iTextSharp.text.Document(PageSize.HALFLETTER.Rotate()); try { //set up RunReport event overrides & create doc string reportFileName = Path.GetFullPath(reportObject.ReportTempFileFullName); if (!Directory.Exists(Path.GetDirectoryName(reportFileName))) { Directory.CreateDirectory(Path.GetDirectoryName(reportFileName)); } PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(reportFileName, FileMode.Create)); writer.PageEvent = this; PdfPTable table = new PdfPTable(_Columns); Image gif = Image.GetInstance(Common.Properties.Resources.logo, BaseColor.WHITE); gif.ScalePercent(35); _reportFont = FontFactory.GetFont("Arial", 8, iTextSharp.text.Font.NORMAL); document.AddTitle(reportObject.ReportTitle); document.SetPageSize(PageSize.HALFLETTER.Rotate()); document.SetMargins(-50, -55, 10, 45); table.HeaderRows = 8; PrintReportHeader(table, gif); PrintReportDetailHeader(table); table.SetWidths(new float[] { 1.5f, 2, 1.5f, 2 }); PrintReportDetailValues(table); PrintReportDetailFooter(table); document.Open(); document.Add(table); document.Close(); isSuccessful = true; } catch (DocumentException de) { reportObject.ReportError = de.Message; reportObject.ReportErrorLevel = (int)LogLevel.ERROR; } catch (IOException ioe) { reportObject.ReportError = ioe.Message; reportObject.ReportErrorLevel = (int)LogLevel.ERROR; } return(isSuccessful); }
public static void GetEXTPDFTable(iTextSharp.text.Document pdfDoc, DataTable des, DataTable dt, List <ColumnTotals> Totals) { try { DataTable table1 = new DataTable(); DataTable table2 = new DataTable(); table1.Columns.Clear(); table2.Columns.Clear(); var depts = dt.AsEnumerable().Select(s => s.Field <string>("Cost Centre")).Distinct(); foreach (DataColumn colu in des.Columns) { // if (colu.ColumnName != "Department") // { table1.Columns.Add(colu.ColumnName); //} } foreach (DataColumn colu in dt.Columns) { if (colu.ColumnName != "Cost Centre") { table2.Columns.Add(colu.ColumnName); } } foreach (var v in depts) { pdfDoc.Add(new iTextSharp.text.Paragraph(v.ToString())); pdfDoc.Add(new iTextSharp.text.Paragraph(" ")); table1.Rows.Clear(); table2.Rows.Clear(); var dest = from db in des.AsEnumerable() where db.Field <string>("Department") == v.ToString() select new { Department = db.Field <object>("Department"), Destinationname = db.Field <object>("Destination Name"), Totalcalls = db.Field <object>("Total Calls"), Totalduration = db.Field <object>("Total Duration"), Totalnonform = db.Field <object>("Totalnonform"), Cost = db.Field <object>("Cost") }; foreach (var destinations in dest) { table1.Rows.Add(destinations.Department.ToString(), destinations.Destinationname.ToString(), destinations.Totalcalls.ToString(), destinations.Totalduration.ToString(), destinations.Totalnonform.ToString(), destinations.Cost.ToString()); } GetPDfTable(pdfDoc, table1, 0, false, Totals); pdfDoc.Add(new iTextSharp.text.Paragraph(" ")); var records = from db in dt.AsEnumerable() where db.Field <string>("Cost Centre") == v.ToString() select new { Name = db.Field <object>("Name"), Extension = db.Field <object>("Extension"), OutgoingCalls = db.Field <object>("Outgoing Calls"), OutgoingDuration = db.Field <object>("Outgoing Duration"), outnonformated = db.Field <object>("outdurnonformated"), RingResponse = db.Field <object>("Ring Response"), AbandonedCalls = db.Field <object>("Abandoned Calls"), IncomingCalls = db.Field <object>("Incoming Calls"), IncomingDuration = db.Field <object>("Incoming Duration"), Innonformated = db.Field <object>("indurnonformated"), Cost = db.Field <object>("Cost") }; foreach (var all in records) { table2.Rows.Add(all.Name.ToString(), all.Extension.ToString(), all.OutgoingCalls.ToString(), Convert.ToString(all.OutgoingDuration), Convert.ToString(all.outnonformated), all.RingResponse.ToString(), all.AbandonedCalls.ToString(), all.IncomingCalls.ToString(), Convert.ToString(all.IncomingDuration), Convert.ToString(all.Innonformated), Convert.ToString(all.Cost)); } GetPDfTable(pdfDoc, table2, 0, false, Totals); pdfDoc.Add(new iTextSharp.text.Paragraph(" ")); } } catch { } }
public static ActionResult PDF( int companyId, string from, string to, long rulesId, long processId, string listOrder) { var res = ActionResult.NoAction; var user = HttpContext.Current.Session["User"] as ApplicationUser; Dictionary = HttpContext.Current.Session["Dictionary"] as Dictionary <string, string>; var company = new Company(companyId); string path = HttpContext.Current.Request.PhysicalApplicationPath; if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase)) { path = string.Format(CultureInfo.InvariantCulture, @"{0}\", path); } var formatedDescription = ToolsPdf.NormalizeFileName(company.Name); string fileName = string.Format( CultureInfo.InvariantCulture, @"{0}_{1}_{2:yyyyMMddhhmmss}.pdf", Dictionary["Item_Oportunities"], formatedDescription, DateTime.Now); var pdfDoc = new iTS.Document(iTS.PageSize.A4.Rotate(), 40, 40, 80, 50); var writer = iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDoc, new FileStream( string.Format(CultureInfo.InvariantCulture, @"{0}Temp\{1}", path, fileName), FileMode.Create)); writer.PageEvent = new TwoColumnHeaderFooter() { CompanyLogo = string.Format(CultureInfo.InvariantCulture, @"{0}\images\logos\{1}.jpg", path, company.Id), IssusLogo = string.Format(CultureInfo.InvariantCulture, "{0}issus.png", path), Date = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", DateTime.Now), CreatedBy = user.UserName, CompanyId = company.Id, CompanyName = company.Name, Title = Dictionary["Item_Oportunities"].ToUpperInvariant() }; pdfDoc.Open(); var titleTable = new iTSpdf.PdfPTable(1); titleTable.SetWidths(new float[] { 50f }); titleTable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(CultureInfo.InvariantCulture, "{0} - {1}", Dictionary["Item_EquipmentList"], company.Name), ToolsPdf.LayoutFonts.TitleFont)) { HorizontalAlignment = iTS.Element.ALIGN_CENTER, Border = iTS.Rectangle.NO_BORDER }); #region Criteria var criteriatable = new iTSpdf.PdfPTable(6) { WidthPercentage = 100 }; criteriatable.SetWidths(new float[] { 15f, 50f, 15f, 50f, 15f, 50f }); #region texts string criteriaProccess = Dictionary["Common_All_Male_Plural"]; if (processId > 0) { var process = new Process(processId, companyId); if (!string.IsNullOrEmpty(process.Description)) { criteriaProccess = process.Description; } } string periode = string.Empty; if (!string.IsNullOrEmpty(from) && string.IsNullOrEmpty(to)) { periode = Dictionary["Item_Incident_List_Filter_From"] + " " + from; } else if (string.IsNullOrEmpty(from) && !string.IsNullOrEmpty(to)) { periode = Dictionary["Item_Incident_List_Filter_To"] + " " + to; } else if (!string.IsNullOrEmpty(from) && !string.IsNullOrEmpty(to)) { periode = from + " - " + to; } else { periode = Dictionary["Common_All_Male"]; } string typetext = Dictionary["Common_All_Male_Plural"]; string ruleDescription = Dictionary["Common_All_Female_Plural"]; if (rulesId > 0) { var rule = Rules.GetById(companyId, rulesId); if (!string.IsNullOrEmpty(rule.Description)) { ruleDescription = rule.Description; } } #endregion ToolsPdf.AddCriteria(criteriatable, Dictionary["Common_Period"], periode); ToolsPdf.AddCriteria(criteriatable, Dictionary["Item_BusinesRisk_ListHeader_Process"], typetext); ToolsPdf.AddCriteria(criteriatable, Dictionary["Item_BusinesRisk_ListHeader_Rule"], ruleDescription); pdfDoc.Add(criteriatable); #endregion var table = new iTSpdf.PdfPTable(7) { WidthPercentage = 100, HorizontalAlignment = 1, SpacingBefore = 20f, SpacingAfter = 30f }; table.SetWidths(new float[] { 10f, 10f, 30f, 20f, 20f, 10f, 10f }); table.AddCell(ToolsPdf.HeaderCell(Dictionary["Item_IncidentAction_Header_Type"])); table.AddCell(ToolsPdf.HeaderCell(Dictionary["Item_BusinesRisk_ListHeader_Date"])); table.AddCell(ToolsPdf.HeaderCell(Dictionary["Item_Oportunity"])); table.AddCell(ToolsPdf.HeaderCell(Dictionary["Item_BusinesRisk_ListHeader_Process"])); table.AddCell(ToolsPdf.HeaderCell(Dictionary["Item_BusinesRisk_ListHeader_Rule"])); table.AddCell(ToolsPdf.HeaderCell(Dictionary["Item_BusinesRisk_ListHeader_StartValue"])); table.AddCell(ToolsPdf.HeaderCell(Dictionary["Item_BusinesRisk_ListHeader_IPR"])); int cont = 0; var data = HttpContext.Current.Session["OportunityFilterData"] as List <OportunityFilterItem>; switch (listOrder.ToUpperInvariant()) { default: case "TH1|ASC": data = data.OrderBy(d => d.OpenDate).ToList(); break; case "TH1|DESC": data = data.OrderByDescending(d => d.OpenDate).ToList(); break; case "TH2|ASC": data = data.OrderBy(d => d.Description).ToList(); break; case "TH2|DESC": data = data.OrderByDescending(d => d.Description).ToList(); break; case "TH3|ASC": data = data.OrderBy(d => d.Process.Description).ToList(); break; case "TH3|DESC": data = data.OrderByDescending(d => d.Process.Description).ToList(); break; case "TH4|ASC": data = data.OrderBy(d => d.Rule.Description).ToList(); break; case "TH4|DESC": data = data.OrderByDescending(d => d.Rule.Description).ToList(); break; case "TH5|ASC": data = data.OrderBy(d => d.Rule.Limit).ToList(); break; case "TH5|DESC": data = data.OrderByDescending(d => d.Rule.Limit).ToList(); break; } foreach (OportunityFilterItem risk in data) { cont++; string typeText = string.Empty; if (risk.Result == 0) { typeText = Dictionary["Item_BusinessRisk_Status_Unevaluated"]; } else if (risk.Result < risk.Rule.Limit) { typeText = Dictionary["Item_BusinessRisk_Status_NotSignificant"]; } else { typeText = Dictionary["Item_BusinessRisk_Status_Significant"]; } string initialResultText = risk.Result == 0 ? string.Empty : risk.Result.ToString(); table.AddCell(ToolsPdf.DataCellCenter(typeText)); table.AddCell(ToolsPdf.DataCellCenter(risk.OpenDate)); table.AddCell(ToolsPdf.DataCell(risk.Description)); table.AddCell(ToolsPdf.DataCell(risk.Process.Description)); table.AddCell(ToolsPdf.DataCellCenter(risk.Rule.Description)); table.AddCell(ToolsPdf.DataCellCenter(initialResultText)); table.AddCell(ToolsPdf.DataCellRight(risk.Rule.Limit)); } table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format( CultureInfo.InvariantCulture, @"{0}: {1}", Dictionary["Common_RegisterCount"], cont), ToolsPdf.LayoutFonts.Times)) { Border = iTS.Rectangle.TOP_BORDER, Padding = 6f, PaddingTop = 4f, Colspan = 4 }); table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Empty, ToolsPdf.LayoutFonts.Times)) { Border = iTS.Rectangle.TOP_BORDER, Colspan = 4 }); pdfDoc.Add(table); pdfDoc.CloseDocument(); res.SetSuccess(string.Format(CultureInfo.InvariantCulture, @"{0}Temp/{1}", ConfigurationManager.AppSettings["siteUrl"], fileName)); return(res); }
private void ButtonHome2_Click(object sender, EventArgs e) { string name = ""; try { Panel p = (Panel)sender; name = f.GetNameOfButton(p); } catch { } try { Label l = (Label)sender; name = l.Text; } catch { } try { PictureBox pb = (PictureBox)sender; name = f.GetNameOfButton(panel2, pb); } catch { } if (name == "Удалить") { if (State.GetType() == typeof(Agencies)) { Agencies cur = (Agencies)State; MyMessageBox message = new MyMessageBox(this, "Предупреждение", $"Вы хотите удалить это турагенство ({cur.dataGridView1.SelectedRows.Count}), его аккаунт и все путевки?", "Да", "Нет", "Удаление_Агентства_Да", "Выход_Нет"); message.Show(); } if (State.GetType() == typeof(OneHotel)) { OneHotel cur = (OneHotel)State; MyMessageBox message = new MyMessageBox(this, "Предупреждение", $"Вы хотите удалить этот тип номера ({cur.dataGridView1.SelectedRows.Count})?", "Да", "Нет", "Удаление_Номера_Да", "Выход_Нет"); message.Show(); } if (State.GetType() == typeof(OneVoucher)) { OneVoucher cur = (OneVoucher)State; MyMessageBox message = new MyMessageBox(this, "Предупреждение", $"Вы хотите удалить эту составляющую путевки?", "Да", "Нет", "Удаление_Человека_Полета_Да", "Выход_Нет"); message.Show(); } if (State.GetType() == typeof(Vouchers)) { Vouchers cur = (Vouchers)State; MyMessageBox message = new MyMessageBox(this, "Предупреждение", $"Вы хотите удалить эту путевку ({cur.dataGridView1.SelectedRows.Count})?", "Да", "Нет", "Удаление_Путевки_Да", "Выход_Нет"); message.Show(); } if (State.GetType() == typeof(Hotels)) { Hotels cur = (Hotels)State; MyMessageBox message = new MyMessageBox(this, "Предупреждение", $"Вы хотите удалить этот отель ({cur.dataGridView1.SelectedRows.Count}) и все его путевки?", "Да", "Нет", "Удаление_Отеля_Да", "Выход_Нет"); message.Show(); } if (State.GetType() == typeof(Routes)) { Routes cur = (Routes)State; MyMessageBox message = new MyMessageBox(this, "Предупреждение", $"Вы хотите удалить этот рейс ({cur.dataGridView1.SelectedRows.Count}) и отменить все путевки по нем?", "Да", "Нет", "Удаление_Рейса_Да", "Выход_Нет"); message.Show(); } if (State.GetType() == typeof(Accounts)) { Accounts cur = (Accounts)State; int i = cur.dataGridView1.SelectedRows.Count; i = Math.Max(i, cur.dataGridView2.SelectedRows.Count); string str = $"Вы хотите удалить этот аккаунт ({i}), его тураегнтство и все путевки?"; if (cur.dataGridView2.SelectedRows.Count != 0) { str = $"Вы хотите удалить этот аккаунт ({i})?"; } MyMessageBox message = new MyMessageBox(this, "Предупреждение", str, "Да", "Нет", "Удаление_Аккаунта_Да", "Выход_Нет"); message.Show(); } } if (name == "Изменить") { if (State.GetType() == typeof(Agencies)) { Agencies cur = (Agencies)State; AddTouragency at = new AddTouragency(this); at.label4.Text = "Edit Touragency"; at.Yes.Text = "Изменить"; at.textBox0.Text = cur.dataGridView1.SelectedRows[0].Cells[0].Value.ToString(); at.comboBox1.Visible = false; at.textBox2.Visible = true; at.label8.Visible = false; at.textBox2.Text = cur.dataGridView1.SelectedRows[0].Cells[2].Value.ToString(); at.textBox1.Text = cur.dataGridView1.SelectedRows[0].Cells[1].Value.ToString(); at.dateTimePicker1.Text = cur.dataGridView1.SelectedRows[0].Cells[3].Value.ToString(); at.textBox3.Text = cur.dataGridView1.SelectedRows[0].Cells[4].Value.ToString(); at.Show(); } if (State.GetType() == typeof(Vouchers)) { DataGridViewRow cur = ((Vouchers)State).dataGridView1.SelectedRows[0]; AddVoucher at = new AddVoucher(this); at.label4.Text = "Edit Voucher"; at.Yes.Text = "Изменить"; at.textBox2.Text = cur.Cells[0].Value.ToString(); at.comboBox5.SelectedItem = cur.Cells[5].Value.ToString(); at.dateTimePicker1.Value = Convert.ToDateTime(cur.Cells[3].Value.ToString()); c.Open(); string sql = $"SELECT Agency.Name, a.Name, aa.Name, Airport.Code, Airport.Name, h.Name, hh.Name" + $", Hotel.Name, Room.TypeRoom, Voucher.NumNights " + "FROM Agency, Country a, Country h, City aa, City hh, Airport, Hotel, Room, voucher " + $"WHERE Voucher.ID = '{cur.Cells[0].Value.ToString()}' AND Voucher.idTypeRoom = Room.ID AND Voucher.CodeAirport = Airport.Code " + "AND Airport.idCity = aa.ID AND aa.idCountry = a.ID AND Room.idHotel = Hotel.ID AND Hotel.idCity = hh.ID " + "AND hh.idCountry = h.ID AND Voucher.Login = Agency.Login"; MySqlCommand command1 = new MySqlCommand(sql, c); MySqlDataReader reader1 = command1.ExecuteReader(); reader1.Read(); at.comboBox8.SelectedItem = reader1[0].ToString(); at.comboBox7.SelectedItem = reader1[1].ToString(); at.comboBox6.SelectedItem = reader1[2].ToString(); at.comboBox9.SelectedItem = reader1[3].ToString() + $" ({reader1[4].ToString()})"; at.comboBox2.SelectedItem = reader1[5].ToString(); at.comboBox3.SelectedItem = reader1[6].ToString(); at.comboBox1.SelectedItem = reader1[7].ToString(); at.comboBox4.SelectedItem = reader1[8].ToString(); at.textBox1.Text = reader1[9].ToString(); c.Close(); at.Show(); } if (State.GetType() == typeof(OneHotel)) { OneHotel cur = (OneHotel)State; AddRoom at = new AddRoom(this); at.label4.Text = "Edit Room"; at.Yes.Text = "Изменить"; at.textBox1.Text = cur.dataGridView1.SelectedRows[0].Cells[0].Value.ToString(); at.textBox2.Text = cur.dataGridView1.SelectedRows[0].Cells[2].Value.ToString().Split(' ')[0]; at.textBox3.Text = cur.dataGridView1.SelectedRows[0].Cells[1].Value.ToString(); at.Show(); } if (State.GetType() == typeof(Routes)) { AddRoute at = new AddRoute(this, false); at.Show(); } if (State.GetType() == typeof(Accounts)) { Accounts cur = (Accounts)State; string p = ""; if (cur.dataGridView1.SelectedRows.Count != 0) { p = cur.dataGridView1.SelectedRows[0].Cells[1].Value.ToString(); } else { p = cur.dataGridView2.SelectedRows[0].Cells[0].Value.ToString(); } AddAccount at = new AddAccount(new AddTouragency(this), new User(p)); at.label4.Text = "Edit Account"; at.Yes.Text = "Изменить"; if (cur.dataGridView1.SelectedRows.Count != 0) { at.textBox0.Text = cur.dataGridView1.SelectedRows[0].Cells[1].Value.ToString(); at.comboBox1.Visible = false; at.textBox2.Visible = true; at.textBox1.Text = cur.dataGridView1.SelectedRows[0].Cells[2].Value.ToString(); at.Show(); } else { at.textBox0.Text = cur.dataGridView2.SelectedRows[0].Cells[0].Value.ToString(); at.comboBox1.Visible = false; at.textBox2.Visible = true; at.textBox2.Text = "Администратор"; at.textBox1.Text = cur.dataGridView2.SelectedRows[0].Cells[1].Value.ToString(); at.Show(); } } if (State.GetType() == typeof(Hotels)) { Hotels cur = (Hotels)State; AddHotel at = new AddHotel(this); at.label4.Text = "Edit Hotel"; at.Yes.Text = "Изменить"; at.textBox0.Text = cur.dataGridView1.SelectedRows[0].Cells[0].Value.ToString(); at.textBox1.Text = cur.dataGridView1.SelectedRows[0].Cells[1].Value.ToString(); string str = cur.dataGridView1.SelectedRows[0].Cells[2].Value.ToString(); switch (str) { case "RO": str = "RO - Room Only"; break; case "BB": str = "BB - Bed & Breakfast"; break; case "HB": str = "HB - Half Board"; break; case "FB": str = "FB - Full Board"; break; case "AI": str = "AI - All Inclusive"; break; case "UAI": str = "UAI - Ultra All Inclusive"; break; } at.comboBox1.Text = str; at.comboBox2.SelectedItem = cur.dataGridView1.SelectedRows[0].Cells[4].Value.ToString(); at.comboBox3.SelectedItem = cur.dataGridView1.SelectedRows[0].Cells[3].Value.ToString(); at.ID = int.Parse(cur.dataGridView1.SelectedRows[0].Cells[5].Value.ToString()); at.Show(); } } if (name == "Добавить") { if (State.GetType() == typeof(Agencies)) { Agencies cur = (Agencies)State; AddTouragency at = new AddTouragency(this); at.Show(); } if (State.GetType() == typeof(OneHotel)) { OneHotel cur = (OneHotel)State; AddRoom at = new AddRoom(this); at.Show(); } if (State.GetType() == typeof(Accounts)) { Accounts acc = (Accounts)State; AddAccount aa = new AddAccount(new AddTouragency(this)); aa.Show(); } if (State.GetType() == typeof(Hotels)) { Hotels acc = (Hotels)State; AddHotel aa = new AddHotel(this); aa.Show(); } if (State.GetType() == typeof(Routes)) { Routes acc = (Routes)State; AddRoute aa = new AddRoute(this); aa.Show(); } if (State.GetType() == typeof(Vouchers)) { AddVoucher aa = new AddVoucher(this); aa.Show(); } } if (name == "Фильтр") { if (State.GetType() == typeof(Agencies)) { string SQL1 = "SELECT Max(comission) FROM Agency"; string SQL2 = "SELECT Min(comission) FROM Agency"; string SQL3 = "SELECT Max(dateLicense) FROM Agency"; string SQL4 = "SELECT Min(dateLicense) FROM Agency"; int maxc = 0; c.Open(); MySqlCommand command = new MySqlCommand(SQL1, c); MySqlDataReader reader = command.ExecuteReader(); while (reader.Read()) { maxc = Convert.ToInt32(reader[0]); } c.Close(); Agencies cur = (Agencies)State; FilterAgency filter = new FilterAgency(this); int minc = 0; c.Open(); MySqlCommand command1 = new MySqlCommand(SQL2, c); MySqlDataReader reader1 = command1.ExecuteReader(); while (reader1.Read()) { minc = Convert.ToInt32(reader1[0]); } c.Close(); DateTime maxd = new DateTime(); c.Open(); MySqlCommand command2 = new MySqlCommand(SQL3, c); MySqlDataReader reader2 = command2.ExecuteReader(); while (reader2.Read()) { maxd = Convert.ToDateTime(reader2[0]); } c.Close(); DateTime mind = new DateTime(); c.Open(); MySqlCommand command3 = new MySqlCommand(SQL4, c); MySqlDataReader reader3 = command3.ExecuteReader(); while (reader3.Read()) { mind = Convert.ToDateTime(reader3[0]); } c.Close(); filter.textBox3.Text = minc.ToString(); filter.textBox4.Text = maxc.ToString(); filter.dateTimePicker1.Value = mind; filter.dateTimePicker2.Value = maxd; filter.Show(); } if (State.GetType() == typeof(Hotels)) { Hotels acc = (Hotels)State; AddHotel aa = new AddHotel(this); aa.label4.Text = "Filter"; aa.Yes.Visible = false; aa.No.Visible = false; aa.button1.Visible = true; aa.label7.Visible = false; aa.label8.Visible = false; aa.Show(); } if (State.GetType() == typeof(Routes)) { Routes acc = (Routes)State; FilterRoute aa = new FilterRoute(this); aa.label4.Text = "Filter"; aa.Show(); } } if (name == "Выполнить") { if (State.GetType() == typeof(SQLQuery)) { SQLQuery sq = (SQLQuery)State; c.Open(); MySqlCommand command = new MySqlCommand(sq.richTextBox1.Text, c); MySqlDataReader reader = command.ExecuteReader(); sq.dataGridView1.Rows.Clear(); sq.dataGridView1.Columns.Clear(); for (int i = 0; i < reader.VisibleFieldCount; i++) { DataGridViewTextBoxColumn column = new DataGridViewTextBoxColumn(); column.Name = "column" + i; column.HeaderText = reader.GetName(i); column.Width = (sq.dataGridView1.Width - 35) / reader.VisibleFieldCount; sq.dataGridView1.Columns.Add(column); } while (reader.Read()) { int num = sq.dataGridView1.Rows.Add(); for (int i = 0; i < reader.FieldCount; i++) { sq.dataGridView1.Rows[num].Cells[i].Value = reader[i]; if (reader[i].GetType() == typeof(DateTime)) { DateTime dt = Convert.ToDateTime(reader[i]); if (dt.Hour == 0 && dt.Minute == 0 && dt.Second == 0) { sq.dataGridView1.Rows[num].Cells[i].Value = dt.ToShortDateString(); } } } } c.Close(); } } if (name == "Очистить") { if (State.GetType() == typeof(SQLQuery)) { SQLQuery sq = (SQLQuery)State; sq.richTextBox1.Text = "SELECT"; sq.richTextBox1.SelectionStart = 6; sq.richTextBox1.SelectionLength = 0; } } if (name == "Справка") { if (State.GetType() == typeof(SQLQuery)) { Help h = new Help(); h.Show(); } } if (name == "Просмотр") { if (State.GetType() == typeof(Hotels)) { Hotels h = (Hotels)State; Controls.Remove(State); OneHotel ag = new OneHotel(this, new Hotel(Convert.ToInt32(h.dataGridView1.SelectedRows[0].Cells[5].Value))); State = ag; this.Controls.Add(ag); ag.Location = new Point(panel3.Location.X + panel3.Size.Width, panel3.Location.Y + panel3.Size.Height + PanelForm.Size.Height); ag.Visible = true; ag.Show(); } if (State.GetType() == typeof(Agencies)) { Agencies h = (Agencies)State; Controls.Remove(State); OneAgency ag = new OneAgency(this, new Touragency(h.dataGridView1.SelectedRows[0].Cells[2].Value.ToString())); State = ag; this.Controls.Add(ag); ag.Location = new Point(panel3.Location.X + panel3.Size.Width, panel3.Location.Y + panel3.Size.Height + PanelForm.Size.Height); ag.Visible = true; ag.Show(); } if (State.GetType() == typeof(Vouchers)) { Vouchers h = (Vouchers)State; OneVoucher ag = new OneVoucher(this); Controls.Remove(State); State = ag; this.Controls.Add(ag); ag.Location = new Point(panel3.Location.X + panel3.Size.Width, panel3.Location.Y + panel3.Size.Height + PanelForm.Size.Height); ag.Visible = true; ag.Show(); } } if (name == "Обновить") { if (State.GetType() == typeof(Routes)) { UpdateRoutes u = new UpdateRoutes(); u.Show(); } if (State.GetType() == typeof(Agencies)) { UpdateRoutes u = new UpdateRoutes(this, 1); u.Show(); } } if (name == "Отчет") { if (State.GetType() == typeof(OneAgency)) { OneAgency a = (OneAgency)State; var document = new iTextSharp.text.Document(); using (var writer = PdfWriter.GetInstance(document, new FileStream("ReportTourAgency.pdf", FileMode.Create))) { document.Open(); BaseFont baseFont = BaseFont.CreateFont(Environment.GetEnvironmentVariable("windir") + @"\fonts\arial.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED); iTextSharp.text.Font font = new iTextSharp.text.Font(baseFont, 20, 0); document.Add(new Paragraph($"{a.label1.Text}", new iTextSharp.text.Font(baseFont, 30, 0))); document.Add(new Paragraph($" ", new iTextSharp.text.Font(baseFont, 10, 0))); iTextSharp.text.pdf.PdfContentByte cb = writer.DirectContent; cb.MoveTo(30, 745); cb.LineTo(560, 745); cb.Stroke(); document.Add(new Paragraph($"{a.label2.Text}", font)); document.Add(new Paragraph($"{a.label4.Text}", font)); document.Add(new Paragraph($"{a.label3.Text}", font)); document.Add(new Paragraph($"{a.label6.Text}", font)); document.Add(new Paragraph($" ", new iTextSharp.text.Font(baseFont, 3, 0))); DataGridView d = a.dataGridView1; int sum = 0; int suma = 0; int sumb = 0; for (int i = 0; i < d.Rows.Count; i++) { if (d.Rows[i].Cells[4].Value.ToString() == "Выполнено" || d.Rows[i].Cells[4].Value.ToString() == "В процессе" || d.Rows[i].Cells[4].Value.ToString() == "Оплачено") { if (DateTime.Now <= Convert.ToDateTime(d.Rows[i].Cells[2].Value.ToString()).AddYears(1)) { if (DateTime.Now <= Convert.ToDateTime(d.Rows[i].Cells[2].Value.ToString()).AddMonths(1)) { sumb += Convert.ToInt32(d.Rows[i].Cells[3].Value); } suma += Convert.ToInt32(d.Rows[i].Cells[3].Value); } sum += Convert.ToInt32(d.Rows[i].Cells[3].Value); } } document.Add(new Paragraph($"Прибыль от турагентства за все время: {sum}$", font)); document.Add(new Paragraph($"Прибыль от турагентства за месяц: {sumb}$", font)); document.Add(new Paragraph($"Прибыль от турагентства за год: {suma}$", font)); bool t = false; for (int i = 0; i < d.Rows.Count; i++) { if (d.Rows[i].Cells[4].Value.ToString() == "Забронировано") { if (!t) { document.Add(new Paragraph($"К оплате:", font)); t = true; } document.Add(new Paragraph($" Путевка №{d.Rows[i].Cells[0].Value.ToString()} - {d.Rows[i].Cells[3].Value.ToString()}$ ", font)); } } document.Add(new Paragraph($" ", font)); document.Add(new Paragraph($" ", font)); document.Add(new Paragraph("Дата создания отчета: " + DateTime.Now.ToString(), new iTextSharp.text.Font(baseFont, 10, 0))); document.Close(); writer.Close(); ReportPDF r = new ReportPDF(true); } } if (State.GetType() == typeof(OneVoucher)) { OneVoucher a = (OneVoucher)State; var document = new Document(); using (var writer = PdfWriter.GetInstance(document, new FileStream("ReportVoucher.pdf", FileMode.Create))) { document.Open(); BaseFont baseFont = BaseFont.CreateFont(Environment.GetEnvironmentVariable("windir") + @"\fonts\arial.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED); iTextSharp.text.Font font = new iTextSharp.text.Font(baseFont, 20, 0); document.Add(new Paragraph($"{a.label1.Text}", new iTextSharp.text.Font(baseFont, 30, 0))); document.Add(new Paragraph($" ", new iTextSharp.text.Font(baseFont, 10, 0))); iTextSharp.text.pdf.PdfContentByte cb = writer.DirectContent; cb.MoveTo(30, 745); cb.LineTo(560, 745); cb.Stroke(); document.Add(new Paragraph($"{a.label4.Text}", font)); document.Add(new Paragraph($"{a.label6.Text}", font)); document.Add(new Paragraph($"{a.label3.Text}", font)); document.Add(new Paragraph($"{a.label8.Text}", font)); document.Add(new Paragraph($"{a.label7.Text}", font)); document.Add(new Paragraph($"{a.label2.Text}", font)); document.Add(new Paragraph($"Перелеты: ", font)); document.Add(new Paragraph($" ", font)); PdfPTable table = new PdfPTable(4); for (int g = 0; g < 4; g++) { table.AddCell(new Paragraph($"{a.dataGridView2.Columns[g].HeaderText}", new iTextSharp.text.Font(baseFont, 10, 0))); } for (int g = 0; g < a.dataGridView2.Rows.Count; g++) { for (int s = 0; s < a.dataGridView2.Rows[g].Cells.Count - 1; s++) { table.AddCell(new Paragraph($"{a.dataGridView2.Rows[g].Cells[s].Value.ToString()}", new iTextSharp.text.Font(baseFont, 10, 0))); } } document.Add(table); document.Add(new Paragraph($"Люди: ", font)); document.Add(new Paragraph($" ", font)); PdfPTable table1 = new PdfPTable(6); for (int g = 0; g < 6; g++) { table1.AddCell(new Paragraph($"{a.dataGridView1.Columns[g].HeaderText}", new iTextSharp.text.Font(baseFont, 10, 0))); } for (int g = 0; g < a.dataGridView1.Rows.Count; g++) { for (int s = 0; s < a.dataGridView1.Rows[g].Cells.Count; s++) { table1.AddCell(new Paragraph($"{a.dataGridView1.Rows[g].Cells[s].Value.ToString()}", new iTextSharp.text.Font(baseFont, 10, 0))); } } document.Add(table1); document.Add(new Paragraph($" ", font)); document.Add(new Paragraph($" ", font)); document.Add(new Paragraph("Дата создания отчета: " + DateTime.Now.ToString(), new iTextSharp.text.Font(baseFont, 10, 0))); document.Close(); writer.Close(); ReportPDF r = new ReportPDF(false); } } } }
private void setBillPageBody(iTextSharp.text.Document document, OPDHistoryModel model) { try { var boldTableFont = FontFactory.GetFont("verdana", Convert.ToInt32(ConfigurationManager.AppSettings["bodyboldTable11"]), iTextSharp.text.Font.BOLD); var bodyFontNormal = FontFactory.GetFont("verdana", Convert.ToInt32(ConfigurationManager.AppSettings["bodyboldTable12"]), iTextSharp.text.Font.NORMAL); var headerFont = FontFactory.GetFont("verdana", Convert.ToInt32(ConfigurationManager.AppSettings["headerFont"]), iTextSharp.text.Font.BOLD, iTextSharp.text.Color.BLACK); setBillPageHeader(document); //Patient Details PdfPTable table = new PdfPTable(2); table.DeleteBodyRows(); table.WidthPercentage = 100; table.HorizontalAlignment = 0; table.SpacingBefore = 5; table.SpacingAfter = 10; newCell(table, "Name : " + model.PatientDetails.FullName, boldTableFont, 0, 0); newCell(table, "Date. : " + model.InTime.Value.ToShortDateString(), boldTableFont, 2, 0); newCell(table, "O.P.D No. : " + model.CasePaperNumber, boldTableFont, 0, 0); newCell(table, "Receipt No. : " + new BillHistory().GetByOPDId(model.Id.Value).ReceiptNumber.ToString(), boldTableFont, 2, 0); document.Add(table); // Bill Details table = new PdfPTable(3); table.DeleteBodyRows(); table.WidthPercentage = 100; table.HorizontalAlignment = 0; table.SpacingBefore = 5; table.SpacingAfter = 10; newCell(table, "Received for ", boldTableFont, -1, -1, 2); newCell(table, "Rs", boldTableFont, 1, -1); int srNo = 1; newCell(table, srNo.ToString(), bodyFontNormal, 1, 4); newCell(table, "Conc. FEE. :", bodyFontNormal, 0, 8); PdfPCell cell = new PdfPCell(new Phrase(model.Amount.ToString(), bodyFontNormal)); cell.HorizontalAlignment = Element.ALIGN_CENTER; cell.Border = PdfCell.LEFT_BORDER; cell.Border = PdfCell.RIGHT_BORDER; table.AddCell(cell); if (model.LabTestingAmount.HasValue && model.LabTestingAmount.Value != Convert.ToDecimal(0.00)) { srNo++; newCell(table, srNo.ToString(), bodyFontNormal, 1, 4); newCell(table, "Labarotry. FEE. ", bodyFontNormal, 0, 8); newCell(table, model.LabTestingAmount.ToString(), bodyFontNormal, 1, 8); } newCell(table, "Total", boldTableFont, 2, -1, 2); newCell(table, model.TotalAmount.ToString(), boldTableFont, 1, -1, 2); for (int i = 0; i < 5; i++) { blankCell(table, 3); } newCell(table, "Signature", boldTableFont, 2, 0, 3); table.SetWidths(new int[] { 1, 12, 6 }); document.Add(table); } catch (Exception ex) { throw ex; } }
public bool CreateReport() { bool isSuccessful = false; iTextSharp.text.Document document = new iTextSharp.text.Document(PageSize.HALFLETTER.Rotate()); try { //set up RunReport event overrides & create doc TerminatedLayawayPickingSlip events = this; PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(ReportObject.ReportTempFileFullName, FileMode.Create)); writer.PageEvent = events; MultiColumnText columns = new MultiColumnText(document.PageSize.Top - 90, document.PageSize.Height - (90)); float pageLeft = document.PageSize.Left; float pageright = document.PageSize.Right; columns.AddSimpleColumn(-27, document.PageSize.Width + 29); //set up tables, etc... PdfPTable table = new PdfPTable(7); table.WidthPercentage = 85;// document.PageSize.Width; PdfPCell cell = new PdfPCell(); Image gif = Image.GetInstance(Resources.logo, BaseColor.WHITE); gif.ScalePercent(25); runReport = new LayawayRunReports(); document.Open(); document.SetPageSize(PageSize.HALFLETTER.Rotate()); document.SetMargins(-100, -100, 10, 45); document.AddTitle(ReportObject.ReportTitle + ": " + DateTime.Now.ToString("MM/dd/yyyy")); //int layawayCount = ReportObject.TerminatedLayawayPickingSlipList.Count; //int counter = 1; //foreach (LayawayVO layaway in ReportObject.TerminatedLayawayPickingSlipList) //{ WriteCell(table, "Ticket #: " + ReportObject.TerminatedLayaway.TicketNumber.ToString(), ReportFontBold, 9, Rectangle.ALIGN_CENTER, Rectangle.NO_BORDER); WriteInfo(table, ReportObject.TerminatedLayaway); DrawLine(table); WritePaymentList(table, ReportObject.TerminatedLayaway); DrawLine(table); WriteDetail(table, ReportObject.TerminatedLayaway); /*while (counter < layawayCount) * { * WriteCell(table, string.Empty, ReportFont, 7, Rectangle.ALIGN_CENTER, Rectangle.NO_BORDER); * WriteCell(table, string.Empty, ReportFont, 7, Rectangle.ALIGN_CENTER, Rectangle.NO_BORDER); * WriteCell(table, string.Empty, ReportFont, 7, Rectangle.ALIGN_CENTER, Rectangle.NO_BORDER); * WriteCell(table, string.Empty, ReportFont, 7, Rectangle.ALIGN_CENTER, Rectangle.NO_BORDER); * WriteCell(table, string.Empty, ReportFont, 7, Rectangle.ALIGN_CENTER, Rectangle.NO_BORDER); * WriteCell(table, string.Empty, ReportFont, 7, Rectangle.ALIGN_CENTER, Rectangle.NO_BORDER); * WriteCell(table, string.Empty, ReportFont, 7, Rectangle.ALIGN_CENTER, Rectangle.NO_BORDER); * WriteCell(table, string.Empty, ReportFont, 7, Rectangle.ALIGN_CENTER, Rectangle.NO_BORDER); * WriteCell(table, string.Empty, ReportFont, 7, Rectangle.ALIGN_CENTER, Rectangle.NO_BORDER); * WriteCell(table, string.Empty, ReportFont, 7, Rectangle.ALIGN_CENTER, Rectangle.NO_BORDER); * break; * } * counter++; * }*/ columns.AddElement(table); document.Add(columns); document.Close(); //OpenFile(); //CreateReport(); isSuccessful = true; } catch (DocumentException de) { ReportObject.ReportError = de.Message; ReportObject.ReportErrorLevel = (int)LogLevel.ERROR; } catch (IOException ioe) { ReportObject.ReportError = ioe.Message; ReportObject.ReportErrorLevel = (int)LogLevel.ERROR; } return(isSuccessful); }
protected void PDFLST(object sender, EventArgs e) { Buscadores bus = new Buscadores(); List <stock> Lstock = bus.listastock(); DataTable dt = new DataTable(); dt.Columns.AddRange(new DataColumn[4] { new DataColumn("Codigo"), new DataColumn("Detalle"), new DataColumn("Marca"), new DataColumn("Cantidad") }); foreach (stock ostock in Lstock) { dt.Rows.Add(ostock.codigo, ostock.detalle, ostock.marca, ostock.cantidad); } iTextSharp.text.Rectangle rec = new iTextSharp.text.Rectangle(PageSize.A4); var doc = new iTextSharp.text.Document(rec); rec.BackgroundColor = new BaseColor(System.Drawing.Color.Olive); doc.SetPageSize(iTextSharp.text.PageSize.A4); string path = Server.MapPath("~"); PdfWriter.GetInstance(doc, new FileStream(path + "/ReportesLST.pdf", FileMode.Create)); doc.Open(); //Cabecera BaseFont bfntHead = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); iTextSharp.text.Font fntHead = new iTextSharp.text.Font(bfntHead, 16, 1, iTextSharp.text.BaseColor.GREEN.Darker()); Paragraph prgHeading = new Paragraph(); prgHeading.Alignment = Element.ALIGN_LEFT; prgHeading.Add(new Chunk("Taller de Reparaciones Reportes PDF".ToUpper(), fntHead)); doc.Add(prgHeading); //Generado By Paragraph prgGeneratedBY = new Paragraph(); BaseFont btnAuthor = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); iTextSharp.text.Font fntAuthor = new iTextSharp.text.Font(btnAuthor, 8, 2, iTextSharp.text.BaseColor.BLACK); prgGeneratedBY.Alignment = Element.ALIGN_RIGHT; prgGeneratedBY.Add(new Chunk("Generado por: " + LogEmpleado.nombreyapellido, fntAuthor)); //Agregar LOG Empleado prgGeneratedBY.Add(new Chunk("\nFecha Generada : " + DateTime.Now.ToShortDateString(), fntAuthor)); doc.Add(prgGeneratedBY); //La f Linea Paragraph p = new Paragraph(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(0.0F, 100.0F, iTextSharp.text.BaseColor.BLACK, Element.ALIGN_LEFT, 1))); doc.Add(p); //Espacio doc.Add(new Chunk("\n", fntHead)); //Tabla PdfPTable table = new PdfPTable(dt.Columns.Count); for (int i = 0; i < dt.Columns.Count; i++) { string cellText = Server.HtmlDecode(dt.Columns[i].ColumnName); PdfPCell cell = new PdfPCell(); cell.Phrase = new Phrase(cellText, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 10, 1, new BaseColor(System.Drawing.ColorTranslator.FromHtml("#000000")))); cell.BackgroundColor = new BaseColor(System.Drawing.ColorTranslator.FromHtml("#C8C8C8")); cell.HorizontalAlignment = Element.ALIGN_CENTER; cell.PaddingBottom = 5; table.AddCell(cell); } //Agregando Campos a la tabla for (int i = 0; i < dt.Rows.Count; i++) { for (int j = 0; j < dt.Columns.Count; j++) { table.AddCell(dt.Rows[i][j].ToString()); } } doc.Add(table); doc.Close(); Page.ClientScript.RegisterStartupScript(this.GetType(), "OpenWindow", "window.open('ReportesLST.pdf','_newtab');", true); }
protected void btnDispAadhar_Click(object sender, EventArgs e) { Button btn = (Button)sender; GridViewRow gvr = (GridViewRow)btn.NamingContainer; int rowindex = gvr.RowIndex; string ApplicationNumber = ArivugvCWApprove.DataKeys[rowindex].Values["ApplicationNumber"].ToString(); string filepath = HttpContext.Current.Server.MapPath("~/DownloadFiles/"); string filename1 = ApplicationNumber + "Aadhar1.png"; string filename2 = ApplicationNumber + "Aadhar2.png"; string filename3 = ApplicationNumber + "Aadhar.pdf"; string sPathToSaveFileTo1 = filepath + filename1; string sPathToSaveFileTo2 = filepath + filename2; string sPathToSaveFileTo3 = filepath + filename3; string DBFile = "ImgAadharFront"; //ViewFile(DBFile, ApplicationNumber, filename, sPathToSaveFileTo, "[KACDC].[dbo].[ArivuEduLoan]"); using (kvdConn) { kvdConn.Open(); using (SqlCommand cmd = new SqlCommand("select ImgAadharFront,ImgAadharBack from [KACDC].[dbo].[ArivuEduLoan] where [ApplicationNumber]='" + ApplicationNumber + "' ", kvdConn)) { using (SqlDataReader dr1 = cmd.ExecuteReader(System.Data.CommandBehavior.Default)) { if (dr1.Read()) { // read in using GetValue and cast to byte array byte[] fileData1 = ((byte[])dr1["ImgAadharFront"]); // write bytes to disk as file using (System.IO.FileStream fs = new System.IO.FileStream(sPathToSaveFileTo1, System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite)) { // use a binary writer to write the bytes to disk using (System.IO.BinaryWriter bw = new System.IO.BinaryWriter(fs)) { bw.Write(fileData1); bw.Close(); } } byte[] fileData2 = ((byte[])dr1["ImgAadharBack"]); // write bytes to disk as file using (System.IO.FileStream fs = new System.IO.FileStream(sPathToSaveFileTo2, System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite)) { // use a binary writer to write the bytes to disk using (System.IO.BinaryWriter bw = new System.IO.BinaryWriter(fs)) { bw.Write(fileData2); bw.Close(); } } } dr1.Close(); } } } using (var doc1 = new iTextSharp.text.Document()) { PdfWriter writer = PdfWriter.GetInstance(doc1, new FileStream(sPathToSaveFileTo3, FileMode.Create)); doc1.Open(); //Add the Image file to the PDF document object. iTextSharp.text.Image img1 = iTextSharp.text.Image.GetInstance(sPathToSaveFileTo1); iTextSharp.text.Image img2 = iTextSharp.text.Image.GetInstance(sPathToSaveFileTo2); doc1.Add(new Paragraph("AAdhar Front")); doc1.Add(img1); doc1.Add(new Paragraph("AAdhar Back")); doc1.Add(img2); doc1.Close(); } //Download the PDF file. //Response.ContentType = "application/pdf"; //Response.AddHeader("content-disposition", "attachment;filename=ImageExport.pdf"); //Response.Cache.SetCacheability(HttpCacheability.NoCache); //Response.Write(pdfDoc); //Response.End(); callaadhar(filename3); }
protected void PDFRPE(object sender, EventArgs e) { if (((FechaFinale.Value != "") && (FechaInicios.Value != ""))) { Buscadores bus = new Buscadores(); DateTime oDateinicio = Convert.ToDateTime(FechaInicios.Value); DateTime oDatefin = Convert.ToDateTime(FechaFinale.Value); int tipodempleado = int.Parse(DropTipodeEmpleados.SelectedValue); List <empleado> Lempleados = bus.Lempleado(); Lempleados = Lempleados.FindAll(x => (x.id_tipo ?? default(int)) == tipodempleado); if (Lempleados.Count != 0) { var doc = new iTextSharp.text.Document(PageSize.A4); string path = Server.MapPath("~"); PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(path + "/Taller.pdf", FileMode.Create)); doc.Open(); //Cabecera BaseFont bfntHead = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); iTextSharp.text.Font fntHead = new iTextSharp.text.Font(bfntHead, 16, 1, iTextSharp.text.BaseColor.GREEN.Darker()); Paragraph prgHeading = new Paragraph(); prgHeading.Alignment = 1; prgHeading.Add(new Chunk("Taller de Reparaciones".ToUpper(), fntHead)); doc.Add(prgHeading); doc.Add(Chunk.NEWLINE); //Generado By Paragraph prgGeneratedBY = new Paragraph(); BaseFont btnAuthor = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); iTextSharp.text.Font fntAuthor = new iTextSharp.text.Font(btnAuthor, 12, 2, iTextSharp.text.BaseColor.BLACK); prgGeneratedBY.Alignment = Element.ALIGN_RIGHT; prgGeneratedBY.Add(new Chunk("Generado por: " + LogEmpleado.nombreyapellido, fntAuthor)); //Agregar LOG Empleado prgGeneratedBY.Add(new Chunk("\nFecha : " + DateTime.Now.ToShortDateString(), fntAuthor)); doc.Add(prgGeneratedBY); Paragraph p = new Paragraph(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(0.0F, 100.0F, iTextSharp.text.BaseColor.BLACK, Element.ALIGN_LEFT, 1))); doc.Add(p); //Espacio doc.Add(new Chunk("\n", fntHead)); //Datos Paragraph Datos = new Paragraph(); BaseFont bfntDatos = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); iTextSharp.text.Font fntDatos = new iTextSharp.text.Font(bfntDatos, 16, 0, iTextSharp.text.BaseColor.BLACK); Datos.Alignment = Element.ALIGN_CENTER; Datos.Add(new Chunk("\nEmpleado tipo: " + DropTipodeEmpleados.SelectedItem.Text, fntDatos)); doc.Add(Datos); //Espacio doc.Add(new Chunk("\n", fntHead)); int controlprecio; foreach (empleado oempleado in Lempleados) { controlprecio = 0; DataTable dt = new DataTable(); dt.Columns.AddRange(new DataColumn[4] { new DataColumn("N°Orden"), new DataColumn("Vehiculo"), new DataColumn("Fecha"), new DataColumn("PrecioTotal") }); //nombre de las columnas List <ordenempleado> Lordenempleado = bus.buscarListOrdenEstadoporempleado(oempleado.id_empleado); List <orden> Lorden = bus.buscarordexempleado(Lordenempleado); foreach (orden OrdenActual in Lorden) { int id = int.Parse(OrdenActual.id_vehiculo.ToString()); vehiculo ovehiculo = bus.buscarvehiculoid(id); int preciototal = 0; ordenestado oestado = bus.buscarvestadoorden(OrdenActual.id_orden); if ((oestado.fecha_entregado >= oDateinicio) && (oestado.fecha_entregado <= oDatefin)) { List <ordenservicio> Lidservidcios = new List <ordenservicio>(); Lidservidcios = bus.buscarlistaid(OrdenActual.id_orden); List <servicio> Lservicio = bus.ObtenerServicios(Lidservidcios); foreach (ordenservicio ordenservi in Lidservidcios) { servicio oservicio = Lservicio.Find(x => x.id_servicios == ordenservi.id_servicio); int cantidad = ordenservi.cantidad ?? default(int); string total = (double.Parse(oservicio.precio) * Convert.ToDouble(cantidad)).ToString(); preciototal = preciototal + int.Parse(total); } string fecha = oestado.fecha_entregado.ToString(); string[] fechasinhora; fechasinhora = fecha.Split(' '); dt.Rows.Add(OrdenActual.id_orden, ovehiculo.patente, fechasinhora[0], preciototal); controlprecio = preciototal; } } //aqui if (dt.Rows.Count != 0) { doc.Add(p); Paragraph Dato = new Paragraph(); Dato.Alignment = Element.ALIGN_LEFT; Dato.Add(new Chunk("\nNombre y Apellido: " + oempleado.nombreyapellido + " Correo: " + oempleado.correo + " Direccion: " + oempleado.direccion + "\nDireccion: " + oempleado.telefono, fntDatos)); doc.Add(Dato); //Espacio doc.Add(new Chunk("\n", fntHead)); //Tabla PdfPTable table = new PdfPTable(dt.Columns.Count); for (int i = 0; i < dt.Columns.Count; i++) { string cellText = Server.HtmlDecode(dt.Columns[i].ColumnName); PdfPCell cell = new PdfPCell(); cell.Phrase = new Phrase(cellText, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 10, 1, new BaseColor(System.Drawing.ColorTranslator.FromHtml("#000000")))); cell.BackgroundColor = new BaseColor(System.Drawing.ColorTranslator.FromHtml("#C8C8C8")); cell.HorizontalAlignment = Element.ALIGN_CENTER; cell.PaddingBottom = 5; table.AddCell(cell); } for (int i = 0; i < dt.Rows.Count; i++) { for (int j = 0; j < dt.Columns.Count; j++) { table.AddCell(dt.Rows[i][j].ToString()); } } table.HorizontalAlignment = Element.ALIGN_CENTER; doc.Add(table); //Espacio doc.Add(new Chunk("\n", fntHead)); } } doc.Close(); Page.ClientScript.RegisterStartupScript(this.GetType(), "OpenWindow", "window.open('Taller.pdf','_newtab');", true); } } }
private void Form1_Load(object sender, EventArgs e) { //Folder that we will be working in string WorkingFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Big File PDF Test"); //Base name of PDFs that we will be creating string BigFileBase = Path.Combine(WorkingFolder, "BigFile"); //Final combined PDF name string CombinedFile = Path.Combine(WorkingFolder, "Combined.pdf"); //Number of "large" files to create int NumberOfBigFilesToMakes = 10; //Number of pages to put in the files int NumberOfPagesInBigFile = 1000; //Number of pages to insert into combined file int NumberOfPagesToInsertIntoCombinedFile = 500; //Create our test directory if (!Directory.Exists(WorkingFolder)) { Directory.CreateDirectory(WorkingFolder); } //First step, create a bunch of files with a bunch of pages, hopefully code is self-explanatory for (int FileCount = 1; FileCount <= NumberOfBigFilesToMakes; FileCount++) { using (FileStream FS = new FileStream(BigFileBase + FileCount + ".pdf", FileMode.Create, FileAccess.Write, FileShare.Read)) { using (iTextSharp.text.Document Doc = new iTextSharp.text.Document(PageSize.LETTER)) { using (PdfWriter writer = PdfWriter.GetInstance(Doc, FS)) { Doc.Open(); for (int I = 1; I <= NumberOfPagesInBigFile; I++) { Doc.NewPage(); Doc.Add(new Paragraph("This is file " + FileCount)); Doc.Add(new Paragraph("This is page " + I)); } Doc.Close(); } } } } //Second step, loop around pulling random pages from random files //Create our output file using (FileStream FS = new FileStream(CombinedFile, FileMode.Create, FileAccess.Write, FileShare.Read)) { using (Document Doc = new Document()) { using (PdfCopy pdfCopy = new PdfCopy(Doc, FS)) { Doc.Open(); //Setup some variables to use in the loop below PdfReader reader = null; PdfImportedPage page = null; int RanFileNum = 0; int RanPageNum = 0; //Standard random number generator Random R = new Random(); for (int I = 1; I <= NumberOfPagesToInsertIntoCombinedFile; I++) { //Just to output our current progress Console.WriteLine(I); //Get a random page and file. Remember iText pages are 1-based. RanFileNum = R.Next(1, NumberOfBigFilesToMakes + 1); RanPageNum = R.Next(1, NumberOfPagesInBigFile + 1); //Open the random file reader = new PdfReader(BigFileBase + RanFileNum + ".pdf"); //Set the current page Doc.SetPageSize(reader.GetPageSizeWithRotation(1)); //Grab a random page page = pdfCopy.GetImportedPage(reader, RanPageNum); //Add it to the combined file pdfCopy.AddPage(page); //Clean up reader.Close(); } //Clean up Doc.Close(); } } } }
private string PrintReceipt(string BookingNo) { if (!string.IsNullOrEmpty(BookingNo)) { var dtBooking = Operation.GetDataTable("Select Booking.*,Inquiry.[BkDate],Inquiry.[FuncType],Inquiry.[Plot],Inquiry.[TotPerson] from Booking left join Inquiry on Inquiry.[Number] = Booking.[InqNo] where Booking.[Number]='" + BookingNo + "'"); iTextSharp.text.Font font10 = FontFactory.GetFont("Calibri", 10, iTextSharp.text.Font.NORMAL); iTextSharp.text.Font font10_bold = FontFactory.GetFont("Calibri", 10, iTextSharp.text.Font.BOLD); iTextSharp.text.Font font16 = FontFactory.GetFont("Calibri", 16, iTextSharp.text.Font.BOLD); var folderPath = Application.StartupPath + "//Receipts"; bool exists = Directory.Exists(folderPath); if (!exists) { Directory.CreateDirectory(folderPath); } DirectoryInfo info = new DirectoryInfo(folderPath); FileInfo[] files = info.GetFiles().Where(p => p.CreationTime <= DateTime.Now.AddDays(-1)).ToArray(); foreach (var file in files) { file.Delete(); } var document = new iTextSharp.text.Document(PageSize.A4, 20f, 20f, 10f, 0f); var pdffilename = DateTime.Now.ToString("h:mm:ss").Replace(":", ""); var writer = PdfWriter.GetInstance(document, new FileStream(folderPath + "/" + pdffilename + ".PDF", FileMode.Create)); document.Open(); var outerTable = new PdfPTable(1); outerTable.HorizontalAlignment = iTextSharp.text.Rectangle.ALIGN_CENTER; outerTable.TotalWidth = document.PageSize.Width - document.LeftMargin - document.RightMargin; outerTable.LockedWidth = true; outerTable.DefaultCell.Border = iTextSharp.text.Rectangle.NO_BORDER; var table = new PdfPTable(1); table.HorizontalAlignment = iTextSharp.text.Rectangle.ALIGN_CENTER; table.TotalWidth = document.PageSize.Width - document.LeftMargin - document.RightMargin; table.LockedWidth = true; table.DefaultCell.Border = iTextSharp.text.Rectangle.NO_BORDER; var dtSettings = Operation.GetDataTable("select * from settings"); PdfPCell cell = new PdfPCell(new Phrase("Receipt", font10)); cell.HorizontalAlignment = iTextSharp.text.Rectangle.ALIGN_CENTER; cell.Border = iTextSharp.text.Rectangle.NO_BORDER; table.AddCell(cell); document.Add(table); table = new PdfPTable(1); table.HorizontalAlignment = iTextSharp.text.Rectangle.ALIGN_CENTER; table.TotalWidth = document.PageSize.Width - document.LeftMargin - document.RightMargin; table.LockedWidth = true; table.DefaultCell.Border = iTextSharp.text.Rectangle.NO_BORDER; if (dtSettings != null && dtSettings.Rows.Count > 0) { cell = new PdfPCell(new Phrase(dtSettings.Rows[0]["CName"].ToString(), font16)); cell.HorizontalAlignment = iTextSharp.text.Rectangle.ALIGN_CENTER; cell.Border = iTextSharp.text.Rectangle.NO_BORDER; table.AddCell(cell); cell = new PdfPCell(new Phrase(dtSettings.Rows[0]["CAddress"].ToString(), font10_bold)); cell.HorizontalAlignment = iTextSharp.text.Rectangle.ALIGN_CENTER; cell.Border = iTextSharp.text.Rectangle.NO_BORDER; table.AddCell(cell); } else { table.AddCell(new Phrase(" ", font16)); table.AddCell(new Phrase(" ", font10_bold)); } //document.Add(table); cell = new PdfPCell(table); cell.Border = iTextSharp.text.Rectangle.BOX; outerTable.AddCell(cell); table = new PdfPTable(2); table.HorizontalAlignment = iTextSharp.text.Rectangle.ALIGN_CENTER; table.TotalWidth = document.PageSize.Width - document.LeftMargin - document.RightMargin; table.LockedWidth = true; table.DefaultCell.Border = iTextSharp.text.Rectangle.NO_BORDER; cell = new PdfPCell(new Phrase("Receipt No. : " + dtBooking.Rows[0]["Number"].ToString(), font10_bold)); cell.HorizontalAlignment = iTextSharp.text.Rectangle.ALIGN_LEFT; cell.Border = iTextSharp.text.Rectangle.TOP_BORDER | iTextSharp.text.Rectangle.BOTTOM_BORDER; table.AddCell(cell); cell = new PdfPCell(new Phrase("Receipt Dt. : " + Convert.ToDateTime(dtBooking.Rows[0]["Date"].ToString()).ToString("dd/MM/yyyy"), font10_bold)); cell.HorizontalAlignment = iTextSharp.text.Rectangle.ALIGN_RIGHT; cell.Border = iTextSharp.text.Rectangle.TOP_BORDER | iTextSharp.text.Rectangle.BOTTOM_BORDER; table.AddCell(cell); cell = new PdfPCell(new Phrase("Received with thanks from", font10)); cell.HorizontalAlignment = iTextSharp.text.Rectangle.ALIGN_LEFT; cell.Border = iTextSharp.text.Rectangle.NO_BORDER; cell.PaddingBottom = 8; cell.Colspan = 2; table.AddCell(cell); cell = new PdfPCell(new Phrase("M/S." + dtBooking.Rows[0]["Party"].ToString(), font10_bold)); cell.HorizontalAlignment = iTextSharp.text.Rectangle.ALIGN_LEFT; cell.Border = iTextSharp.text.Rectangle.NO_BORDER; cell.PaddingBottom = 8; cell.Colspan = 2; table.AddCell(cell); cell = new PdfPCell(new Phrase("The sum of Rupees " + NumberToWords(Convert.ToInt32(dtBooking.Rows[0]["Deposite"])), font10)); cell.HorizontalAlignment = iTextSharp.text.Rectangle.ALIGN_LEFT; cell.Border = iTextSharp.text.Rectangle.NO_BORDER; cell.PaddingBottom = 8; cell.Colspan = 2; table.AddCell(cell); if (Convert.ToString(dtBooking.Rows[0]["PmtMode"]).ToUpper() == "CASH") { cell = new PdfPCell(new Phrase("By Cash", font10_bold)); cell.Colspan = 2; cell.PaddingBottom = 8; cell.Border = iTextSharp.text.Rectangle.NO_BORDER; table.AddCell(cell); } else { table.AddCell(new Phrase("By Cheque / Draft No. :" + Convert.ToString(dtBooking.Rows[0]["ChequeNo"]), font10_bold)); table.AddCell(new Phrase("Cheque / Draft Date :" + Convert.ToDateTime(Convert.ToString(dtBooking.Rows[0]["ChequeDt"])).ToString("dd/MM/yyyy"), font10_bold)); table.AddCell(new Phrase("Drawn on Bank : " + Convert.ToString(dtBooking.Rows[0]["ChequeBank"]), font10_bold)); } cell = new PdfPCell(new Phrase("In Part / Full Payment for following details, ", font10)); cell.Colspan = 2; cell.PaddingBottom = 8; cell.Border = iTextSharp.text.Rectangle.NO_BORDER; table.AddCell(cell); cell = new PdfPCell(new Phrase("Function Date : " + Convert.ToString(dtBooking.Rows[0]["BkDate"]), font10_bold)); cell.Border = iTextSharp.text.Rectangle.NO_BORDER; cell.Colspan = 2; table.AddCell(cell); cell = new PdfPCell(new Phrase("Function Type : " + Convert.ToString(dtBooking.Rows[0]["FuncType"]), font10_bold)); cell.Border = iTextSharp.text.Rectangle.NO_BORDER; cell.Colspan = 2; table.AddCell(cell); cell = new PdfPCell(new Phrase("Plot : " + Convert.ToString(dtBooking.Rows[0]["Plot"]), font10_bold)); cell.Border = iTextSharp.text.Rectangle.NO_BORDER; cell.Colspan = 2; table.AddCell(cell); cell = new PdfPCell(new Phrase("Gathering Person : " + Convert.ToString(dtBooking.Rows[0]["TotPerson"]), font10_bold)); cell.Border = iTextSharp.text.Rectangle.BOTTOM_BORDER; cell.Colspan = 2; table.AddCell(cell); cell = new PdfPCell(new Phrase("For, " + Convert.ToString(dtSettings.Rows[0]["CName"]), font10_bold)); cell.Border = iTextSharp.text.Rectangle.NO_BORDER; cell.Colspan = 2; cell.HorizontalAlignment = iTextSharp.text.Rectangle.ALIGN_RIGHT; table.AddCell(cell); cell = new PdfPCell(new Phrase("Rs. " + Convert.ToString(dtBooking.Rows[0]["Deposite"]), font10_bold)); cell.Border = iTextSharp.text.Rectangle.NO_BORDER; cell.PaddingBottom = 8; cell.Colspan = 2; table.AddCell(cell); cell = new PdfPCell(new Phrase("Subject to Realisation of Cheque / Draft.", font10)); cell.Border = iTextSharp.text.Rectangle.BOTTOM_BORDER; cell.Colspan = 2; table.AddCell(cell); cell = new PdfPCell(table); cell.Border = iTextSharp.text.Rectangle.BOX; outerTable.AddCell(cell); document.Add(outerTable); document.Close(); return(folderPath + "//" + pdffilename + ".PDF"); } else { return(null); } }
/// <inheritdoc /> public override async Task <ExportedRoleplay> ExportAsync(Roleplay roleplay) { // Create our document var pdfDoc = new Document(); var filePath = Path.GetTempFileName(); using (var of = File.Create(filePath)) { var writer = PdfWriter.GetInstance(pdfDoc, of); writer.Open(); pdfDoc.Open(); var owner = await this.Guild.GetUserAsync((ulong)roleplay.Owner.DiscordID); pdfDoc.AddAuthor(owner.Nickname); pdfDoc.AddCreationDate(); pdfDoc.AddCreator("DIGOS Ambassador"); pdfDoc.AddTitle(roleplay.Name); var joinedUsers = await Task.WhenAll ( roleplay.JoinedUsers.Select ( async p => { var guildUser = await this.Guild.GetUserAsync((ulong)p.User.DiscordID); if (guildUser is null) { var messageByUser = roleplay.Messages.FirstOrDefault ( m => m.AuthorDiscordID == p.User.DiscordID ); if (messageByUser is null) { return($"Unknown user ({p.User.DiscordID})"); } return(messageByUser.AuthorNickname); } return(guildUser.Username); } ) ); pdfDoc.Add(CreateTitle(roleplay.Name)); pdfDoc.Add(CreateParticipantList(joinedUsers)); pdfDoc.NewPage(); var messages = roleplay.Messages.OrderBy(m => m.Timestamp).DistinctBy(m => m.Contents); foreach (var message in messages) { pdfDoc.Add(CreateMessage(message.AuthorNickname, message.Contents)); } pdfDoc.Close(); writer.Flush(); writer.Close(); } var resultFile = File.OpenRead(filePath); var exported = new ExportedRoleplay(roleplay.Name, ExportFormat.PDF, resultFile); return(exported); }
private void ReproductivityToolStripMenuItem_Click(object sender, EventArgs e) { saveFileDialog1.Title = "Сохранение документа"; saveFileDialog1.FileName = "Молокоотдача коров"; saveFileDialog1.DefaultExt = "*.pdf"; saveFileDialog1.Filter = "Файлы PDF (*.pdf)|*.pdf|Все файлы (*.*)|*.*"; if (saveFileDialog1.ShowDialog() == DialogResult.OK) { string SaveFileName = saveFileDialog1.FileName; //Объект документа пдф iTextSharp.text.Document doc = new iTextSharp.text.Document(); //Создаем объект записи пдф-документа в файл PdfWriter.GetInstance(doc, new FileStream(SaveFileName, FileMode.Create)); //Открываем документ doc.Open(); //Определение шрифта необходимо для сохранения кириллического текста //Иначе мы не увидим кириллический текст //Если мы работаем только с англоязычными текстами, то шрифт можно не указывать string FONT_LOCATION = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "arial.TTF"); //определяем В СИСТЕМЕ(чтобы не копировать файл) расположение шрифта arial.ttf BaseFont baseFont = BaseFont.CreateFont(FONT_LOCATION, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); //создаем шрифт iTextSharp.text.Font fontParagraph = new iTextSharp.text.Font(baseFont, 17, iTextSharp.text.Font.NORMAL); //регистрируем + можно задать параметры для него(17 - размер, последний параметр - стиль) //Создаем объект таблицы и передаем в нее число столбцов таблицы из нашего датасета PdfPTable table = new PdfPTable(5); //MyDataSet.Tables[i].Columns.Count); //Добавим в таблицу общий заголовок PdfPCell cell = new PdfPCell(new Phrase("Молокоотдача коров")); cell.Colspan = 5; cell.HorizontalAlignment = 1; //Убираем границу первой ячейки, чтобы был как заголовок cell.Border = 0; table.AddCell(cell); //Сначала добавляем заголовки таблицы cell = new PdfPCell(new Phrase(new Phrase("Номер коровы", fontParagraph))); //Фоновый цвет (необязательно, просто сделаем по красивее) cell.BackgroundColor = BaseColor.LIGHT_GRAY; table.AddCell(cell); cell = new PdfPCell(new Phrase(new Phrase("Количество осеменения на одно плодотворное", fontParagraph))); cell.BackgroundColor = BaseColor.LIGHT_GRAY; table.AddCell(cell); cell = new PdfPCell(new Phrase(new Phrase("Продолжительность сервис периода", fontParagraph))); cell.BackgroundColor = BaseColor.LIGHT_GRAY; table.AddCell(cell); cell = new PdfPCell(new Phrase(new Phrase("Продолжительность сухостойного периода", fontParagraph))); cell.BackgroundColor = BaseColor.LIGHT_GRAY; table.AddCell(cell); cell = new PdfPCell(new Phrase(new Phrase("Продолжительность межотельного периода", fontParagraph))); cell.BackgroundColor = BaseColor.LIGHT_GRAY; table.AddCell(cell); //Добавляем все остальные ячейки for (int j = 0; j < reproductiveDataGridView.RowCount - 1; j++) { table.AddCell(new Phrase(reproductiveDataGridView.Rows[j].Cells[1].Value.ToString(), fontParagraph)); table.AddCell(new Phrase(reproductiveDataGridView.Rows[j].Cells[2].Value.ToString(), fontParagraph)); table.AddCell(new Phrase(reproductiveDataGridView.Rows[j].Cells[7].Value.ToString(), fontParagraph)); table.AddCell(new Phrase(reproductiveDataGridView.Rows[j].Cells[8].Value.ToString(), fontParagraph)); if (reproductiveDataGridView.Rows[j].Cells[5].Value != null && reproductiveDataGridView.Rows[j].Cells[4].Value != null && reproductiveDataGridView.Rows[j].Cells[5].Value.ToString().Length > 4 && reproductiveDataGridView.Rows[j].Cells[4].Value.ToString().Length > 4) { TimeSpan day = Convert.ToDateTime(reproductiveDataGridView.Rows[j].Cells[4].Value) - Convert.ToDateTime(reproductiveDataGridView.Rows[j].Cells[5].Value); table.AddCell(new Phrase(day.Days.ToString(), fontParagraph)); } else { table.AddCell(new Phrase("", fontParagraph)); } } //Добавляем таблицу в документ doc.Add(table); //Закрываем документ doc.Close(); Process.Start(saveFileDialog1.FileName); } }
private void btnMarkSheet_Click(object sender, EventArgs e) { List <Project> Projects = new List <Project>(); List <DateTime> Dates = new List <DateTime>(); DatabaseConnection.createStatement("select CONVERT(date, EvaluationDate)as EDate from GroupEvaluation group by CONVERT(date, EvaluationDate) order by CONVERT(date, EvaluationDate) desc"); SqlDataReader firstReader = DatabaseConnection.getData(); while (firstReader.Read()) { Dates.Add(DateTime.Parse(firstReader["EDate"].ToString())); } DatabaseConnection.createStatement("select * from Project"); SqlDataReader dataReader = DatabaseConnection.getData(); while (dataReader.Read()) { Project project = new Project(); project.Id = int.Parse(dataReader["Id"].ToString()); project.Title = dataReader["Title"].ToString(); Projects.Add(project); } StringWriter sw = new StringWriter(); HtmlTextWriter hw = new HtmlTextWriter(sw); StringBuilder sb = new StringBuilder(); //Generate Invoice (Bill) Header. sb.Append("<p style=\"text-align:center; font-size: 32px; \"><b>University of Engineering and Technology, Lahore</b></p>"); sb.Append("<p style=\"text-align:center; font-size: 20px; \"><b>CSE Department</b></p>"); sb.Append("<p style=\"text-align:center; \"><b><u>Mark Sheet</b></u></p>"); StringReader sr = new StringReader(sb.ToString()); PdfPTable tbl = new PdfPTable(Dates.Count + 1); tbl.AddCell("Date"); foreach (DateTime date in Dates) { tbl.AddCell(date.ToShortDateString().ToString()); } List <Evaluation> evaluations = new List <Evaluation>(); foreach (DateTime date in Dates) { string d = date.ToString("yyyy-MM-dd"); DatabaseConnection.createStatement("Select * from GroupEvaluation join Evaluation on GroupEvaluation.EvaluationId = Evaluation.Id where CONVERT(date, GroupEvaluation.EvaluationDate) = CONVERT(date, '" + d + "')"); SqlDataReader sqlDataReader = DatabaseConnection.getData(); if (sqlDataReader.Read()) { Evaluation evaluation = new Evaluation(); evaluation.Date = d; evaluation.TotalMarks = sqlDataReader["TotalMarks"].ToString(); evaluation.TotalWeightage = sqlDataReader["TotalWeightage"].ToString(); evaluations.Add(evaluation); } } tbl.AddCell("Total Marks"); foreach (Evaluation eval in evaluations) { tbl.AddCell(eval.TotalMarks); } tbl.AddCell("Weightage"); foreach (Evaluation eval in evaluations) { tbl.AddCell(eval.TotalWeightage); } foreach (Project p in Projects) { tbl.AddCell(p.Title); foreach (DateTime d in Dates) { string date = d.ToString("yyyy-MM-dd"); DatabaseConnection.createStatement("select * from Project join GroupProject on Project.Id = GroupProject.ProjectId join GroupEvaluation on GroupProject.GroupId = GroupEvaluation.GroupId join Evaluation on GroupEvaluation.EvaluationId = Evaluation.Id where Project.Id = " + p.Id + " and CONVERT(date, GroupEvaluation.EvaluationDate) = CONVERT(date, '" + date + "') order by GroupEvaluation.EvaluationDate"); SqlDataReader reader2 = DatabaseConnection.getData(); if (reader2.Read()) { tbl.AddCell(reader2["ObtainedMarks"].ToString()); } else { tbl.AddCell("N/A"); } } } SaveFileDialog saveFileDialog = new SaveFileDialog() { Filter = "PDF file|*.pdf", ValidateNames = true }; if (saveFileDialog.ShowDialog() == DialogResult.OK) { iTextSharp.text.Document document = new iTextSharp.text.Document(PageSize.A4.Rotate()); HTMLWorker htmlparser = new HTMLWorker(document); try { PdfWriter.GetInstance(document, new FileStream(saveFileDialog.FileName, FileMode.Create)); document.Open(); htmlparser.Parse(sr); document.Add(new iTextSharp.text.Paragraph("\n Date : " + DateTime.Now.ToShortDateString() + "\n \n")); document.Add(tbl); document.Add(new iTextSharp.text.Paragraph("\n \n This report was generated by computer. Errors are acceptible. ")); } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { document.Close(); } MessageBox.Show("Report saved successfully"); } }
private void EndOfProductionButton_Click(object sender, EventArgs e) { string filename = "C:/OP2GUI/"; if (System.IO.Directory.Exists(filename)) { } else { Directory.CreateDirectory(filename); } DateTime now = DateTime.Now; rapor = new iTextSharp.text.Document(); PdfWriter.GetInstance(rapor, new FileStream("C:/OP2GUI/" + Initialize.name + DateTime.Now.ToString("yyyyMMddHHmmss") + "OP2GUI.pdf", FileMode.Create)); rapor.SetMargins(80, 80, 80, 80); Initialize.name = TurkceKarakter(Initialize.name); rapor.AddAuthor(Initialize.name); rapor.AddCreationDate(); rapor.AddCreator(Initialize.name); rapor.AddSubject(Initialize.name + "|OP2-GUI"); if (rapor.IsOpen() == false) { rapor.Open(); } BaseFont times = BaseFont.CreateFont("c:\\windows\\fonts\\times.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED); Font font16 = new Font(times, 16); Font font14 = new Font(times, 14); Font font12 = new Font(times, 12); ///Tarih Ekle Paragraph head0 = new Paragraph(now.ToString(), font12); head0.Alignment = Element.ALIGN_RIGHT; rapor.Add(head0); ////Başlık Paragraph head = new Paragraph("OP2-GUI", font16); head.Alignment = Element.ALIGN_CENTER; rapor.Add(head); ///Üretimden Sorumlu kişi Paragraph head2 = new Paragraph("Üretimden Sorumlu Kisi: " + Initialize.name, font14); head2.Alignment = Element.ALIGN_CENTER; rapor.Add(head2); /// Yeni Veriler PdfNewDataLeft("\n"); PdfNewDataCenter("--------------------------------------------------"); PdfNewDataCenter("Başlangıçta Belirlenen Parametreler"); PdfNewDataCenter("--------------------------------------------------"); PdfNewDataLeft("\n"); PdfNewDataLeft("--------------------------------------------------"); PdfNewDataLeft("Malzemenin Adı: " + RefProduction.materialNameTextRP); PdfNewDataLeft("Numume Adedi: " + RefProduction.numberOfSamplesTextRP); PdfNewDataLeft("Numune Boyutları: " + RefProduction.sampleSizeTextRP); PdfNewDataLeft("Üretim Türü: " + Initialize.publicrefProductiontext); PdfNewDataLeft("Solüsyon Bilgisi: " + ProductionParameters.publicsolutionInfoText); PdfNewDataLeft("--------------------------------------------------"); PdfNewDataLeft("Başlangıç Saati: " + DateTime.Now.ToShortTimeString()); PdfNewDataLeft("Kullanılan Program: " + programNameLabelOP.Text); PdfNewDataLeft("Alt-taş Sıcaklığı: " + substrateHeaterLabelOP.Text); PdfNewDataLeft("Akış Miktarı: " + flowRateLabelOP.Text); PdfNewDataLeft("Geçiş Sayısı: " + passCountLabelOP.Text); PdfNewDataLeft("Nozzle Gaz: " + nozzleGasPressureLabelOP.Text); PdfNewDataLeft("Oksijen Seviyesi (SET): " + oxygenLevelSetLabelOP.Text); PdfNewDataLeft("Oksijen Seviyesi (Başlangıç): " + oxygenLevelStartLabelOP.Text); PdfNewDataLeft("Ortam Sıcaklığı (SET): " + ambienceTemperatureSetLabelOP.Text); PdfNewDataLeft("Ortam Sıcaklığı (Başlangıç) :" + ambienceTemperatureStartLabelOP.Text); PdfNewDataLeft("Nem Seviyesi (SET) :" + humidityLevelSetLabelOP.Text); PdfNewDataLeft("Nem Seviyesi (Başlangıç) :" + humidityLevelStartLabelOP.Text); PdfNewDataLeft("Nemlendirici Gerilimi: " + humidityVoltageLabelOP.Text); PdfNewDataLeft("Fan Hızı : " + fanRPMLabelOP.Text); PdfNewDataLeft("--------------------------------------------------"); PdfNewDataLeft("\n"); PdfNewDataLeft("\n"); PdfNewDataLeft("\n"); PdfNewDataLeft("\n"); PdfNewDataLeft("\n"); PdfNewDataLeft("\n"); PdfNewDataCenter("--------------------------------------------------"); PdfNewDataCenter("Üretim Sırasında Belirlenen Parametreler"); PdfNewDataCenter("--------------------------------------------------"); PdfNewDataLeft("\n"); if (changesListBox.Items.Count > 0) { PdfNewDataLeft("--------------------------------------------------"); foreach (string item in changesListBox.Items) { PdfNewDataLeft(item); } PdfNewDataLeft("--------------------------------------------------"); } PdfNewDataLeft("\n"); PdfNewDataCenter("--------------------------------------------------"); PdfNewDataCenter("Üretim Sırasında Anlık Parametreler"); PdfNewDataCenter("--------------------------------------------------"); PdfNewDataLeft("\n"); if (instantDataListBox.Items.Count > 0) { PdfNewDataLeft("--------------------------------------------------"); foreach (string item in instantDataListBox.Items) { PdfNewDataLeft(item); Console.WriteLine(item); } PdfNewDataLeft("--------------------------------------------------"); } PdfNewDataLeft("\n"); PdfNewDataCenter("--------------------------------------------------"); PdfNewDataCenter("Temizlik"); PdfNewDataCenter("--------------------------------------------------"); PdfNewDataLeft("\n"); if (!(CleaningProcess.cleaningProcessCP == "")) { PdfNewDataLeft("--------------------------------------------------"); PdfNewDataLeft(CleaningProcess.cleaningProcessCP); PdfNewDataLeft("--------------------------------------------------"); } PdfNewDataLeft("\n"); PdfNewDataCenter("--------------------------------------------------"); PdfNewDataCenter("İleri İşlemler"); PdfNewDataCenter("--------------------------------------------------"); PdfNewDataLeft("\n"); if (!(PostProcessing.postProcessPOP == "")) { PdfNewDataLeft("--------------------------------------------------"); PdfNewDataLeft(PostProcessing.postProcessPOP); PdfNewDataLeft("--------------------------------------------------"); } PdfNewDataLeft("\n"); PdfNewDataCenter("--------------------------------------------------"); PdfNewDataCenter("Alınacak Olçümler"); PdfNewDataCenter("--------------------------------------------------"); PdfNewDataLeft("\n"); if (Measurements.measumentsMP.Length > 0) { PdfNewDataLeft("--------------------------------------------------"); foreach (var item in Measurements.measumentsMP) { PdfNewDataLeft(item); } PdfNewDataLeft("--------------------------------------------------"); } PdfNewDataLeft("\n"); PdfNewDataCenter("--------------------------------------------------"); PdfNewDataCenter("Notlar"); PdfNewDataCenter("--------------------------------------------------"); PdfNewDataLeft("\n"); if (!(takeNotesText.Text == "")) { PdfNewDataLeft("--------------------------------------------------"); PdfNewDataLeft(takeNotesText.Text); PdfNewDataLeft("--------------------------------------------------"); } rapor.Close(); MessageBox.Show("Dosya Oluşturuldu.\n" + "C:/OP2GUI/" + Initialize.name + DateTime.Now.ToString("yyyyMMddHHmmss") + "OP2GUI.pdf"); System.Diagnostics.Process.Start("C:/OP2GUI/"); }
private void SaveIntervalPDF_Click(object sender, RoutedEventArgs e) { if (intervalControl.Open) { System.Windows.Forms.SaveFileDialog sfd = new System.Windows.Forms.SaveFileDialog(); sfd.Filter = "Файл PDF|*.pdf"; sfd.DefaultExt = "pdf"; if (sfd.ShowDialog() != System.Windows.Forms.DialogResult.OK) { return; } iTextSharp.text.Document document = new iTextSharp.text.Document(); PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(sfd.FileName, FileMode.Create) ); document.Open(); string fg = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "Arial.TTF"); BaseFont fgBaseFont = BaseFont.CreateFont(fg, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); iTextSharp.text.Font fgFont = new iTextSharp.text.Font(fgBaseFont, 12, iTextSharp.text.Font.BOLD, BaseColor.BLACK); iTextSharp.text.Paragraph p = new iTextSharp.text.Paragraph("Первичный статистический анализ данных. Интервальный ряд.", fgFont); p.Alignment = Element.ALIGN_CENTER; document.Add(p); iTextSharp.text.Paragraph p_1 = new iTextSharp.text.Paragraph(" ", fgFont); document.Add(p_1); int column = 4; int row = intervalControl.IntervalGrid.Count(); PdfPTable table = new PdfPTable(column); PdfPCell cell1 = new PdfPCell(new Phrase(new Phrase("Левая граница", fgFont))); cell1.BackgroundColor = iTextSharp.text.BaseColor.LIGHT_GRAY; table.AddCell(cell1); PdfPCell cell2 = new PdfPCell(new Phrase(new Phrase("Правая граница", fgFont))); cell2.BackgroundColor = iTextSharp.text.BaseColor.LIGHT_GRAY; table.AddCell(cell2); PdfPCell cell3 = new PdfPCell(new Phrase(new Phrase("Частота", fgFont))); cell3.BackgroundColor = iTextSharp.text.BaseColor.LIGHT_GRAY; table.AddCell(cell3); PdfPCell cell4 = new PdfPCell(new Phrase(new Phrase("Накопленная частота", fgFont))); cell4.BackgroundColor = iTextSharp.text.BaseColor.LIGHT_GRAY; table.AddCell(cell4); double[] lBorder = intervalControl.IntervalGrid.Select(c => c.leftBorder).ToArray(); double[] rBorder = intervalControl.IntervalGrid.Select(c => c.rightBorder).ToArray(); double[] frequency = intervalControl.IntervalGrid.Select(c => c.frequency).ToArray(); double[] accumulatedFrequency = intervalControl.IntervalGrid.Select(c => c.accumulatedFrequency).ToArray(); for (int i = 0; i < row; i++) { string lb = "", rb = "", fre = "", acc = ""; lb = lBorder[i].ToString(); rb = rBorder[i].ToString(); fre = frequency[i].ToString(); acc = accumulatedFrequency[i].ToString(); table.AddCell(new Phrase(lb)); table.AddCell(new Phrase(rb)); table.AddCell(new Phrase(fre)); table.AddCell(new Phrase(acc)); } document.Add(table); iTextSharp.text.Paragraph p_2 = new iTextSharp.text.Paragraph(" ", fgFont); document.Add(p_2); PdfPTable table2 = new PdfPTable(1); PdfPCell cell = new PdfPCell(new Phrase(new Phrase("Расчеты", fgFont))); cell.BackgroundColor = iTextSharp.text.BaseColor.LIGHT_GRAY; table2.AddCell(cell); table2.AddCell(new Phrase(intervalControl.tbAverageValue.Text, fgFont)); table2.AddCell(new Phrase(intervalControl.tbMode.Text, fgFont)); table2.AddCell(new Phrase(intervalControl.tbMedian.Text, fgFont)); table2.AddCell(new Phrase(intervalControl.tbRangeOfVariation.Text, fgFont)); table2.AddCell(new Phrase(intervalControl.tbMeanLinearDeviation.Text, fgFont)); table2.AddCell(new Phrase(intervalControl.tbDispersion.Text, fgFont)); table2.AddCell(new Phrase(intervalControl.tbStandardDeviation.Text, fgFont)); table2.AddCell(new Phrase(intervalControl.tbCoefficientVariation.Text, fgFont)); table2.AddCell(new Phrase(intervalControl.tbNormalCoefficientAsymmetry.Text, fgFont)); table2.AddCell(new Phrase(intervalControl.tbEstimationCoefficientAsymmetry.Text, fgFont)); table2.AddCell(new Phrase(intervalControl.tbDegreeAsymmetry.Text, fgFont)); table2.AddCell(new Phrase(intervalControl.tbMaterialityAsymmetry.Text, fgFont)); table2.AddCell(new Phrase(intervalControl.tbExcess.Text, fgFont)); table2.AddCell(new Phrase(intervalControl.tbExcessError.Text, fgFont)); document.Add(table2); document.NewPage(); iTextSharp.text.Paragraph p_4 = new iTextSharp.text.Paragraph("Гистограмма", fgFont); p_4.Alignment = Element.ALIGN_CENTER; document.Add(p_4); SaveToPng(intervalControl.barChart, "barChart.png"); string path = System.IO.Path.Combine(Directory.GetCurrentDirectory(), "barChart.png"); iTextSharp.text.Image chart_image = iTextSharp.text.Image.GetInstance(path); chart_image.Alignment = Element.ALIGN_CENTER; chart_image.ScaleToFit(344f, 336f); document.Add(chart_image); File.Delete(path); document.Close(); writer.Close(); } else { dialogError.IsOpen = true; } }
public void GenerateReport(List <ISimulationObject> objects, string format, Stream ms) { string ptext = ""; switch (format) { case "PDF": iTextSharp.text.Document document = new iTextSharp.text.Document(PageSize.A4, 25, 25, 30, 30); var writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, ms); var bf = iTextSharp.text.pdf.BaseFont.CreateFont(iTextSharp.text.pdf.BaseFont.COURIER, iTextSharp.text.pdf.BaseFont.CP1252, true); var regfont = new Font(bf, 12, Font.NORMAL); var boldfont = new Font(bf, 12, Font.BOLD); document.Open(); document.Add(new Paragraph("DWSIM Simulation Results Report", boldfont)); document.Add(new Paragraph("Simulation Name: " + Options.SimulationName, boldfont)); document.Add(new Paragraph("Date created: " + System.DateTime.Now.ToString() + "\n\n", boldfont)); foreach (var obj in objects) { ptext = obj.GetDisplayName() + ": " + obj.GraphicObject.Tag + "\n\n"; document.Add(new Paragraph(ptext, boldfont)); ptext = obj.GetReport(Options.SelectedUnitSystem, System.Globalization.CultureInfo.CurrentCulture, Options.NumberFormat); ptext += "\n"; document.Add(new Paragraph(ptext, regfont)); } document.Close(); writer.Close(); break; case "TXT": string report = ""; report += "DWSIM Simulation Results Report\nSimulation Name: " + Options.SimulationName + "\nDate created: " + System.DateTime.Now.ToString() + "\n\n"; foreach (var obj in objects) { ptext = ""; ptext += obj.GetDisplayName() + ": " + obj.GraphicObject.Tag + "\n\n"; ptext += obj.GetReport(Options.SelectedUnitSystem, System.Globalization.CultureInfo.CurrentCulture, Options.NumberFormat); ptext += "\n"; report += ptext; } using (StreamWriter wr = new StreamWriter(ms)) { wr.Write(report); } break; default: throw new NotImplementedException("Sorry, this feature is not yet available."); } }
public bool Print() { try { rptFont = FontFactory.GetFont("Arial", 8, Font.NORMAL); rptFontBold = FontFactory.GetFont("Arial", 8, Font.BOLD); rptFontHeader = FontFactory.GetFont("Arial", 10, Font.BOLD); if (string.IsNullOrWhiteSpace(_context.OutputPath)) { FileLogger.Instance.logMessage(LogLevel.ERROR, this, "Authorization to release fingerprints printing failed since file name is not set"); return(false); } document = new Document(PageSize.HALFLETTER.Rotate()); document.AddTitle("Authorization to Release Fingerprints"); var writer = PdfWriter.GetInstance(document, new FileStream(_context.OutputPath, FileMode.Create)); const int headerTableColumns = 2; var headerTable = new PdfPTable(headerTableColumns) { WidthPercentage = 100 }; headerTable.AddCell( new PdfPCell(new Paragraph("Date: " + string.Format("{0:MM/dd/yyyy}", DateTime.Parse(_context.TransactionDate)), rptFont)) { Border = Rectangle.NO_BORDER }); headerTable.AddCell( new PdfPCell(new Paragraph("Employee #: " + _context.EmployeeNumber, rptFont)) { Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_RIGHT }); headerTable.AddCell(new PdfPCell(new Paragraph("Authorization to Release Fingerprints", rptFontHeader)) { Border = Rectangle.BOTTOM_BORDER, HorizontalAlignment = Element.ALIGN_CENTER, Colspan = headerTableColumns }); headerTable.AddCell(new PdfPCell(new Phrase()) { Border = Rectangle.NO_BORDER, Colspan = headerTableColumns, FixedHeight = 10 }); // empty row const int bodyTableColumns = 2; var bodyTable = new PdfPTable(bodyTableColumns) { WidthPercentage = 100 }; bodyTable.SetWidths(new [] { .5f, 2.5f }); bodyTable.AddCell(new PdfPCell(new Paragraph("Received From:", rptFont)) { Border = Rectangle.NO_BORDER, VerticalAlignment = Element.ALIGN_LEFT, Colspan = 1 }); bodyTable.AddCell(new PdfPCell(new Paragraph(_context.ShopName, rptFont)) { Border = Rectangle.NO_BORDER, VerticalAlignment = Element.ALIGN_LEFT, Colspan = 1 }); bodyTable.AddCell(new PdfPCell(new Paragraph("", rptFont)) { Border = Rectangle.NO_BORDER, VerticalAlignment = Element.ALIGN_LEFT, Colspan = 1 }); bodyTable.AddCell(new PdfPCell(new Paragraph(_context.ShopAddress, rptFont)) { Border = Rectangle.NO_BORDER, VerticalAlignment = Element.ALIGN_LEFT, Colspan = 1 }); bodyTable.AddCell(new PdfPCell(new Paragraph("", rptFont)) { Border = Rectangle.NO_BORDER, VerticalAlignment = Element.ALIGN_LEFT, Colspan = 1 }); bodyTable.AddCell(new PdfPCell(new Paragraph(string.Format("{0}, {1} {2}", _context.ShopCity, _context.ShopState, _context.ShopZipCode), rptFont)) { Border = Rectangle.NO_BORDER, VerticalAlignment = Element.ALIGN_LEFT, Colspan = 1 }); bodyTable.AddCell(new PdfPCell(new Phrase()) { Border = Rectangle.NO_BORDER, Colspan = headerTableColumns, FixedHeight = 10 }); // empty row bodyTable.AddCell(new PdfPCell(new Paragraph("Pawned By:", rptFont)) { Border = Rectangle.NO_BORDER, VerticalAlignment = Element.ALIGN_LEFT, Colspan = 1 }); bodyTable.AddCell(new PdfPCell(new Paragraph(_context.CustomerName, rptFont)) { Border = Rectangle.NO_BORDER, VerticalAlignment = Element.ALIGN_LEFT, Colspan = 1 }); bodyTable.AddCell(new PdfPCell(new Paragraph("", rptFont)) { Border = Rectangle.NO_BORDER, VerticalAlignment = Element.ALIGN_LEFT, Colspan = 1 }); bodyTable.AddCell(new PdfPCell(new Paragraph(FormatCustomerAddress(), rptFont)) { Border = Rectangle.NO_BORDER, VerticalAlignment = Element.ALIGN_LEFT, Colspan = 1 }); bodyTable.AddCell(new PdfPCell(new Paragraph("", rptFont)) { Border = Rectangle.NO_BORDER, VerticalAlignment = Element.ALIGN_LEFT, Colspan = 1 }); bodyTable.AddCell(new PdfPCell(new Paragraph(string.Format("{0}, {1} {2}", _context.CustomerCity, _context.CustomerState, _context.CustomerZipCode), rptFont)) { Border = Rectangle.NO_BORDER, VerticalAlignment = Element.ALIGN_LEFT, Colspan = 1 }); bodyTable.AddCell(new PdfPCell(new Phrase()) { Border = Rectangle.NO_BORDER, Colspan = bodyTableColumns, FixedHeight = 10 }); // empty row const int bodyTable2Columns = 3; var bodyTable2 = new PdfPTable(bodyTable2Columns) { WidthPercentage = 100 }; bodyTable2.SetWidths(new[] { .5f, 1f, 1.5f }); bodyTable2.AddCell(new PdfPCell(new Paragraph("Authorization #:", rptFont)) { Border = Rectangle.NO_BORDER, VerticalAlignment = Element.ALIGN_LEFT, Colspan = 1 }); bodyTable2.AddCell(new PdfPCell(new Paragraph(_seizeNumber.ToString(), rptFont)) { Border = Rectangle.NO_BORDER, VerticalAlignment = Element.ALIGN_LEFT, Colspan = 1 }); string loanBuyLabel = _productType == ProductType.BUY ? "Buy" : "Loan"; bodyTable2.AddCell(new PdfPCell(new Paragraph(loanBuyLabel + "#: " + _context.TicketNumber, rptFont)) { Border = Rectangle.NO_BORDER, VerticalAlignment = Element.ALIGN_LEFT, Colspan = 1 }); bodyTable2.AddCell(new PdfPCell(new Phrase()) { Border = Rectangle.NO_BORDER, Colspan = bodyTable2Columns, FixedHeight = 10 }); // empty row const int bodyTable3Columns = 2; var bodyTable3 = new PdfPTable(bodyTable3Columns) { WidthPercentage = 100 }; bodyTable3.SetWidths(new[] { .65f, 2.35f }); bodyTable3.AddCell(new PdfPCell(new Paragraph("Agency Receiving Fingerprint", rptFont)) { Border = Rectangle.NO_BORDER, VerticalAlignment = Element.ALIGN_LEFT, Colspan = 1 }); bodyTable3.AddCell(new PdfPCell(new Paragraph(": " + _context.Agency, rptFont)) { Border = Rectangle.NO_BORDER, VerticalAlignment = Element.ALIGN_LEFT, Colspan = 1 }); bodyTable3.AddCell(new PdfPCell(new Paragraph("Case #", rptFont)) { Border = Rectangle.NO_BORDER, VerticalAlignment = Element.ALIGN_LEFT, Colspan = 1 }); bodyTable3.AddCell(new PdfPCell(new Paragraph(": " + _context.CaseNumber, rptFont)) { Border = Rectangle.NO_BORDER, VerticalAlignment = Element.ALIGN_LEFT, Colspan = 1 }); bodyTable3.AddCell(new PdfPCell(new Paragraph("Subpoena #", rptFont)) { Border = Rectangle.NO_BORDER, VerticalAlignment = Element.ALIGN_LEFT, Colspan = 1 }); bodyTable3.AddCell(new PdfPCell(new Paragraph(": " + _context.SubpoenaNumber, rptFont)) { Border = Rectangle.NO_BORDER, VerticalAlignment = Element.ALIGN_LEFT, Colspan = 1 }); bodyTable3.AddCell(new PdfPCell(new Paragraph("Officer Name / Badge #:", rptFont)) { Border = Rectangle.NO_BORDER, VerticalAlignment = Element.ALIGN_LEFT, Colspan = 1 }); bodyTable3.AddCell(new PdfPCell(new Paragraph(string.Format(": {0} / {1}", _context.OfficerName, _context.BadgeNumber), rptFont)) { Border = Rectangle.NO_BORDER, VerticalAlignment = Element.ALIGN_LEFT, Colspan = 1 }); bodyTable3.AddCell(new PdfPCell(new Phrase()) { Border = Rectangle.NO_BORDER, Colspan = bodyTable3Columns, FixedHeight = 10 }); // empty row bodyTable3.AddCell(new PdfPCell(new Phrase()) { Border = Rectangle.NO_BORDER, Colspan = bodyTable3Columns, FixedHeight = 10 }); // empty row bodyTable3.AddCell(new PdfPCell(new Phrase()) { Border = Rectangle.NO_BORDER, Colspan = bodyTable3Columns, FixedHeight = 10 }); // empty row const int signatureTableColumns = 3; var signatureTable = new PdfPTable(signatureTableColumns) { WidthPercentage = 100 }; signatureTable.SetWidths(new[] { 3F, 1F, 3F }); signatureTable.AddCell(new PdfPCell(new Paragraph("X", rptFont)) { Border = Rectangle.BOTTOM_BORDER, VerticalAlignment = Element.ALIGN_LEFT, Colspan = 1 }); signatureTable.AddCell(new PdfPCell(new Paragraph("", rptFont)) { Border = Rectangle.NO_BORDER, VerticalAlignment = Element.ALIGN_LEFT, Colspan = 1 }); signatureTable.AddCell(new PdfPCell(new Paragraph("X", rptFont)) { Border = Rectangle.BOTTOM_BORDER, VerticalAlignment = Element.ALIGN_LEFT, Colspan = 1 }); signatureTable.AddCell(new PdfPCell(new Paragraph(" Employee Signature", rptFont)) { Border = Rectangle.NO_BORDER, VerticalAlignment = Element.ALIGN_LEFT, Colspan = 1 }); signatureTable.AddCell(new PdfPCell(new Paragraph("", rptFont)) { Border = Rectangle.NO_BORDER, VerticalAlignment = Element.ALIGN_LEFT, Colspan = 1 }); signatureTable.AddCell(new PdfPCell(new Paragraph(" Officer Signature", rptFont)) { Border = Rectangle.NO_BORDER, VerticalAlignment = Element.ALIGN_LEFT, Colspan = 1 }); document.Open(); document.Add(headerTable); document.Add(bodyTable); document.Add(bodyTable2); document.Add(bodyTable3); document.Add(signatureTable); document.Close(); } catch (Exception de) { FileLogger.Instance.logMessage(LogLevel.ERROR, this, "Authorization to release fingerprints printing " + de.Message); return(false); } return(true); }
public void PDFESTADOCERO() { Buscadores bus = new Buscadores(); vehiculo ovehiculo = bus.buscarvehiculo(txtpatente.Value); cliente ocliente = bus.ocliente(ovehiculo); modelo omarca = bus.buscarmodelo(ovehiculo); marca omodelo = bus.buscarmarca(omarca); iTextSharp.text.Rectangle rec = new iTextSharp.text.Rectangle(PageSize.A4); var doc = new iTextSharp.text.Document(rec); rec.BackgroundColor = new BaseColor(System.Drawing.Color.Olive); doc.SetPageSize(iTextSharp.text.PageSize.A4); string path = Server.MapPath("~"); PdfWriter.GetInstance(doc, new FileStream(path + "/Presupuesto.pdf", FileMode.Create)); doc.Open(); //Cabecera BaseFont bfntHead = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); iTextSharp.text.Font fntHead = new iTextSharp.text.Font(bfntHead, 16, 1, iTextSharp.text.BaseColor.GREEN.Darker()); Paragraph prgHeading = new Paragraph(); prgHeading.Alignment = Element.ALIGN_LEFT; prgHeading.Add(new Chunk("Taller de Reparaciones - Presupuesto".ToUpper(), fntHead)); doc.Add(prgHeading); //Generado By Paragraph prgGeneratedBY = new Paragraph(); BaseFont btnAuthor = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); iTextSharp.text.Font fntAuthor = new iTextSharp.text.Font(btnAuthor, 8, 2, iTextSharp.text.BaseColor.BLACK); prgGeneratedBY.Alignment = Element.ALIGN_RIGHT; prgGeneratedBY.Add(new Chunk("Generado por: " + LogEmpleado.nombreyapellido, fntAuthor)); //Agregar LOG Empleado prgGeneratedBY.Add(new Chunk("\nFecha Generado valido por 5 dias : " + DateTime.Now.ToShortDateString(), fntAuthor)); prgGeneratedBY.Add(new Chunk("\nN° de Orden : " + OrdenActual.id_orden, fntAuthor)); doc.Add(prgGeneratedBY); //La f Linea Paragraph p = new Paragraph(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(0.0F, 100.0F, iTextSharp.text.BaseColor.BLACK, Element.ALIGN_LEFT, 1))); doc.Add(p); //Espacio doc.Add(new Chunk("\n", fntHead)); //Datos Paragraph Datos = new Paragraph(); BaseFont bfntDatos = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); iTextSharp.text.Font fntDatos = new iTextSharp.text.Font(bfntDatos, 12, 0, iTextSharp.text.BaseColor.BLACK); Datos.Alignment = Element.ALIGN_CENTER; Datos.Add(new Chunk("Apellido y Nombre: " + ocliente.nombre + " DNI: " + ocliente.dni + " Telefono: " + ocliente.telefono + "\nCorreo Electronico: " + ocliente.email, fntDatos)); Datos.Add(new Chunk("\nPatente: " + ovehiculo.patente + " Modelo:" + omodelo.nombre + " Marca: " + omarca.nombre, fntDatos)); doc.Add(Datos); //Espacio doc.Add(new Chunk("\n", fntHead)); //Tabla PdfPTable table = new PdfPTable(dtable.Columns.Count); for (int i = 0; i < dtable.Columns.Count; i++) { string cellText = Server.HtmlDecode(dtable.Columns[i].ColumnName); PdfPCell cell = new PdfPCell(); cell.Phrase = new Phrase(cellText, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 10, 1, new BaseColor(System.Drawing.ColorTranslator.FromHtml("#000000")))); cell.BackgroundColor = new BaseColor(System.Drawing.ColorTranslator.FromHtml("#C8C8C8")); cell.HorizontalAlignment = Element.ALIGN_CENTER; cell.PaddingBottom = 5; table.AddCell(cell); } //Agregando Campos a la tabla for (int i = 0; i < dtable.Rows.Count; i++) { for (int j = 0; j < dtable.Columns.Count; j++) { table.AddCell(dtable.Rows[i][j].ToString()); } } doc.Add(table); //Espacio doc.Add(new Chunk("\n", fntHead)); //Datos2.0 Paragraph Datos2 = new Paragraph(); Datos2.Alignment = Element.ALIGN_RIGHT; Datos2.Add(new Chunk("\nPrecio Total= $" + lblprecio.Text, fntDatos)); doc.Add(Datos2); Paragraph Datos3 = new Paragraph(); Datos3.Alignment = Element.ALIGN_CENTER; iTextSharp.text.Font fntDatos3 = new iTextSharp.text.Font(bfntDatos, 12, 1, iTextSharp.text.BaseColor.BLACK); Datos3.Add(new Chunk("\nPresupuesto NO VALIDO como Factura", fntDatos3)); doc.Add(Datos3); doc.Close(); Page.ClientScript.RegisterStartupScript(this.GetType(), "OpenWindow", "window.open('Presupuesto.pdf','_newtab');", true); }
public static ActionResult PDF( int companyId, DateTime?from, DateTime?to, int status, string listOrder, string filterText) { var res = ActionResult.NoAction; var user = HttpContext.Current.Session["User"] as ApplicationUser; dictionary = HttpContext.Current.Session["Dictionary"] as Dictionary <string, string>; var company = new Company(companyId); string path = HttpContext.Current.Request.PhysicalApplicationPath; if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase)) { path = string.Format(CultureInfo.InvariantCulture, @"{0}\", path); } var formatedDescription = ToolsPdf.NormalizeFileName(company.Name); string fileName = string.Format( CultureInfo.InvariantCulture, @"{0}_{1}_{2:yyyyMMddhhmmss}.pdf", dictionary["Item_Objetivo_List"], formatedDescription, DateTime.Now); // FONTS string pathFonts = HttpContext.Current.Request.PhysicalApplicationPath; if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase)) { pathFonts = string.Format(CultureInfo.InstalledUICulture, @"{0}\", pathFonts); } var headerFont = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\ARIAL.TTF", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED); var arial = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\ARIAL.TTF", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED); var pdfDoc = new iTS.Document(iTS.PageSize.A4.Rotate(), 40, 40, 80, 50); var writer = iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDoc, new FileStream( string.Format(CultureInfo.InvariantCulture, @"{0}Temp\{1}", path, fileName), FileMode.Create)); writer.PageEvent = new TwoColumnHeaderFooter() { CompanyLogo = string.Format(CultureInfo.InvariantCulture, @"{0}\images\logos\{1}.jpg", path, company.Id), IssusLogo = string.Format(CultureInfo.InvariantCulture, "{0}issus.png", path), Date = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", DateTime.Now), CreatedBy = user.UserName, CompanyId = company.Id, CompanyName = company.Name, Title = dictionary["Item_Objetivo_List"].ToUpperInvariant() }; pdfDoc.Open(); var rowEven = new iTS.BaseColor(240, 240, 240); var titleTable = new iTSpdf.PdfPTable(1); titleTable.SetWidths(new float[] { 50f }); titleTable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(CultureInfo.InvariantCulture, "{0} - {1}", dictionary["Item_EquipmentList"], company.Name), ToolsPdf.LayoutFonts.TitleFont)) { HorizontalAlignment = iTS.Element.ALIGN_CENTER, Border = iTS.Rectangle.NO_BORDER }); #region Criteria var criteriatable = new iTSpdf.PdfPTable(4) { WidthPercentage = 100 }; criteriatable.SetWidths(new float[] { 20f, 50f, 20f, 150f }); #region texts string periode = string.Empty; if (from.HasValue && to == null) { periode = string.Format(CultureInfo.InvariantCulture, @"{0} {1:dd/MM/yyyy}", dictionary["Item_IncidentAction_List_Filter_From"], from); } else if (from == null && to.HasValue) { periode = string.Format(CultureInfo.InvariantCulture, @"{0} {1:dd/MM/yyyy}", dictionary["Item_IncidentAction_List_Filter_To"], to); } else if (from.HasValue && to.HasValue) { periode = string.Format(CultureInfo.InvariantCulture, @"{0:dd/MM/yyyy} {1:dd/MM/yyyy}", from, to); } else { periode = dictionary["Common_All_Male"]; } string statusText = dictionary["Common_All"]; if (status == 1) { statusText = dictionary["Item_ObjetivoAction_List_Filter_ShowActive"]; } if (status == 2) { statusText = dictionary["Item_ObjetivoAction_List_Filter_ShowClosed"]; } #endregion ToolsPdf.AddCriteria(criteriatable, dictionary["Common_Period"], periode); ToolsPdf.AddCriteria(criteriatable, dictionary["Item_IncidentAction_Header_Status"], statusText); if (!string.IsNullOrEmpty(filterText)) { ToolsPdf.AddCriteria(criteriatable, dictionary["Common_PDF_Filter_Contains"], filterText); } pdfDoc.Add(criteriatable); #endregion var table = new iTSpdf.PdfPTable(5) { WidthPercentage = 100, HorizontalAlignment = 1, SpacingBefore = 20f, SpacingAfter = 30f }; table.SetWidths(new float[] { 7f, 50f, 30f, 12f, 12f }); table.AddCell(ToolsPdf.HeaderCell(dictionary["Common_Status"])); table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Objetivo_Header_Name"])); table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Objetivo_Header_Responsible"])); table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Objetivo_Header_StartDate"])); table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Objetivo_Header_PreviewEndDate"])); int cont = 0; var data = Objetivo.Filter(companyId, from, to, status).ToList(); foreach (var item in data) { if (!item.Objetivo.EndDate.HasValue) { item.Objetivo.EndDate = item.Objetivo.PreviewEndDate; } } switch (listOrder.ToUpperInvariant()) { default: case "TH0|ASC": data = data.OrderBy(d => d.Objetivo.Name).ToList(); break; case "TH0|DESC": data = data.OrderByDescending(d => d.Objetivo.Name).ToList(); break; case "TH1|ASC": data = data.OrderBy(d => d.Objetivo.Responsible.FullName).ToList(); break; case "TH1|DESC": data = data.OrderByDescending(d => d.Objetivo.Responsible.FullName).ToList(); break; case "TH2|ASC": data = data.OrderBy(d => d.Objetivo.StartDate).ToList(); break; case "TH2|DESC": data = data.OrderByDescending(d => d.Objetivo.StartDate).ToList(); break; case "TH3|ASC": data = data.OrderBy(d => d.Objetivo.EndDate).ToList(); break; case "TH3|DESC": data = data.OrderByDescending(d => d.Objetivo.EndDate).ToList(); break; } cont = 0; foreach (var item in data) { if (!string.IsNullOrEmpty(filterText)) { var show = false; if (item.Objetivo.Name.IndexOf(filterText, StringComparison.OrdinalIgnoreCase) != -1) { show = true; } if (item.Objetivo.Responsible.FullName.IndexOf(filterText, StringComparison.OrdinalIgnoreCase) != -1) { show = true; } if (!show) { continue; } } string endDateText = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", item.Objetivo.PreviewEndDate); if (item.Objetivo.EndDate.HasValue) { endDateText = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", item.Objetivo.EndDate); } table.AddCell(ToolsPdf.DataCell(item.Objetivo.Active ? dictionary["Common_Active"] : dictionary["Common_Inactve"], ToolsPdf.LayoutFonts.Times)); table.AddCell(ToolsPdf.DataCell(item.Objetivo.Name, ToolsPdf.LayoutFonts.Times)); table.AddCell(ToolsPdf.DataCell(item.Objetivo.Responsible.FullName, ToolsPdf.LayoutFonts.Times)); table.AddCell(ToolsPdf.DataCellCenter(string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", item.Objetivo.StartDate), ToolsPdf.LayoutFonts.Times)); table.AddCell(ToolsPdf.DataCellCenter(endDateText, ToolsPdf.LayoutFonts.Times)); cont++; } string totalRegistros = string.Format( CultureInfo.InvariantCulture, @"{0}: {1}", dictionary["Common_RegisterCount"], cont); table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(totalRegistros, ToolsPdf.LayoutFonts.Times)) { Border = iTS.Rectangle.TOP_BORDER, BackgroundColor = rowEven, Padding = 6f, PaddingTop = 4f, Colspan = 2 }); table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Empty, ToolsPdf.LayoutFonts.Times)) { Border = iTS.Rectangle.TOP_BORDER, BackgroundColor = rowEven, Colspan = 3 }); pdfDoc.Add(table); pdfDoc.CloseDocument(); res.SetSuccess(string.Format(CultureInfo.InvariantCulture, @"{0}Temp/{1}", ConfigurationManager.AppSettings["siteUrl"], fileName)); return(res); }
public bool CreateReport() { bool isSuccessful = false; iTextSharp.text.Document document = new iTextSharp.text.Document(PageSize.LETTER); try { //set up RunReport event overrides & create doc //_pageCount = 1; RefurbList events = this; PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(ReportObject.ReportTempFileFullName, FileMode.Create)); writer.PageEvent = events; MultiColumnText columns = new MultiColumnText(document.PageSize.Top - 90, document.PageSize.Height - (100)); columns.AddSimpleColumn(-5, document.PageSize.Width - 15); //set up tables, etc... int colspan = 12; var table = new PdfPTable(colspan); table.WidthPercentage = 95;// document.PageSize.Width; //table.TotalHeight = 95; var cell = new PdfPCell(); var gif = Image.GetInstance(Common.Properties.Resources.logo, BaseColor.WHITE); gif.ScalePercent(25); runReport = new RunReport(); document.Open(); document.SetPageSize(PageSize.LETTER); document.SetMargins(-100, -20, 10, 35); document.AddTitle(string.Format("{0}: {1}", ReportObject.ReportTitle, DateTime.Now.ToString("MM/dd/yyyy"))); ReportColumns(table, colspan, "Merchandise Expected to be Received from Refurb"); WriteDetail(table, colspan, ReportObject.ListRefurbItemsExpected); WriteTotals(table, colspan, ReportObject.ListRefurbItemsExpected); WriteCell(table, string.Empty, ReportFontBold, colspan, Element.ALIGN_LEFT, Rectangle.NO_BORDER); WriteCell(table, string.Empty, ReportFontBold, colspan, Element.ALIGN_LEFT, Rectangle.NO_BORDER); WriteCell(table, string.Empty, ReportFontBold, colspan, Element.ALIGN_LEFT, Rectangle.NO_BORDER); WriteCell(table, string.Empty, ReportFontBold, colspan, Element.ALIGN_LEFT, Rectangle.NO_BORDER); ReportColumns(table, colspan, "Merchandise Not Expected to be Received from Refurb"); WriteDetail(table, colspan, ReportObject.ListRefurbItemsNotExpected); WriteTotals(table, colspan, ReportObject.ListRefurbItemsNotExpected); WriteCell(table, string.Empty, ReportFont, colspan, Element.ALIGN_LEFT, Element.ALIGN_TOP, Rectangle.NO_BORDER); columns.AddElement(table); document.Add(columns); document.Close(); //OpenFile(ReportObject.ReportTempFileFullName); //CreateReport(); isSuccessful = true; } catch (DocumentException de) { ReportObject.ReportError = de.Message; ReportObject.ReportErrorLevel = (int)LogLevel.ERROR; } catch (IOException ioe) { ReportObject.ReportError = ioe.Message; ReportObject.ReportErrorLevel = (int)LogLevel.ERROR; } return(isSuccessful); }
public bool Print() { // Create a return value so there is only one way out of this function bool retval; try { if (string.IsNullOrWhiteSpace(Context.FilePath)) { FileLogger.Instance.logMessage(LogLevel.ERROR, this, "No file name is set for Indiana Partial Payment Receipt. Printing did not complete successfully!"); retval = false; } else { document = new Document(PageSize.HALFLETTER.Rotate()); document.AddTitle("Partial Payment Receipt"); var writer = PdfWriter.GetInstance(document, new FileStream(Context.FilePath, FileMode.Create)); var MainTable = new PdfPTable(2) { TotalWidth = 1500f }; // Add ticket information PdfPCell cell; var blankCell = new PdfPCell(new Phrase("")) { Border = Rectangle.NO_BORDER }; // Insert spacer row MainTable.AddCell(blankCell); MainTable.AddCell(blankCell); MainTable.AddCell(new PdfPCell(GenerateItemListTable()) { Border = Rectangle.NO_BORDER }); MainTable.AddCell(new PdfPCell(GenerateCostTable()) { Border = Rectangle.NO_BORDER }); MainTable.AddCell(new PdfPCell(GenerateCustomerInformationTable()) { Border = Rectangle.NO_BORDER }); MainTable.AddCell(blankCell); document.Open(); document.Add(GenerateHeaderTable()); document.Add(MainTable); document.Close(); retval = true; } } catch (Exception de) { FileLogger.Instance.logMessage(LogLevel.ERROR, this, "Partial Payment Receipt printing {0}", de.Message); retval = false; } return(retval); }
public static ActionResult PDF(int companyId, string listOrder) { var res = ActionResult.NoAction; var user = HttpContext.Current.Session["User"] as ApplicationUser; dictionary = HttpContext.Current.Session["Dictionary"] as Dictionary <string, string>; var company = new Company(companyId); string path = HttpContext.Current.Request.PhysicalApplicationPath; if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase)) { path = string.Format(CultureInfo.InvariantCulture, @"{0}\", path); } var formatedDescription = ToolsPdf.NormalizeFileName(company.Name); string fileName = string.Format( CultureInfo.InvariantCulture, @"{0}_{1}_{2:yyyyMMddhhmmss}.pdf", dictionary["Item_EquipmentList"], formatedDescription, DateTime.Now); // FONTS string pathFonts = HttpContext.Current.Request.PhysicalApplicationPath; if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase)) { pathFonts = string.Format(CultureInfo.InstalledUICulture, @"{0}\", pathFonts); } var headerFont = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\ARIAL.TTF", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED); var arial = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\ARIAL.TTF", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED); var pdfDoc = new iTS.Document(iTS.PageSize.A4.Rotate(), 40, 40, 80, 50); var writer = iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDoc, new FileStream( string.Format(CultureInfo.InvariantCulture, @"{0}Temp\{1}", path, fileName), FileMode.Create)); writer.PageEvent = new TwoColumnHeaderFooter() { CompanyLogo = string.Format(CultureInfo.InvariantCulture, @"{0}\images\logos\{1}.jpg", path, company.Id), IssusLogo = string.Format(CultureInfo.InvariantCulture, "{0}issus.png", path), Date = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", DateTime.Now), CreatedBy = user.UserName, CompanyId = company.Id, CompanyName = company.Name, Title = dictionary["Item_EquipmentList"].ToUpperInvariant() }; pdfDoc.Open(); var backgroundColor = new iTS.BaseColor(225, 225, 225); var rowPair = new iTS.BaseColor(255, 255, 255); var rowEven = new iTS.BaseColor(240, 240, 240); var titleTable = new iTSpdf.PdfPTable(1); titleTable.SetWidths(new float[] { 50f }); var titleCell = new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(CultureInfo.InvariantCulture, "{0} - {1}", dictionary["Item_EquipmentList"], company.Name), ToolsPdf.LayoutFonts.TitleFont)) { HorizontalAlignment = iTS.Element.ALIGN_CENTER, Border = iTS.Rectangle.NO_BORDER }; titleTable.AddCell(titleCell); // @alex: hay que indicar que hay una columna menos por fila //// var table = new iTSpdf.PdfPTable(4) var table = new iTSpdf.PdfPTable(3) { WidthPercentage = 100, HorizontalAlignment = 1, SpacingBefore = 20f, SpacingAfter = 30f }; table.SetWidths(new float[] { 20f, 10f, 5f, 15f }); table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Equipment_Header_Code"] + " - " + dictionary["Item_Equipment_Header_Description"])); table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Equipment_Header_Location"])); // @alex: se omite la columna de la cabecera //// table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Equipment_Header_Cost"])); table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Equipment_Header_Responsible"])); int cont = 0; var data = Equipment.ByCompany(companyId).ToList(); string filter = GetFilter(); if (filter.IndexOf("1", StringComparison.OrdinalIgnoreCase) != -1) { data = data.Where(d => !d.EndDate.HasValue).ToList(); } if (filter.IndexOf("2", StringComparison.OrdinalIgnoreCase) != -1) { data = data.Where(d => d.EndDate.HasValue).ToList(); } var dataC = new List <Equipment>(); if (filter.IndexOf("C", StringComparison.OrdinalIgnoreCase) != -1) { dataC = data.Where(d => d.IsCalibration).ToList(); } var dataV = new List <Equipment>(); if (filter.IndexOf("V", StringComparison.OrdinalIgnoreCase) != -1) { dataV = data.Where(d => d.IsVerification).ToList(); } var dataM = new List <Equipment>(); if (filter.IndexOf("M", StringComparison.OrdinalIgnoreCase) != -1) { dataM = data.Where(d => d.IsMaintenance).ToList(); } data = dataC; foreach (var equipmentV in dataV) { if (!data.Any(d => d.Id == equipmentV.Id)) { data.Add(equipmentV); } } foreach (var equipmentM in dataM) { if (!data.Any(d => d.Id == equipmentM.Id)) { data.Add(equipmentM); } } // aplicar filtros //------ CRITERIA var criteriatable = new iTSpdf.PdfPTable(2) { WidthPercentage = 100 }; criteriatable.SetWidths(new float[] { 8f, 50f }); string statusText = string.Empty; string operativaText = string.Empty; if (filter.IndexOf("0") != -1) { statusText = dictionary["Common_All"]; } else if (filter.IndexOf("1") != -1) { statusText = dictionary["Item_Equipment_List_Filter_ShowActive"]; } else if (filter.IndexOf("2") != -1) { statusText = dictionary["Item_Equipment_List_Filter_ShowClosed"]; } bool first = true; if (filter.IndexOf("C") != -1) { first = false; operativaText = dictionary["Item_Equipment_List_Filter_ShowCalibration"]; } if (filter.IndexOf("V") != -1) { if (!first) { operativaText += ", "; } first = false; operativaText += dictionary["Item_Equipment_List_Filter_ShowVerification"]; } if (filter.IndexOf("M") != -1) { if (!first) { operativaText += ", "; } first = false; operativaText += dictionary["Item_Equipment_List_Filter_ShowMaintenance"]; } ToolsPdf.AddCriteria(criteriatable, dictionary["Item_Equipment_List_Filter_ShowByOperation"], operativaText); ToolsPdf.AddCriteria(criteriatable, dictionary["Item_Equipment_List_Filter_ShowByStatus"], statusText); bool pair = false; decimal total = 0; int border = 0; if (!string.IsNullOrEmpty(listOrder)) { switch (listOrder.ToUpperInvariant()) { default: case "TH0|ASC": data = data.OrderBy(d => d.Code).ToList(); break; case "TH0|DESC": data = data.OrderByDescending(d => d.Code).ToList(); break; case "TH1|ASC": data = data.OrderBy(d => d.Location).ToList(); break; case "TH1|DESC": data = data.OrderByDescending(d => d.Location).ToList(); break; case "TH2|ASC": data = data.OrderBy(d => d.Responsible.FullName).ToList(); break; case "TH2|DESC": data = data.OrderByDescending(d => d.Responsible.FullName).ToList(); break; case "TH3|ASC": data = data.OrderBy(d => d.TotalCost).ToList(); break; case "TH3|DESC": data = data.OrderByDescending(d => d.TotalCost).ToList(); break; } } foreach (Equipment equipment in data) { total += equipment.TotalCost; var lineBackground = pair ? rowEven : rowPair; table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(equipment.Code + " - " + equipment.Description, ToolsPdf.LayoutFonts.Times)) { Border = border, BackgroundColor = lineBackground, Padding = 6f, PaddingTop = 4f }); table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(equipment.Location, ToolsPdf.LayoutFonts.Times)) { Border = border, BackgroundColor = lineBackground, Padding = 6f, PaddingTop = 4f }); // @alex: se omite la celda de los datos del coste /*string totalCost = string.Format("{0:#,##0.00}", equipment.TotalCost); * table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(totalCost, ToolsPdf.LayoutFonts.Times)) * { * Border = border, * BackgroundColor = lineBackground, * Padding = 6f, * PaddingTop = 4f, * HorizontalAlignment = 2 * });*/ table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(equipment.Responsible.FullName, ToolsPdf.LayoutFonts.Times)) { Border = border, BackgroundColor = lineBackground, Padding = 6f, PaddingTop = 4f }); cont++; } string totalRegistros = string.Format( CultureInfo.InvariantCulture, @"{0}: {1}", dictionary["Common_RegisterCount"], cont); table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(totalRegistros, ToolsPdf.LayoutFonts.Times)) { Border = iTS.Rectangle.TOP_BORDER, BackgroundColor = rowEven, Padding = 6f, PaddingTop = 4f }); table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Common_Total"].ToUpperInvariant(), ToolsPdf.LayoutFonts.Times)) { Border = iTS.Rectangle.TOP_BORDER, BackgroundColor = rowEven, Padding = 6f, PaddingTop = 4f, HorizontalAlignment = 2 }); string totalText = string.Format("{0:#,##0.00}", total); table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(totalText, ToolsPdf.LayoutFonts.Times)) { Border = iTS.Rectangle.TOP_BORDER, BackgroundColor = rowEven, Padding = 6f, PaddingTop = 4f, HorizontalAlignment = 2 }); table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Empty, ToolsPdf.LayoutFonts.Times)) { Border = iTS.Rectangle.TOP_BORDER, BackgroundColor = rowEven, Colspan = 2 }); pdfDoc.Add(criteriatable); pdfDoc.Add(table); pdfDoc.CloseDocument(); res.SetSuccess(string.Format(CultureInfo.InvariantCulture, @"{0}Temp/{1}", ConfigurationManager.AppSettings["siteUrl"], fileName)); return(res); }
public byte[] PrintTRBalance(string Header, List <ledger> ledgerList, string balance) { MemoryStream ms = new MemoryStream(); string fileName = ""; string payMode = ""; string[] str = Header.Split(';'); string HeaderSring = "Financial Year: " + str[0] + ";Trial Balance Date: " + str[1]; string ColHeader = "SI No.;Account No;Account Date; Debit Balance; Credit Balance"; //string footer3 = "Receiver's Signature;Authorised Signatory"; int n = 1; string ColDetailString = ""; var count = ledgerList.Count(); foreach (ledger ldg in ledgerList) { if (n == count) { ColDetailString = ColDetailString + n + "+" + ldg.AccountCode + "+" + ldg.AccountName + "+" + ldg.DebitAmnt + "+" + ldg.CreditAmnt; } else { ColDetailString = ColDetailString + n + "+" + ldg.AccountCode + "+" + ldg.AccountName + "+" + ldg.DebitAmnt + "+" + ldg.CreditAmnt + ";"; } //totQuant = totQuant + pod.Quantity; //totAmnt = totAmnt + (pod.Quantity * pod.Price); n++; } try { //SaveFileDialog sfd = new SaveFileDialog(); //sfd.Title = "Save As PDF"; //sfd.Filter = "Pdf files (*.Pdf)|*.pdf"; //sfd.InitialDirectory = @"C:\"; //sfd.FileName = "ledger"; //sfd.ShowDialog(); //FileStream fs = new FileStream(sfd.FileName + ".pdf", FileMode.Create, FileAccess.Write); //fileName = sfd.FileName + ".pdf"; Rectangle rec = new Rectangle(PageSize.A4); iTextSharp.text.Document doc = new iTextSharp.text.Document(rec); PdfWriter writer = PdfWriter.GetInstance(doc, ms); MyEvent evnt = new MyEvent(); writer.PageEvent = evnt; doc.Open(); Font font1 = FontFactory.GetFont("Arial", 8, iTextSharp.text.Font.NORMAL, BaseColor.BLACK); Font font2 = FontFactory.GetFont("Arial", 8, iTextSharp.text.Font.BOLD, BaseColor.BLACK); Font font3 = FontFactory.GetFont("Arial", 8, iTextSharp.text.Font.ITALIC, BaseColor.BLACK); //String imageURL = @"D:\Smrutiranjan\PurchaseOrder\index.jpg"; //iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(imageURL); String URL = "Cellcomm2.JPG"; iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(URL); img.Alignment = Element.ALIGN_LEFT; Paragraph paragraph1 = new Paragraph(new Phrase("CELLCOMM SOLUTIONS Ltd.", font2)); paragraph1.Alignment = Element.ALIGN_CENTER; Paragraph paragraph2 = new Paragraph(new Phrase("Trial Balance", font2)); paragraph2.Alignment = Element.ALIGN_CENTER; //PrintPurchaseOrder prog = new PrintPurchaseOrder(); string[] HeaderStr = HeaderSring.Split(';'); Paragraph para = new Paragraph(); para.Add(new Chunk(HeaderStr[0] + "\n", font1)); para.Add(new Chunk(HeaderStr[1] + "\n", font1)); string[] ColHeaderStr = ColHeader.Split(';'); PdfPTable table1 = new PdfPTable(5); table1.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER; table1.WidthPercentage = 100; table1.SpacingBefore = 20; float[] width = new float[] { 0.5f, 2f, 2f, 3f, 3f }; table1.SetWidths(width); for (int i = 0; i < ColHeaderStr.Length; i++) { PdfPCell hcell = new PdfPCell(new Phrase(ColHeaderStr[i].Trim(), font2)); hcell.HorizontalAlignment = PdfPCell.ALIGN_CENTER; table1.AddCell(hcell); } //--- PdfPCell foot = new PdfPCell(new Phrase("")); foot.Colspan = 5; foot.BorderWidthTop = 0; foot.MinimumHeight = 0.5f; table1.AddCell(foot); table1.HeaderRows = 2; table1.FooterRows = 1; table1.SkipFirstHeader = false; table1.SkipLastFooter = true; //--- string[] DetailStr = ColDetailString.Split(';'); float hg = 0f; for (int i = 0; i < DetailStr.Length; i++) { string st = DetailStr[i]; hg = table1.GetRowHeight(i + 1); string[] detail = DetailStr[i].Split('+'); for (int j = 0; j < detail.Length; j++) { PdfPCell pcell; pcell = new PdfPCell(new Phrase(detail[j], font1)); pcell.HorizontalAlignment = PdfPCell.ALIGN_CENTER; table1.AddCell(pcell); string stt = detail[j]; } } if (table1.Rows.Count > 10) { table1.KeepRowsTogether(table1.Rows.Count - 4, table1.Rows.Count); } PdfPTable table2 = new PdfPTable(5); table2.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER; table2.WidthPercentage = 100; table2.SetWidths(width); //table2.SpacingBefore = 20; PdfPCell cel = new PdfPCell(new Phrase("")); cel.Colspan = 2; table2.AddCell(cel); //table2.AddCell(new Phrase("Balance",font2)); //string[] bal = balance.Split(';'); //if (bal[0].Contains("Credit")) //{ // string str4 = bal[0].Substring(bal[0].IndexOf(':') + 1); // table2.AddCell(new Phrase("")); // table2.AddCell(new Phrase(bal[0].Substring(bal[0].IndexOf(':') + 1), font2)); //} //else if (bal[0].Contains("Debit")) //{ // string str4 = bal[0].Substring(bal[0].IndexOf(':') + 1); // table2.AddCell(new Phrase(bal[0].Substring(bal[0].IndexOf(':') + 1), font2)); // table2.AddCell(new Phrase("")); //} table2.AddCell(new Phrase("Total", font2)); table2.AddCell(new Phrase(balance, font2)); table2.AddCell(new Phrase(balance, font2)); doc.Add(img); doc.Add(paragraph1); doc.Add(paragraph2); doc.Add(para); doc.Add(table1); doc.Add(table2); doc.Close(); } catch (Exception ie) { MessageBox.Show("error"); } //return fileName; byte[] pdfByte = ms.ToArray(); string path = Path.GetTempPath(); fileDir = path + "Test.pdf"; File.Delete(fileDir); using (FileStream fs = File.Create(path + "Test.pdf")) { fs.Write(pdfByte, 0, (int)pdfByte.Length); } File.SetAttributes(fileDir, FileAttributes.Hidden); System.Diagnostics.Process process = System.Diagnostics.Process.Start(path + "Test.pdf"); process.EnableRaisingEvents = true; process.Exited += new EventHandler(myProcess_Exited); process.WaitForExit(); //if (process.HasExited) //{ // MessageBox.Show("Exited"); //} //System.Diagnostics.Process.Start(path + "Test.pdf"); return(ms.ToArray()); }
private void btnSaveReport_Click(object sender, EventArgs e) { StringWriter sw = new StringWriter(); HtmlTextWriter hw = new HtmlTextWriter(sw); StringBuilder sb = new StringBuilder(); //Generate Invoice (Bill) Header. sb.Append("<p style=\"text-align:center; font-size: 32px; \"><b>University of Engineering and Technology, Lahore</b></p>"); sb.Append("<p style=\"text-align:center; font-size: 20px; \"><b>CSE Department</b></p>"); sb.Append("<p style=\"text-align:center; \"><b><u>Projects Report</b></u></p>"); StringReader sr = new StringReader(sb.ToString()); PdfPTable tbl = new PdfPTable(9); tbl.AddCell("Sr No"); tbl.AddCell("Title"); tbl.AddCell("Main Advisor"); tbl.AddCell("Co Advisor"); tbl.AddCell("Industry Advisor"); tbl.AddCell("Member 1"); tbl.AddCell("Member 2"); tbl.AddCell("Member 3"); tbl.AddCell("Member 4"); int i = 1; foreach (ProjectReport p in reports) { tbl.AddCell(i.ToString()); tbl.AddCell(p.Title); tbl.AddCell(p.MainAdvisor); tbl.AddCell(p.CoAdvisor); tbl.AddCell(p.IndustryAdvisor); tbl.AddCell(p.Member1); tbl.AddCell(p.Member2); tbl.AddCell(p.Member3); tbl.AddCell(p.Member4); ++i; } SaveFileDialog saveFileDialog = new SaveFileDialog() { Filter = "PDF file|*.pdf", ValidateNames = true }; if (saveFileDialog.ShowDialog() == DialogResult.OK) { iTextSharp.text.Document document = new iTextSharp.text.Document(PageSize.A4.Rotate()); HTMLWorker htmlparser = new HTMLWorker(document); try { PdfWriter.GetInstance(document, new FileStream(saveFileDialog.FileName, FileMode.Create)); document.Open(); htmlparser.Parse(sr); document.Add(new iTextSharp.text.Paragraph("\n Date : " + DateTime.Now.ToShortDateString() + "\n \n")); document.Add(tbl); document.Add(new iTextSharp.text.Paragraph("\n \n This report was generated by computer. Errors are acceptible. ")); } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { document.Close(); } MessageBox.Show("Report saved successfully"); } }
private void exportToPDF(DataTable dt) { iTextSharp.text.Document document = new iTextSharp.text.Document(PageSize.LEDGER, 10, 10, 42, 35); //using (Document document = new Document(PageSize.LEDGER, 10, 10, 42, 35)) //string title = "System Report (Visitor)_" + DateTime.Now.ToString("yyyyMMdd_hhmmss") + ".pdf"; PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(txtBoxPath.Text, FileMode.Create)); HeaderFooter hf = new HeaderFooter(); writer.SetBoxSize("art", new Rectangle(36, 54, 220, 760)); writer.PageEvent = hf; document.Open(); var logo = CondorProject.Properties.Resources.textCondor; var logoCondor = iTextSharp.text.Image.GetInstance(logo, BaseColor.WHITE); logoCondor.Alignment = Image.ALIGN_CENTER; document.Add(logoCondor); Font font5 = FontFactory.GetFont(FontFactory.HELVETICA, 12); Font font6 = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 12); Font headerFont = FontFactory.GetFont(FontFactory.COURIER_BOLD, 18); Paragraph labelHeader = new Paragraph("VISITOR LIST", headerFont); labelHeader.Alignment = Element.ALIGN_CENTER; labelHeader.SpacingAfter = 20; document.Add(labelHeader); PdfPTable table = new PdfPTable(dt.Columns.Count); float[] widths = new float[] { 4f, 4f, 4f, 4f, 4f, 4f, 4f, 4f, 4f, 4f, 4f, 4f, 4f, 4f, 4f }; table.SetWidths(widths); table.WidthPercentage = 100; PdfPCell cell = new PdfPCell(new Phrase("Visitors")); cell.Colspan = dt.Columns.Count; foreach (DataColumn c in dt.Columns) { String NewName = c.ColumnName; String revisedName = ""; switch (NewName) { case "idVisitor": revisedName = "Visitor's ID"; break; case "firstName": revisedName = "First Name"; break; case "lastName": revisedName = "Last Name"; break; case "gender": revisedName = "Gender"; break; case "unitNumber": revisedName = "Unit Number"; break; case "idDetails": revisedName = "ID Detail"; break; case "visitorRelation": revisedName = "Relation to Owner"; break; case "purposeOfVisit": revisedName = "Purpose Of Visit"; break; case "timeIn": revisedName = "Time In"; break; case "timeOut": revisedName = "Time Out"; break; case "idOwner": revisedName = "Owner's ID"; break; case "idFacilitator": revisedName = "Facilitator's ID"; break; case "ownerLastName": revisedName = "Unit Owner(Last Name)"; break; case "ownerFirstName": revisedName = "Unit Owner(First Name)"; break; case "facilitatorLastName": revisedName = "Facilitator(Last Name)"; break; default: break; } PdfPCell labeledCell = new PdfPCell(new Phrase(revisedName, font6)); labeledCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER; labeledCell.BackgroundColor = new BaseColor(35, 197, 227); labeledCell.Padding = 4; table.AddCell(labeledCell); //table.AddCell(new Phrase(c.ColumnName, font5)); } foreach (DataRow r in dt.Rows) { if (dt.Rows.Count > 0) { table.AddCell(new Phrase(r[0].ToString(), font5)); table.AddCell(new Phrase(r[1].ToString(), font5)); cell.BackgroundColor = BaseColor.LIGHT_GRAY; table.AddCell(new Phrase(r[2].ToString(), font5)); table.AddCell(new Phrase(r[3].ToString(), font5)); cell.BackgroundColor = BaseColor.LIGHT_GRAY; table.AddCell(new Phrase(r[4].ToString(), font5)); table.AddCell(new Phrase(r[5].ToString(), font5)); cell.BackgroundColor = BaseColor.LIGHT_GRAY; table.AddCell(new Phrase(r[6].ToString(), font5)); table.AddCell(new Phrase(r[7].ToString(), font5)); cell.BackgroundColor = BaseColor.LIGHT_GRAY; table.AddCell(new Phrase(r[8].ToString(), font5)); table.AddCell(new Phrase(r[9].ToString(), font5)); cell.BackgroundColor = BaseColor.LIGHT_GRAY; table.AddCell(new Phrase(r[10].ToString(), font5)); table.AddCell(new Phrase(r[11].ToString(), font5)); cell.BackgroundColor = BaseColor.LIGHT_GRAY; table.AddCell(new Phrase(r[12].ToString(), font5)); table.AddCell(new Phrase(r[13].ToString(), font5)); cell.BackgroundColor = BaseColor.LIGHT_GRAY; table.AddCell(new Phrase(r[14].ToString(), font5)); cell.BackgroundColor = BaseColor.LIGHT_GRAY; } } document.Add(table); document.Close(); }
/// <summary> /// This function prints the invoice in pdf. /// </summary> /// <param name="_name">This parameter is customer's name.</param> /// <param name="_phoneNumber">This parameter is customer's phone number.</param> /// <param name="_adress">This parameter is customer's addres.</param> /// <param name="_paymentType">This parameter is Customer's payment type.</param> /// <param name="_delivery">This parameter is shipping cost.</param> /// <param name="_taxex">This parameter is tax.</param> /// <param name="_totalCost">This parameter is the total cost.</param> public void Document(string _name, string _phoneNumber, string _adress, string _paymentType, string _subtotal, string _delivery, string _taxex, string _totalCost) { try { NumberFormatInfo provider = new NumberFormatInfo(); provider.NumberDecimalSeparator = "."; iTextSharp.text.Document pdfDoc = new iTextSharp.text.Document(PageSize.A4, 40f, 40f, 80f, 80f); PdfWriter.GetInstance(pdfDoc, new FileStream("InvoicePDF.pdf", FileMode.Create)); pdfDoc.Open(); pdfDoc.AddCreator("Dream Book Store"); pdfDoc.AddCreationDate(); pdfDoc.AddAuthor("Admin"); pdfDoc.AddHeader("Dream Book Store", "Involce"); pdfDoc.AddTitle("Dream Book Store"); Paragraph spacer = new Paragraph("") { SpacingBefore = 30f, SpacingAfter = 30f }; string[] headers = new string[5]; headers[0] = "ID"; headers[1] = "Product Name"; headers[2] = "Quantity"; headers[3] = "Price"; headers[4] = "Total Price"; var logo = iTextSharp.text.Image.GetInstance(Resources.invoice, Resources.invoice.RawFormat); logo.ScalePercent(21f); logo.SetAbsolutePosition(pdfDoc.Left, pdfDoc.Top - 30); pdfDoc.Add(logo); var timeTable = new PdfPTable(new[] { .75f }) { HorizontalAlignment = 2, WidthPercentage = 40, DefaultCell = { MinimumHeight = 12f, } }; timeTable.AddCell("Date"); timeTable.AddCell(DateTime.Now.ToString()); pdfDoc.Add(timeTable); pdfDoc.Add(spacer); Paragraph elements1 = new Paragraph("Bill to :" + Environment.NewLine + "Dream Book Store" + Environment.NewLine + "Root" + Environment.NewLine + "Eskisehir Osmangazi University " + Environment.NewLine + "Computer Engineering Department " + Environment.NewLine + "0222 222 01 01" + Environment.NewLine + "*****@*****.**" + Environment.NewLine); Paragraph elements2 = new Paragraph("Ship to :" + Environment.NewLine + "Customer ID: " + MainWindow.cart.CustomerId1 + Environment.NewLine + _name + Environment.NewLine + _adress + Environment.NewLine + _phoneNumber + Environment.NewLine + _paymentType); elements1.Alignment = Element.ALIGN_LEFT; elements2.Alignment = Element.ALIGN_RIGHT; pdfDoc.Add(elements1); pdfDoc.Add(elements2); pdfDoc.Add(spacer); PdfPTable table = new PdfPTable(new[] { .75f, 2.5f, 1f, 1f, 1.5f }) { HorizontalAlignment = 1, WidthPercentage = 75, DefaultCell = { MinimumHeight = 22f, } }; for (int i = 0; i < headers.Length; i++) { PdfPCell cell = new PdfPCell(new PdfPCell()); cell.AddElement(new Chunk(headers[i])); table.AddCell(cell); } for (int i = 0; i < ShoppingCart.ItemsToPurchase.Count; i++) { double TotalPrice = Convert.ToDouble((ShoppingCart.ItemsToPurchase[i].Product.Price), provider) * ShoppingCart.ItemsToPurchase[i].Quantity; table.AddCell(ShoppingCart.ItemsToPurchase[i].Product.Id); table.AddCell(ShoppingCart.ItemsToPurchase[i].Product.Name); table.AddCell(ShoppingCart.ItemsToPurchase[i].Quantity.ToString()); table.AddCell(ShoppingCart.ItemsToPurchase[i].Product.Price); table.AddCell(TotalPrice.ToString()); } pdfDoc.Add(table); Paragraph elements3 = new Paragraph("Subtotal :" + _subtotal + Environment.NewLine + "Delivery :" + _delivery + Environment.NewLine + "Taxex :" + _taxex + Environment.NewLine + "-----------------------" + Environment.NewLine + "Total Cost =" + _totalCost); elements3.Alignment = Element.ALIGN_RIGHT; pdfDoc.Add(elements3); pdfDoc.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
protected void Page_Load(object sender, EventArgs e) { iTextSharp.text.pdf.BarcodeQRCode qrcode = new BarcodeQRCode("testing", 50, 50, null); iTextSharp.text.Image img1 = qrcode.GetImage(); Document doc = new Document(); try { PdfWriter.GetInstance(doc, new FileStream(Server.MapPath("css") + "/Images.pdf", FileMode.Create)); doc.Open(); doc.Add(new Paragraph("GIF")); doc.Add(img1); MemoryStream ms = new MemoryStream(img1.OriginalData); System.Drawing.Image returnImage = System.Drawing.Image.FromStream(ms); // img = returnImage.Save(new Stream(), System.Drawing.Imaging.ImageFormat.Jpeg); } catch (Exception ex) { } finally { doc.Close(); } }