private void btnCreateReport_Click(object sender, EventArgs e) { // _______________________________________________________1_______________________________________________________ // Setting pagetype, margins and encryption iTextSharp.text.Rectangle pageType = iTextSharp.text.PageSize.A4; float marginLeft = 72; float marginRight = 36; float marginTop = 60; float marginBottom = 50; String reportName = "Test.pdf"; Document report = new Document(pageType, marginLeft, marginRight, marginTop, marginBottom); PdfWriter writer = PdfWriter.GetInstance(report, new FileStream(reportName, FileMode.Create)); //writer.SetEncryption(PdfWriter.STRENGTH40BITS, "Good", "Bad", PdfWriter.ALLOW_COPY); report.Open(); // _______________________________________________________2_______________________________________________________ // Setting Document properties(Meta data) // 1. Title // 2. Subject // 3. Keywords // 4. Creator // 5. Author // 6. Header report.AddTitle("Employee Details Report"); report.AddSubject("This file is generated for administrative use only"); report.AddKeywords("Civil Security Department, Employee Management System, Version 1.0.0, Report Generator"); report.AddCreator("Ozious Technologies"); report.AddAuthor("Eranga Heshan"); report.AddHeader("Owner", "Civil Security Department"); // _______________________________________________________3_______________________________________________________ // Setup the font factory /* int totalFonts = FontFactory.RegisterDirectory("C:\\WINDOWS\\Fonts"); StringBuilder sb = new StringBuilder(); foreach (string fontname in FontFactory.RegisteredFonts) { sb.Append(fontname + "\n"); } report.Add(new Paragraph("All Fonts:\n" + sb.ToString())); */ iTextSharp.text.Font fontHeader_1 = FontFactory.GetFont("Calibri", 30, iTextSharp.text.Font.BOLD, new iTextSharp.text.BaseColor(0, 0, 0)); iTextSharp.text.Font fontHeader_2 = FontFactory.GetFont("Calibri", 15, iTextSharp.text.Font.BOLD, new iTextSharp.text.BaseColor(125, 125, 125)); // _______________________________________________________x_______________________________________________________ // Create header PdfContentByte cb = writer.DirectContent; cb.MoveTo(marginLeft, marginTop); cb.LineTo(500, marginTop); cb.Stroke(); Paragraph paraHeader_1 = new Paragraph("Civil Security Department", fontHeader_1); paraHeader_1.Alignment = Element.ALIGN_CENTER; paraHeader_1.SpacingAfter = 0f; report.Add(paraHeader_1); Paragraph paraHeader_2 = new Paragraph("Employee Detailed Report", fontHeader_2); paraHeader_2.Alignment = Element.ALIGN_CENTER; paraHeader_2.SpacingAfter = 10f; report.Add(paraHeader_2); // _______________________________________________________x_______________________________________________________ // Adding employee image iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(imgEmployee.ImageLocation); img.ScaleToFit(100f, 100f); img.Border = iTextSharp.text.Rectangle.BOX; img.BorderColor = iTextSharp.text.BaseColor.BLACK; img.BorderWidth = 5f; img.Alignment = iTextSharp.text.Image.TEXTWRAP | iTextSharp.text.Image.ALIGN_RIGHT | iTextSharp.text.Image.ALIGN_TOP; img.IndentationLeft = 50f; img.SpacingAfter = 20f; img.SpacingBefore = 20f; report.Add(img); Paragraph para1 = new Paragraph("Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... "); para1.Alignment = Element.ALIGN_JUSTIFIED; report.Add(para1); report.Close(); this.Close(); }
/// <summary> /// 读取或创建Pdf文档并打开写入文件流 /// </summary> /// <param name="fileName"></param> /// <param name="folderPath"></param> public Document GetOrCreatePDF(string fileName, string folderPath) { string filePath = folderPath + fileName; FileStream fs = null; if (!File.Exists(filePath)) { fs = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None); } else { fs = new FileStream(filePath, FileMode.Append, FileAccess.Write, FileShare.None); } //获取A4纸尺寸 Rectangle rec = new Rectangle(PageSize.A4); Document doc = new Document(rec); //创建一个 iTextSharp.text.pdf.PdfWriter 对象: 它有助于把Document书写到特定的FileStream: PdfWriter writer = PdfWriter.GetInstance(doc, fs); doc.AddTitle(fileName.Remove(fileName.LastIndexOf('.'))); doc.AddSubject(fileName.Remove(fileName.LastIndexOf('.'))); doc.AddKeywords("Metadata, iTextSharp 5.4.4, Chapter 1, Tutorial"); doc.AddCreator("MCS"); doc.AddAuthor("Chingy"); doc.AddHeader("Nothing", "No Header"); //打开 Document: doc.Open(); ////关闭 Document: //doc.Close(); return doc; }
// From <ClickButt> -> PdfConnector PdfCreatora <- PdfCreator(naemBank,Bodytext) // Form <Image> <- PdfConnector -- tworzyć pdf | public Form1() { while (!fileBanksLists.EndOfStream) { InitializeComponent(); 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(nameBank); document.AddLanguage("pl"); document.AddSubject("Payment transaction"); document.AddTitle("Transaction"); document.AddKeywords("OutcomingNumber :" + OutcomingNumber); document.AddKeywords("IncomingNumber :" + IncomingNumber); /// 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(); } } }
//PDF Ayarları public void PdfHazirla() { iTextSharp.text.Document fis = new iTextSharp.text.Document(new iTextSharp.text.Rectangle(300, 600)); iTextSharp.text.Font normalFont = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.COURIER, 10f, iTextSharp.text.Font.NORMAL); iTextSharp.text.Font italikFont = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 10f, iTextSharp.text.Font.ITALIC); iTextSharp.text.Font tahomaFont = iTextSharp.text.FontFactory.GetFont("Tahoma", 10f); PdfWriter.GetInstance(fis, new FileStream("D:e-fatura.pdf", FileMode.Create)); fis.AddAuthor("Yunus Turhan"); fis.AddCreationDate(); fis.AddSubject("Bilgilendirme Maili"); if (fis.IsOpen() == false) { fis.Open(); } fis.Add(new Paragraph(mailicerigi.Text)); fis.Close(); }
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; } }
//Alım Geçmişi Pdf Rapor Butonu private void PdfButton_Click(object sender, EventArgs e) { iTextSharp.text.Document pdfDosya = new iTextSharp.text.Document(); PdfWriter.GetInstance(pdfDosya, new FileStream("D:Rapor.pdf", FileMode.Create)); pdfDosya.Open(); pdfDosya.AddCreator("Swap - Modern Dünyada Tarıma Dair Alışveriş"); pdfDosya.AddAuthor("Kullanıcı"); pdfDosya.AddTitle("SATIN ALMA RAPORU"); SqlCommand komut = new SqlCommand("Select * From AlimKayitTablosu Where Tarih BETWEEN @t1 and @t2 and KullaniciID=" + Login.UserId, baglanti.baglanti()); SqlDataAdapter data = new SqlDataAdapter(komut); data.SelectCommand.Parameters.AddWithValue("@t1", StartDatePicker.Value); data.SelectCommand.Parameters.AddWithValue("@t2", EndDatePicker.Value); SqlDataReader oku = komut.ExecuteReader(); string id, tarih, miktar, alimtutar, komisyon, metin; metin = "KullaniciID / Tarih / Miktar / AlimTutari / UygulamaKomsiyon \n"; pdfDosya.Add(new Paragraph(metin)); while (oku.Read()) { id = Convert.ToString(oku["KullaniciID"]); tarih = Convert.ToString(oku["Tarih"]); miktar = Convert.ToString(oku["Miktar"]); alimtutar = Convert.ToString(oku["AlimTutari"]); komisyon = Convert.ToString(oku["UygulamaKomisyonu"]); metin = id + " - " + tarih + " - " + miktar + " - " + alimtutar + " - " + komisyon + "\n"; pdfDosya.Add(new Paragraph(metin)); } pdfDosya.Close(); baglanti.baglanti().Close(); }
static void CreatePDF() { string text = "This is a test case"; if (!string.IsNullOrEmpty(text)) { var pdfFilePath = "./test.pdf"; //simple file write check //using (System.IO.StreamWriter file = //new System.IO.StreamWriter(pdfFilePath, true)) //{ // file.WriteLine("Fourth line"); //} var author = "Dummy author"; var stream = new FileStream(pdfFilePath, FileMode.Create); // step 1 var document = new iTextSharp.text.Document(); // step 2 PdfWriter.GetInstance(document, stream); // step 3 document.AddAuthor(author); document.Open(); // step 4 document.Add(new Paragraph(text)); document.Close(); stream.Dispose(); } }
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 CreatePDF() { System.IO.FileStream fs = new FileStream("GeneratedDocument.pdf", FileMode.Create); iTextSharp.text.Document document = new iTextSharp.text.Document(PageSize.A4, 25, 25, 30, 30); PdfWriter writer = PdfWriter.GetInstance(document, fs); document.AddAuthor("UCV"); document.AddCreator("UCV"); document.AddKeywords("Note"); document.AddSubject("Situatie Scolara"); document.AddTitle("Situatie scolara"); document.Open(); document.Close(); writer.Close(); fs.Close(); }
public void CreatePdf(Project project, Stream writeStream) { var document = new Document(); var writer = PdfWriter.GetInstance(document, writeStream); // landscape document.SetPageSize(PageSize.A4.Rotate()); document.SetMargins(36f, 36f, 36f, 36f); // 0.5 inch margins // metadata document.AddCreator("EstimatorX.com"); document.AddKeywords("estimation"); document.AddAuthor(project.Creator); document.AddSubject(project.Name); document.AddTitle(project.Name); document.Open(); AddName(project, document); AddDescription(project, document); AddAssumptions(project, document); AddFactors(project, document); AddTasks(project, document); AddSummary(project, document); writer.Flush(); document.Close(); }
private void btn_Update_Click(object sender, EventArgs e) { //the library for create a new pdf document iTextSharp.text.Document report = new iTextSharp.text.Document(); //file path of newly created pdf file to save PdfWriter.GetInstance(report, new FileStream(@"C:\Users\Asus\Desktop\UPLOADFILES\" + textboxFileName.Text, FileMode.Create)); //Author name, need for create a new pdf document report.AddAuthor(lbl_Author.Text); //Creation Date, need for create a new pdf document report.AddCreationDate(); //Creator, need for create a new pdf document report.AddCreator(lbl_Creator.Text); //Subject, need for create a new pdf document report.AddSubject(lbl_Subject.Text); //Keywords, need for create a new pdf document report.AddKeywords(lbl_Keyword.Text); if (report.IsOpen() == false) { //open report for create a new pdf document report.Open(); } //Paragraph, need for create a new pdf document report.Add(new Paragraph(rtxt_Paragraph.Text)); //open the connection db.openConnection(); //a command line for update the document SqlCommand query = new SqlCommand("UPDATE Table_DOCUMENT SET file_Path = @fp, u_ID = @uid WHERE file_ID = @fid", db.getConnection()); //add the value in the label to @fp query.Parameters.AddWithValue("@fp", labelFilePath.Text); //add the value in the combobox to @uid query.Parameters.AddWithValue("@uid", comboboxUserID.Text); //add the value in the label to @fid query.Parameters.AddWithValue("@fid", labelFileID.Text); //ecevute the query if (query.ExecuteNonQuery() == 1) { MessageBox.Show("DATA WERE UPDATED", "Message Box", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation); //return the default values labelFilePath.Text = @"C:\Users\Asus\Desktop\UPLOADFILES"; textboxFilePath.Text = ""; labelFileID.Text = ""; lbl_FileName.Text = ""; labelCreationDate.Text = ""; comboboxUserID.Text = " "; rtxt_Paragraph.Text = ""; } else { MessageBox.Show("ERROR", "Message Box", MessageBoxButtons.OKCancel, MessageBoxIcon.Error); } //close the report report.Close(); //close the connection db.closeConnection(); }
private void button4_Click(object sender, EventArgs e) { /*-------------------------------------*/ iTextSharp.text.Document raporum = new iTextSharp.text.Document(); // PDF oluşturması ve konumun belirlenmesi Random r = new Random(); PdfWriter.GetInstance(raporum, new FileStream("C:Raporum" + r.Next() + ".pdf", FileMode.Create)); //PDF yi yazan özelliğine eklenecek raporum.AddAuthor("Selim Silgu"); // PDF Oluşturma Tarihi Ekle raporum.AddCreationDate(); // PDF Oluşturma Tarihi // PDF oluşturan kişi özelliğine yazılacak raporum.AddCreator("Selim Silgu"); if (raporum.IsOpen() == false) { raporum.Open(); } raporum.Add(new Paragraph("Ürün Fiyatı : " + urunFiyat.Text + " TL")); raporum.Add(new Paragraph("Seri Numarası : " + seriNumarasi.Text)); raporum.Add(new Paragraph("Ürün ID : " + urunid.ToString())); raporum.Add(new Paragraph("Ürün Adı : " + urunAdText.Text)); raporum.Add(new Paragraph("Ürün Modeli : " + UrunModel.Text)); raporum.Add(new Paragraph("Islemci Hızı : " + islemciHız.Text)); raporum.Add(new Paragraph("Cache Bellek : " + cache.Text)); raporum.Add(new Paragraph("Islemci Teknolojisi : " + islemciTeknoloji.Text)); raporum.Add(new Paragraph("Islemci Markası : " + islemciMarka.Text)); raporum.Add(new Paragraph("Islemci Hızı : " + islemciHız.Text)); raporum.Add(new Paragraph("Çekirdek Sayısı : " + cekirdekSayisi.Text)); raporum.Add(new Paragraph("RAM Tipi :" + ramTip.Text)); raporum.Add(new Paragraph("RAM Kapasitesi : " + ramKapasite.Text)); raporum.Add(new Paragraph("RAM Markası : " + ramMarka.Text)); raporum.Add(new Paragraph("Disk Türü : " + hddTur.Text)); raporum.Add(new Paragraph("Disk Markası : " + hddMarka.Text)); raporum.Add(new Paragraph("USB : " + usb.Text)); raporum.Add(new Paragraph("Isletim Sistemi : " + isletimSistemi.Text)); raporum.Add(new Paragraph("Ekran Kartı Tipi : " + ekranKartTip.Text)); raporum.Add(new Paragraph("Ekran Kartı Markası : " + ekranMarka.Text)); raporum.Add(new Paragraph("Ekran Kartı Chipset : " + chipset.Text)); raporum.Add(new Paragraph("Ekran Kartı Kapasitesi : " + kapasite.Text)); raporum.Add(new Paragraph("Çözünürlük : " + cozunurluk.Text)); raporum.Add(new Paragraph("Kart Okuyucu : " + kartOkuyucu.Text)); raporum.Add(new Paragraph("Kamera : " + kamera.Text)); raporum.Add(new Paragraph("Garanti Süresi : " + GarantiSuresi.Text)); MessageBox.Show("PDF Dosyanız Oluşmuştur."); raporum.Close(); /*-------------------------------------*/ }
public void pdf(string ad, string soyad, string dosyaNo, string drad, string toplamtuar, DataGridView dgw) { DataTable dtPDF = ToDatatable(); string filetime = DateTime.Now.ToFileTime().ToString(); string path = AppDomain.CurrentDomain.BaseDirectory + dosyaNo + filetime + ".pdf"; BaseFont bf = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1250, BaseFont.EMBEDDED); iTextSharp.text.Font font = new iTextSharp.text.Font(bf, 10, iTextSharp.text.Font.NORMAL); iTextSharp.text.Document rapor = new iTextSharp.text.Document(); PdfWriter.GetInstance(rapor, new FileStream(path, FileMode.Create)); rapor.Open(); rapor.AddAuthor(drad); rapor.AddCreationDate(); PdfPTable Tablo = null; Tablo = new PdfPTable(6); Tablo.WidthPercentage = 100; Tablo.AddCell(new Phrase(dgw.Columns[1].HeaderText, font)); Tablo.AddCell(new Phrase(dgw.Columns[3].HeaderText, font)); Tablo.AddCell(new Phrase(dgw.Columns[4].HeaderText, font)); Tablo.AddCell(new Phrase(dgw.Columns[5].HeaderText, font)); Tablo.AddCell(new Phrase(dgw.Columns[6].HeaderText, font)); Tablo.AddCell(new Phrase(dgw.Columns[7].HeaderText, font)); Tablo.HeaderRows = 1; foreach (DataGridViewRow item in dgw.Rows) { Tablo.AddCell(new Phrase(item.Cells[1].Value.ToString(), font)); Tablo.AddCell(new Phrase(item.Cells[3].Value.ToString(), font)); Tablo.AddCell(new Phrase(item.Cells[4].Value.ToString(), font)); Tablo.AddCell(new Phrase(item.Cells[5].Value.ToString(), font)); Tablo.AddCell(new Phrase(item.Cells[6].Value.ToString(), font)); Tablo.AddCell(new Phrase(item.Cells[7].Value.ToString(), font)); } rapor.Add(new Paragraph("HASTA SEVK ISLEMLERI \n" + ad + " " + soyad, font)); rapor.Add(new Paragraph("\n\n\n")); rapor.Add(Tablo); rapor.Add(new Paragraph("\n\n")); rapor.Add(new Paragraph("Toplam Tutar \t" + toplamtuar + " TL")); rapor.Add(new Paragraph("\n\n")); rapor.Add(new Paragraph("Islemi Yapan Doktor \n Dr. " + drad)); rapor.Close(); Process.Start(path, ".pdf"); }
public void pdfRapor(string veri, DataGridView dgw) { DataTable dtPDF = ToDatatable(); string filetime = DateTime.Now.ToFileTime().ToString(); string path = AppDomain.CurrentDomain.BaseDirectory + filetime + ".pdf"; BaseFont bf = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1250, BaseFont.EMBEDDED); iTextSharp.text.Font font = new iTextSharp.text.Font(bf, 10, iTextSharp.text.Font.NORMAL); iTextSharp.text.Document rapor = new iTextSharp.text.Document(); PdfWriter.GetInstance(rapor, new FileStream(path, FileMode.Create)); rapor.Open(); rapor.AddAuthor(""); rapor.AddCreationDate(); PdfPTable Tablo = null; Tablo = new PdfPTable(8); Tablo.WidthPercentage = 100; Tablo.AddCell(new Phrase(dgw.Columns[0].HeaderText, font)); Tablo.AddCell(new Phrase(dgw.Columns[1].HeaderText, font)); Tablo.AddCell(new Phrase(dgw.Columns[2].HeaderText, font)); Tablo.AddCell(new Phrase(dgw.Columns[3].HeaderText, font)); Tablo.AddCell(new Phrase(dgw.Columns[4].HeaderText, font)); Tablo.AddCell(new Phrase(dgw.Columns[5].HeaderText, font)); Tablo.AddCell(new Phrase(dgw.Columns[6].HeaderText, font)); Tablo.AddCell(new Phrase(dgw.Columns[7].HeaderText, font)); Tablo.HeaderRows = 1; foreach (DataGridViewRow item in dgw.Rows) { Tablo.AddCell(new Phrase(item.Cells[0].Value.ToString(), font)); Tablo.AddCell(new Phrase(item.Cells[1].Value.ToString(), font)); Tablo.AddCell(new Phrase(item.Cells[2].Value.ToString(), font)); Tablo.AddCell(new Phrase(item.Cells[3].Value.ToString(), font)); Tablo.AddCell(new Phrase(item.Cells[4].Value.ToString(), font)); Tablo.AddCell(new Phrase(item.Cells[5].Value.ToString(), font)); Tablo.AddCell(new Phrase(item.Cells[6].Value.ToString(), font)); Tablo.AddCell(new Phrase(item.Cells[7].Value.ToString(), font)); } rapor.Add(new Paragraph("----- RAPOR -----\n-----\t" + veri + "\t -----")); rapor.Add(new Paragraph("\n\n")); rapor.Add(Tablo); rapor.Close(); Process.Start(path, ".pdf"); }
protected void GridViewDogalgaz_RowCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName == "DogalgazOdeme") // Tıklanılan sütun (Kolon Adı == DogalgazOdeme ise) { int index = Convert.ToInt16(e.CommandArgument); // Seçili satır indexini alır.. TableRow secili = GridViewDogalgaz.Rows[index]; // Seçili Satırı değişkene aldık. String aboneNo = secili.Cells[1].Text; // Seçili satırın abone numarasını aldık. String faturaNo = secili.Cells[2].Text; // Seçili satırın fatura numarasını aldık. yonet.dogalgazFaturaOde(aboneNo, faturaNo); // Ödeme işlemi metodunu çağırdık... Response.Write("Ödeme Yapıldı..."); // Mesaj verme /*-------------------------------------*/ iTextSharp.text.Document raporum = new iTextSharp.text.Document(); iTextSharp.text.pdf.BaseFont STF_Helvetica_Turkish = iTextSharp.text.pdf.BaseFont.CreateFont("Helvetica", "CP1254", iTextSharp.text.pdf.BaseFont.NOT_EMBEDDED); iTextSharp.text.Font fontNormal = new iTextSharp.text.Font(STF_Helvetica_Turkish, 12, iTextSharp.text.Font.NORMAL); // PDF oluşturması ve konumun belirlenmesi Random r = new Random(); PdfWriter.GetInstance(raporum, new FileStream("C:\\Users\\süleyman\\Desktop\\E-Fatura" + r.Next() + ".pdf", FileMode.Create)); //PDF yi yazan özelliğine eklenecek raporum.AddAuthor("Tüm Abone Listesi"); // PDF Oluşturma Tarihi Ekle raporum.AddCreationDate(); // PDF Oluşturma Tarihi // PDF oluşturan kişi özelliğine yazılacak raporum.AddCreator("Aboneler"); if (raporum.IsOpen() == false) { raporum.Open(); } raporum.Add(new Paragraph("ABONE LISTESI")); raporum.Add(new Paragraph("__________________________________________________")); raporum.Add(new Paragraph("Abone Numarasi : " + secili.Cells[0].Text)); raporum.Add(new Paragraph("Fatura Numarası : " + secili.Cells[1].Text)); raporum.Add(new Paragraph("Fatura Bedeli : " + secili.Cells[2].Text)); raporum.Add(new Paragraph("Fatura Tarihi : " + secili.Cells[3].Text)); raporum.Add(new Paragraph("Son Ödeme Tarihi : " + secili.Cells[4].Text)); raporum.Add(new Paragraph("Odeme Durumu : " + "Ödenmistir")); Response.Write("PDF Dosyanız Oluşmuştur."); raporum.Close(); Response.Redirect("AboneDogalgaz.aspx"); // Yönlendirme... /*-------------------------------------*/ } }
protected void ManagerPDF_Click(object sender, EventArgs e) { Response.ContentType = "application/pdf"; Response.AddHeader("content-disposition", "attachment;filename=LookupManagers.pdf"); Response.Cache.SetCacheability(HttpCacheability.NoCache); iTextSharp.text.Document managerListDoc = new iTextSharp.text.Document(PageSize.A4, 10f, 10f, 10f, 10f); managerListDoc.AddTitle("List of Managers"); managerListDoc.AddAuthor("Leban Mohamed"); managerListDoc.AddLanguage("English"); ExportPDF(ManagerGrid, managerListDoc); }
protected void PDFOrganization_Click(object sender, EventArgs e) { Response.ContentType = "application/pdf"; Response.AddHeader("content-disposition", "attachment;filename=LookupOrganization.pdf"); Response.Cache.SetCacheability(HttpCacheability.NoCache); iTextSharp.text.Document orgListDoc = new iTextSharp.text.Document(PageSize.A4, 10f, 10f, 10f, 10f); orgListDoc.AddTitle("List of Registered Oranizations"); orgListDoc.AddAuthor("Leban Mohamed"); orgListDoc.AddLanguage("English"); ExportPDF(OrganizationGrid, orgListDoc); }
protected override void WriteDocument(object sender, DoWorkEventArgs e) { BackgroundWorker worker = sender as BackgroundWorker; if (File.Exists(FilePath)) throw new Pdf2KTException("File already exists."); Document document = null; PdfWriter writer = null; while(Converter.MoveNext()) { if (worker.CancellationPending == true) { e.Cancel = true; break; } BitmapEncoder encoder = BitmapProcessor.GetBitmapEncoder(); BitmapSource processed = BitmapProcessor.Convert(Converter.Current); if (document == null) { document = new Document(new Rectangle(processed.PixelWidth, processed.PixelHeight)); writer = PdfWriter.GetInstance(document, new FileStream(FilePath, FileMode.Create)); document.Open(); document.AddTitle(Converter.Document.Title); document.AddAuthor(Converter.Document.Author); document.AddCreationDate(); document.AddCreator("Pdf2KT"); } document.NewPage(); using (MemoryStream ms = new MemoryStream()) { encoder.Frames.Add(BitmapFrame.Create(processed)); encoder.Save(ms); ms.Position = 0; Image pdfpage = Image.GetInstance(ms); pdfpage.SetAbsolutePosition(0, 0); document.Add(pdfpage); } worker.ReportProgress((int)((Converter.CurrentProcessedPageNumber * 1f) / Converter.PageCount * 100)); } document.Close(); }
public void SetDocumentProperties(Models.Document documentTemplate) { if (documentTemplate.Author != null) { _itextDocument.AddAuthor(documentTemplate.Author); } if (documentTemplate.Title != null) { _itextDocument.AddTitle(documentTemplate.Title); } if (documentTemplate.Subject != null) { _itextDocument.AddSubject(documentTemplate.Subject); } }
protected override void InitiateDocument(LnParameters lnParam, string language) { this.lnParameters = lnParam; this.currentLanguage = language; pdf = new PdfDocument(PageSize.A4); foreach (string author in lnParam.authors) { pdf.AddAuthor(author); } pdf.AddCreationDate(); pdf.AddLanguage(language); pdf.AddTitle(DocumentTitle); pdf.AddCreator(Globale.PUBLISHER); pdfChapters = new List <Chapter>(); }
public void SendToPDF(string filename, clsFont jfont) { //New document, 8.5"x11" in landscape orientation. iTextSharp.text.Document doc = new iTextSharp.text.Document(PageSize.LETTER.Rotate()); //add metadata doc.AddTitle("Font preview for font " + jfont.SelectedFontName()); doc.AddSubject("font family " + jfont.SelectedFontName()); doc.AddAuthor("JLION.COM jFONT font preview utility"); doc.AddCreationDate(); //create a pdfwriter iTextSharp.text.pdf.PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(filename, FileMode.Create)); //trap events PDFPageEvent pdfevent = new PDFPageEvent(); writer.PageEvent = pdfevent; //create the doc doc.Open(); doc.SetMargins(.75f * 72, .75f * 72, 0, 0); for (int currentPage = 0; currentPage < jfont.CountOfPages(); currentPage++) { //convert image to a pdf image for inclusion in the doc System.Drawing.Image jfontimage = jfont.MakeCharList(currentPage); //System.Drawing.Image jfontimage = jfont.MakeCharacterSample(); iTextSharp.text.Image convertedimage = iTextSharp.text.Image.GetInstance(jfontimage, System.Drawing.Imaging.ImageFormat.Bmp); //determine size to scale to. PDF is 72 dpi, so 1 point is 1/72. System.Drawing.Rectangle PDFImageSize = jfont.ImageSize(72); convertedimage.ScaleAbsolute(PDFImageSize.Width, PDFImageSize.Height); //Add some blank space at the top of the document doc.Add(new Paragraph("Font: " + jfont.SelectedFontName())); doc.Add(new Paragraph("Style: " + jfont.SelectedFontStyle())); doc.Add(new Paragraph("")); doc.Add(new Paragraph("")); doc.Add(convertedimage); doc.NewPage(); } doc.Close(); }
protected void Button2_Click(object sender, EventArgs e) { /*-------------------------------------*/ iTextSharp.text.Document raporum = new iTextSharp.text.Document(); iTextSharp.text.pdf.BaseFont STF_Helvetica_Turkish = iTextSharp.text.pdf.BaseFont.CreateFont("Helvetica", "CP1254", iTextSharp.text.pdf.BaseFont.NOT_EMBEDDED); iTextSharp.text.Font fontNormal = new iTextSharp.text.Font(STF_Helvetica_Turkish, 12, iTextSharp.text.Font.NORMAL); // PDF oluşturması ve konumun belirlenmesi Random r = new Random(); PdfWriter.GetInstance(raporum, new FileStream("C:\\Users\\süleyman\\Desktop\\E-Fatura" + r.Next() + ".pdf", FileMode.Create)); //PDF yi yazan özelliğine eklenecek raporum.AddAuthor("Tüm Abone Listesi"); // PDF Oluşturma Tarihi Ekle raporum.AddCreationDate(); // PDF Oluşturma Tarihi // PDF oluşturan kişi özelliğine yazılacak raporum.AddCreator("Aboneler"); if (raporum.IsOpen() == false) { raporum.Open(); } yonet.TumAboneler(); raporum.Add(new Paragraph("ABONE LISTESI")); while (yonet.dr.Read()) { raporum.Add(new Paragraph("__________________________________________________")); raporum.Add(new Paragraph("Abone Numarasi : " + yonet.dr["ABONENO"].ToString())); raporum.Add(new Paragraph("TC Kimlik Numarasi : " + yonet.dr["TCKIMLIKNO"].ToString())); raporum.Add(new Paragraph("Abone Ad Soyad : " + yonet.dr["ADSOYAD"].ToString())); raporum.Add(new Paragraph("Abone Dogum Tarihi : " + yonet.dr["DOGTAR"].ToString())); raporum.Add(new Paragraph("Abone Telefon : " + yonet.dr["TEL"].ToString())); raporum.Add(new Paragraph("Abone Adres : " + yonet.dr["ADRES"].ToString())); raporum.Add(new Paragraph("Abone Cinsiyet : " + yonet.dr["CINSIYET"].ToString())); raporum.Add(new Paragraph("Abone Turu : " + yonet.dr["ABONETURU"].ToString())); } Response.Write("PDF Dosyanız Oluşmuştur."); raporum.Close(); /*-------------------------------------*/ }
public PdfGraphics(Stream stream, int width, int height) { originalWidth = currentWidth = width; originalHeight = currentHeight = height; document = new Document(new Rectangle(width, height), 50, 50, 50, 50); document.AddAuthor(""); document.AddSubject(""); try{ writer = PdfWriter.GetInstance(document, stream); document.Open(); content = writer.DirectContent; template = topTemplate = content.CreateTemplate(width, height); content.AddTemplate(template, 0, 0); } catch (DocumentException de){ throw new IOException(de.Message); } }
public static void CreateDocument(Stream stream, Action<Document> action) { using (var document = new Document(PageSize.A4)) { var writer = PdfWriter.GetInstance(document, stream); document.Open(); document.AddAuthor(Author); document.AddCreator(DocumentCreator); document.AddKeywords(DocumentKeywords); document.AddSubject(DocumentSubject); document.AddTitle(DocumentTitle); action.Invoke(document); document.Close(); } }
internal PdfGraphics(string filename, int width, int height) { originalWidth = currentWidth = width; originalHeight = currentHeight = height; document = new Document(new iTextSharp.text.Rectangle(width, height), 50, 50, 50, 50); document.AddAuthor(""); document.AddSubject(""); try{ writer = PdfWriter.GetInstance(document, new FileStream(filename, FileMode.Create)); document.Open(); content = writer.DirectContent; template = topTemplate = content.CreateTemplate(width, height); content.AddTemplate(template, 0, 0); } catch (DocumentException de){ throw new IOException(de.Message); } }
public void Start() { //iTextSharp.text.pdf.BaseFont.AddToResourceSearch(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "iTextAsian.dll")); //iTextSharp.text.pdf.BaseFont.AddToResourceSearch(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "iTextAsianCmaps.dll")); iTextSharp.text.Rectangle pageSize = new iTextSharp.text.Rectangle(_Report.PageWidthPoints, _Report.PageHeightPoints); document = new iTextSharp.text.Document(pageSize, _Report.LeftMarginPoints, _Report.RightMarginPoints, _Report.TopMarginPoints, _Report.BottomMarginPoints); this.pdfWriter = iTextSharp.text.pdf.PdfWriter.GetInstance(document, tw); document.SetMargins(_Report.LeftMarginPoints, _Report.RightMarginPoints, _Report.TopMarginPoints, _Report.BottomMarginPoints); document.Open(); document.AddAuthor(_Report.Author); document.AddCreationDate(); document.AddCreator(_Report.Author); }
private void pictureBox1_Click(object sender, EventArgs e) { iTextSharp.text.Document raporum = new iTextSharp.text.Document(); PdfWriter.GetInstance(raporum, new FileStream("C:'" + LblHastaAdı.Text + LblRecerteKodu.Text + "'.pdf", FileMode.Create)); raporum.AddAuthor(LblHastane.Text + "/" + LblDoktor.Text); raporum.AddCreationDate(); raporum.AddCreator(LblHastane.Text + "/" + LblDoktor.Text); raporum.AddSubject("Recete" + LblRecerteKodu.Text); raporum.AddKeywords(LblHastaAdı.Text); if (raporum.IsOpen() == false) { raporum.Open(); } raporum.Add(new Paragraph(LblRecete.Text)); pictureBox1.Enabled = false; PdfOku(); }
private void CreatePdf(string filePath) { iTextSharp.text.Document pdfDoc = new iTextSharp.text.Document(); PdfWriter.GetInstance(pdfDoc, new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite)); // For Turkish Characters iTextSharp.text.pdf.BaseFont STF_Helvetica_Turkish = BaseFont.CreateFont("Helvetica", "CP1254", BaseFont.NOT_EMBEDDED); iTextSharp.text.Font fontTitle = new iTextSharp.text.Font(STF_Helvetica_Turkish, 12, iTextSharp.text.Font.NORMAL); pdfDoc.AddAuthor("FirstName Lastname"); pdfDoc.AddCreationDate(); pdfDoc.AddHeader(tbxPdfFileName.Text, tbxSubject.Text); if (pdfDoc.IsOpen() == false) { pdfDoc.Open(); } pdfDoc.Add(new Paragraph(rtbPdfText.Text, fontTitle)); pdfDoc.Close(); }
public void WriteTaskListToUserFile(string path, ObservableCollection <TaskTodo> ListofTasks) { iTextSharp.text.Document doc = new iTextSharp.text.Document(PageSize.A4.Rotate()); PdfWriter.GetInstance(doc, new FileStream(path, FileMode.Create)); doc.Open(); doc.AddHeader("TodoList", " "); foreach (var task in ListofTasks) { doc.Add(new iTextSharp.text.Phrase("Name of Task : " + task.Name + "\n")); doc.Add(new iTextSharp.text.Phrase("Description of Task : " + task.Description + "\n")); doc.Add(new iTextSharp.text.Phrase("Tag of Task : " + task.Tag + "\n")); doc.Add(new iTextSharp.text.Phrase("Priority Level of Task : " + task.Prioriti + "\n")); doc.Add(new iTextSharp.text.Phrase("Due To date : " + task.DueTo.ToString("d") + "\n")); doc.Add(new iTextSharp.text.Phrase("Finished status of Task : " + task.Finished + "\n")); doc.Add(new iTextSharp.text.Phrase("\n")); } doc.AddAuthor("Dudchak A.V."); doc.Close(); }
// --------------------------------------------------------------------------- /** * Creates a PDF document. */ public byte[] CreatePdf() { using (MemoryStream ms = new MemoryStream()) { // step 1 using (Document document = new Document()) { // step 2 PdfWriter.GetInstance(document, ms); // step 3 document.AddTitle("Hello World example"); document.AddAuthor("Bruno Lowagie"); document.AddSubject("This example shows how to add metadata"); document.AddKeywords("Metadata, iText, PDF"); document.AddCreator("My program using iText"); document.Open(); // step 4 document.Add(new Paragraph("Hello World")); } return ms.ToArray(); } }
public void CreateGradesPDF(List <CourseModel> grades) { System.IO.FileStream fs = new FileStream("GeneratedDocument.pdf", FileMode.Create); iTextSharp.text.Document document = new iTextSharp.text.Document(PageSize.A4, 25, 25, 30, 30); PdfWriter writer = PdfWriter.GetInstance(document, fs); document.AddAuthor("UCV"); document.AddCreator("UCV"); document.AddKeywords("Note"); document.AddSubject("Situatie Scolara"); document.AddTitle("Situatie scolara"); //document.Add(new Chunk(new LineSeparator(4f, 100f, BaseColor.GRAY, Element.ALIGN_CENTER, -1))); document.Open(); document.Add(new Paragraph("UCV --- Situatie Scolara")); if (grades.Count == 0) { document.Add(new Paragraph("Nu exista situatie scolara.")); } else { foreach (var grade in grades) { document.Add(new Paragraph(grade.Name + " " + grade.Teacher + " " + grade.Credits)); //document.Add(new Chunk(new LineSeparator(4f, 100f, BaseColor.GRAY, Element.ALIGN_CENTER, -1))); } } document.Close(); writer.Close(); fs.Close(); }
public static MemoryStream GeneratePDF(Teacher teacher, SchoolClass schoolClass, string schoolYear) { Document document = new Document(); MemoryStream stream = new MemoryStream(); PdfWriter writer = PdfWriter.GetInstance(document, stream); writer.CloseStream = false; document.Open(); document.AddCreationDate(); document.AddAuthor("VaKEGrade"); document.AddTitle("Certificate"); foreach (Pupil pupil in teacher.PrimaryClasses.First().Pupils.OrderBy(x => x.LastName).ToList()) { CertificateGenerator.GenerateCertificate(pupil, schoolClass, schoolYear, ref document); } document.Close(); stream.Seek(0, SeekOrigin.Begin); return stream; }
void CreatePdf() { Itext.Document idoc = new Itext.Document(Itext.PageSize.A4); try { if (saveCWFileDialog.ShowDialog() == DialogResult.OK) { var newfilePath = saveCWFileDialog.FileName; PdfWriter.GetInstance(idoc, new FileStream(newfilePath, FileMode.Create)); #region 设置PDF的头信息,一些属性设置,在Document.Open 之前完成 idoc.AddAuthor(""); idoc.AddCreationDate(); idoc.AddCreator(""); idoc.AddSubject(""); idoc.AddTitle(""); idoc.AddKeywords(""); idoc.AddHeader("cw", "export pdf"); #endregion idoc.Open(); //载入字体 idoc.Add(new Itext.Paragraph(editContentBox.Text, new Itext.Font(BaseFontAndSize("")))); idoc.Close(); if (MessageBox.Show("是否打开文件?", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes) { Process.Start(newfilePath); } } } catch (Itext.DocumentException de) { Console.WriteLine(de.Message); Console.ReadKey(); WriteLog.Logging(de.Message); } catch (IOException io) { Console.WriteLine(io.Message); Console.ReadKey(); WriteLog.Logging(io.Message); } catch (Exception err) { WriteLog.Logging(err); } }
void WriteDocument(iTextSharp.text.Document doc, List <KeyValuePair <ISearchAlgorithm <string>, SearchReport <string> > > results, System.Drawing.Image initialGraph) { doc.AddCreationDate(); doc.AddAuthor("GraphSEA"); doc.AddCreator("GraphSEA"); doc.AddHeader("Header", "GraphSEA - Graph search algorithms benchmark report"); WriteHeader(doc); doc.NewPage(); WriteGraph(doc, initialGraph, results[0].Value.Result.Start, results[0].Value.Result.End); doc.NewPage(); WriteResultSummary(doc, results); doc.NewPage(); // algorithms benchmarks foreach (var res in results) { CurrentReport = res.Value; WriteAlgorithmBenchmark(doc, res.Key, res.Value); } WriteTableOfContent(doc); }
public override void Initialize() { // step 1 : creation of document object Rectangle rect = new Rectangle((float)bbox.Width * 1.1f, (float)bbox.Height * 1.1f); rect.BackgroundColor = BaseColor.WHITE; _pdfDocument = new iTextSharp.text.Document(rect); // step 2: // we create a writer that listens to the document // and directs a PDF-stream to a file PdfWriter writer = PdfWriter.GetInstance(_pdfDocument, _stream); // step 3: we open the document _pdfDocument.Open(); // step 4: we add content to the document _pdfDocument.AddCreationDate(); _pdfDocument.AddAuthor(author); _pdfDocument.AddTitle(title); _cb = writer.DirectContent; // initialize cotation PicCotation._globalCotationProperties._arrowLength = bbox.Height / 50.0; }
private void Btnpdfolustur_Click_1(object sender, EventArgs e) { iTextSharp.text.Document pdfdosya = new iTextSharp.text.Document(); //pdf dosyamızı temsil edecek nesnemizi oluşturuyoruz PdfWriter.GetInstance(pdfdosya, new FileStream("C:CSharpPDF.pdf", FileMode.Create)); //pdf dosyamızın yolunu belirledik ve dosyanın açılış biçimi olrarak pdf ayarladık pdfdosya.Open(); //dosyayı aç pdfdosya.AddCreator(txtolusturulan.Text); //oluşturan ismi pdfdosya.AddCreationDate(); //tarih pdfdosya.AddAuthor(txticeriksahibi.Text); //yazarın ismi eklendi pdfdosya.AddHeader(txtustbaslik.Text, "PDF UYGULAMASI OLUŞTUR"); pdfdosya.AddTitle(txtaltbaslik.Text); //başlık ve title eklenmesi Paragraph eklenecekmetin = new Paragraph(txtaciklamametni.Text); pdfdosya.Add(eklenecekmetin); //eklenecek metnimizin dosyaya eklenmesi decimal satir = numaricsatirsayisi.Value; //satir bilgisi decimal sutun = numaricsutunsayisi.Value; //sutun bilgisi iTextSharp.text.Table tablo = new Table((int)sutun, (int)satir); for (int i = 0; i < satir; i++) { for (int j = 0; j < sutun; j++) { Cell hucre = new Cell((i + 1).ToString() + " " + (j + 1).ToString()); hucre.BackgroundColor = iTextSharp.text.Color.RED; tablo.AddCell(hucre, i, j); } } tablo.cellspacing = 5; pdfdosya.Add(tablo); if (txtolusturulan.Text != "") { Uri yol = new Uri(txtolusturulan.Text); iTextSharp.text.Jpeg resim = new iTextSharp.text.Jpeg(yol); resim.ScalePercent((int)numaricsikistirmeorani.Value); pdfdosya.Add(resim); } pdfdosya.Close(); }
public static string CreateFactuur(Factuur factuur) { try { var filename = GenerateFileName(factuur); using (var fs = new FileStream(Path.Combine(FactuurFolder.FullName, filename), FileMode.Create)) { var document = new Document(PageSize.A4, 25, 25, 30, 1); var writer = PdfWriter.GetInstance(document, fs); writer.PageEvent = new FactuurHelper(); // Add meta information to the document document.AddAuthor("Dura - Vanseveren"); document.AddCreator("DuraFact"); document.AddKeywords("Factuur"); document.AddSubject(string.Format("Factuur {0}", factuur.FactuurNummer)); document.AddTitle("Factuur"); // Open the document to enable you to write to the document document.Open(); // Makes it possible to add text to a specific place in the document using // a X & Y placement syntax. var content = writer.DirectContent; // Add a footer template to the document // content.AddTemplate(PdfFooter(content, factuur), 30, 1); // Add a logo to the invoice var img = DuraLogo; img.ScalePercent(80); img.SetAbsolutePosition(40, 650); content.AddImage(img); // First we must activate writing content.BeginText(); // First we write out the header information AddKlantData(factuur, content); WriteText(content, "Factuur", 40, 600, 20, true); AddFactuurData(factuur, content); // You need to call the EndText() method before we can write graphics to the document! content.EndText(); // Separate the header from the rows with a line // Draw a line by setting the line width and position content.SetLineWidth(0f); content.MoveTo(40, 590); content.LineTo(560, 590); content.Stroke(); // Don't forget to call the BeginText() method when done doing graphics! content.BeginText(); // Before we write the lines, it's good to assign a "last position to write" // variable to validate against if we need to make a page break while outputting. // Change it to 510 to write to test a page break; the fourth line on a new page const int lastwriteposition = 150; // Loop thru the table of items and set the linespacing to 12 points. // Note that we use the -= operator, the coordinates goes from the bottom of the page! var topMargin = 570; if (!string.IsNullOrEmpty(factuur.Opmerking)) { WriteText(content, "Opmerking", 40, topMargin, 12, true); topMargin -= 20; foreach (string s in factuur.Opmerking.Split(new string[] { Environment.NewLine }, StringSplitOptions.None)) { WriteText(content, s, 40, topMargin, 10); topMargin -= 16; } topMargin -= 4; } AddItemData(factuur, document, lastwriteposition, content, ref topMargin); // You need to call the EndText() method before we can write graphics to the document! content.EndText(); // Separate the header from the rows with a line // Draw a line by setting the line width and position content.SetLineWidth(0f); content.MoveTo(40, topMargin); content.LineTo(560, topMargin); content.Stroke(); // Don't forget to call the BeginText() method when done doing graphics! content.BeginText(); topMargin -= 15; AddBTWData(factuur, content, topMargin); // End the writing of text content.EndText(); // Close the document, the writer and the filestream! document.Close(); writer.Close(); fs.Close(); return Path.Combine(FactuurFolder.FullName, filename); } } catch { return string.Empty; } }
/// <summary> /// Exporta los datos de un grid a un archivo PDF. /// </summary> /// <param name="gvData">DataGridView donde se encuentra la información a exportar</param> /// <param name="sPath">Ruta donde se guardará el archivo fisico</param> /// <param name="Titulo">Título del documento a exportar</param> public void ExportGrid(DataGridView gvData, String sPath, String Titulo) { //Creating iTextSharp Table from the DataTable data if (gvData.Rows.Count < 1) throw new Exception("No Hay datos para exportar"); PdfPTable pdfTable = new PdfPTable(gvData.ColumnCount); pdfTable.DefaultCell.Padding = 3; pdfTable.WidthPercentage = 100; pdfTable.HorizontalAlignment = Element.ALIGN_LEFT; pdfTable.DefaultCell.BorderWidth = 1; //Adding Header row foreach (DataGridViewColumn column in gvData.Columns) { PdfPCell cell = new PdfPCell(new Phrase(column.HeaderText)); cell.BackgroundColor = new iTextSharp.text.Color(240, 240, 240); pdfTable.AddCell(cell); } //Adding DataRow foreach (DataGridViewRow row in gvData.Rows) { foreach (DataGridViewCell cell in row.Cells) { if (cell.Value.GetType().FullName.Equals("System.DateTime")) pdfTable.AddCell(((DateTime)cell.Value).ToString("dd/MM/yyyy")); else if (cell.Value.GetType().FullName.Equals("System.Decimal") || cell.Value.GetType().FullName.Equals("System.int")) { if (gvData.Columns[cell.ColumnIndex].Name.Equals("NoFactura")) pdfTable.AddCell(((decimal)cell.Value).ToString("#,###")); else if (gvData.Columns[cell.ColumnIndex].Name.Equals("Cantidad")) pdfTable.AddCell(((decimal)cell.Value).ToString("N6")); else pdfTable.AddCell(((decimal)cell.Value).ToString("N2")); } else pdfTable.AddCell(cell.Value.ToString()); } } using (FileStream stream = new FileStream(sPath, FileMode.Create)) { Document pdfDoc = new Document(PageSize.A2, 10f, 10f, 10f, 10f); PdfWriter.GetInstance(pdfDoc, stream); iTextSharp.text.Font _standardFont = new iTextSharp.text.Font(iTextSharp.text.Font.HELVETICA, 10, iTextSharp.text.Font.BOLD, iTextSharp.text.Color.BLACK); pdfDoc.Open(); pdfDoc.AddAuthor("LOS MEROS MEROS"); pdfDoc.AddCreator("LOS MEROS MEROS"); //pdfDoc.AddTitle("Generación de un pdf con itextSharp"); Paragraph paragraph = new Paragraph(); //paragraph.Font(iTextSharp.text.Font.BOLD); paragraph.Add(Titulo); paragraph.Font = _standardFont; paragraph.Alignment = Element.ALIGN_CENTER; pdfDoc.Add(new Paragraph(paragraph)); pdfDoc.Add(Chunk.NEWLINE); pdfDoc.Add(pdfTable); pdfDoc.Close(); stream.Close(); System.Diagnostics.Process proc = new System.Diagnostics.Process(); proc.StartInfo.FileName = sPath; proc.Start(); proc.Close(); } }
//public void GeneratePDF(DataSet _ms) public void GeneratePDF(String EstNum, String IsFinancial) { Whitfieldcore _wc = new Whitfieldcore(); // MemoryStream m = new MemoryStream(); // Document document = new Document(); FileStream MyStream = null; Document document = new Document(PageSize.A4, 50, 50, 50, 50); try { iTextSharp.text.Font[] fonts = new iTextSharp.text.Font[16]; fonts[0] = FontFactory.GetFont(FontFactory.COURIER, 8, iTextSharp.text.Font.NORMAL); fonts[1] = FontFactory.GetFont(FontFactory.COURIER, 8, iTextSharp.text.Font.BOLD); fonts[2] = FontFactory.GetFont(FontFactory.COURIER, 8, iTextSharp.text.Font.ITALIC); fonts[3] = FontFactory.GetFont(FontFactory.COURIER, 8, iTextSharp.text.Font.BOLD | iTextSharp.text.Font.ITALIC); fonts[4] = FontFactory.GetFont(FontFactory.HELVETICA, 8, iTextSharp.text.Font.NORMAL); fonts[5] = FontFactory.GetFont(FontFactory.HELVETICA, 8, iTextSharp.text.Font.BOLD); fonts[6] = FontFactory.GetFont(FontFactory.HELVETICA, 8, iTextSharp.text.Font.ITALIC); fonts[7] = FontFactory.GetFont(FontFactory.HELVETICA, 8, iTextSharp.text.Font.BOLD | iTextSharp.text.Font.ITALIC); fonts[8] = FontFactory.GetFont(FontFactory.TIMES_ROMAN, 10, iTextSharp.text.Font.NORMAL); fonts[9] = FontFactory.GetFont(FontFactory.TIMES_ROMAN, 10, iTextSharp.text.Font.BOLD); fonts[10] = FontFactory.GetFont(FontFactory.TIMES_ROMAN, 10, iTextSharp.text.Font.ITALIC); fonts[11] = FontFactory.GetFont(FontFactory.TIMES_ROMAN, 10, iTextSharp.text.Font.BOLD | iTextSharp.text.Font.ITALIC); fonts[12] = FontFactory.GetFont(FontFactory.SYMBOL, 10, iTextSharp.text.Font.NORMAL); fonts[13] = FontFactory.GetFont(FontFactory.ZAPFDINGBATS, 10, iTextSharp.text.Font.NORMAL); fonts[14] = FontFactory.GetFont(FontFactory.TIMES_ROMAN, 10, iTextSharp.text.Font.BOLD | iTextSharp.text.Font.UNDERLINE, iTextSharp.text.Color.GRAY); fonts[15] = FontFactory.GetFont(FontFactory.TIMES_ROMAN, 10, iTextSharp.text.Font.NORMAL, iTextSharp.text.Color.GRAY); // Response.ContentType = "application/pdf"; // Response.AddHeader("content-disposition", "attachment;filename=Proposal_Document.pdf"); //<Current Date> - <Project Name>, Architectural Millwork - WhitfieldCo //String _filename = DateTime.Now.ToString("MM-dd-yyyy") + "-" + txtprjname + ", Architectural Millwork - WhitfieldCo.pdf" //PdfWriter.GetInstance(document, new FileStream(_filename, FileMode.Create)); //PdfWriter writer = PdfWriter.GetInstance(document, m); //writer.CloseStream = false; IDataReader iReader = _wc.GetProjectInfo(Convert.ToInt32(EstNum)); while (iReader.Read()) { txtprjname = iReader["ProjName"] == DBNull.Value ? "" : iReader["ProjName"].ToString(); lblPrjHeader = iReader["ProjName"] == DBNull.Value ? "" : iReader["ProjName"].ToString(); txtbasebid = iReader["BaseBid"] == DBNull.Value ? "" : iReader["BaseBid"].ToString(); txtfinalbid = iReader["FinalPrice"] == DBNull.Value ? "" : iReader["FinalPrice"].ToString(); txtdesc = iReader["ProjDescr"] == DBNull.Value ? "" : iReader["ProjDescr"].ToString(); txtNotes = iReader["Notes"] == DBNull.Value ? "" : iReader["Notes"].ToString(); txtBidDate = iReader["BidDate"] == DBNull.Value ? "" : iReader["BidDate"].ToString(); txtEditStartTime = iReader["BidTime"] == DBNull.Value ? "" : iReader["BidTime"].ToString(); txtARDt = iReader["AwardDur"] == DBNull.Value ? "" : iReader["AwardDur"].ToString(); txtawardDate = iReader["AwardDate"] == DBNull.Value ? "" : iReader["AwardDate"].ToString(); txtConstStdate = iReader["ConstrStart"] == DBNull.Value ? "" : iReader["ConstrStart"].ToString(); txtConstDuration = iReader["ConstrDur"] == DBNull.Value ? "" : iReader["ConstrDur"].ToString(); txtConstEndDate = iReader["ConstrCompl"] == DBNull.Value ? DateTime.Now.ToString() : iReader["ConstrCompl"].ToString(); //Adding New Fields txtfabEndDate = iReader["fab_end"] == DBNull.Value ? "" : iReader["fab_end"].ToString(); txtfabStartdate = iReader["fab_start"] == DBNull.Value ? "" : iReader["fab_start"].ToString(); txtfabdurationt = iReader["fab_duration"] == DBNull.Value ? "" : iReader["fab_duration"].ToString(); txtStreet = iReader["prj_street"] == DBNull.Value ? "" : iReader["prj_street"].ToString(); txtCity = iReader["prj_city"] == DBNull.Value ? "" : iReader["prj_city"].ToString(); txtState = iReader["prj_state"] == DBNull.Value ? "" : iReader["prj_state"].ToString(); txtzip = iReader["prj_zip"] == DBNull.Value ? "" : iReader["prj_zip"].ToString(); //New Fields Ends txtrealprjNumbert = iReader["Real_proj_Number"] == DBNull.Value ? "" : iReader["Real_proj_Number"].ToString(); prjArch = iReader["Architect"] == DBNull.Value ? "" : iReader["Architect"].ToString(); prjEsti = iReader["loginid"] == DBNull.Value ? "" : iReader["loginid"].ToString(); txtTotCotCost = iReader["Contengency"] == DBNull.Value ? "0" : iReader["Contengency"].ToString(); txtEngRate = iReader["enghourrate"] == DBNull.Value ? "45.00" : iReader["enghourrate"].ToString(); txtFabRate = iReader["fabhourrate"] == DBNull.Value ? "32.00" : iReader["fabhourrate"].ToString(); txtInstRate = iReader["insthourrate"] == DBNull.Value ? "45.00" : iReader["insthourrate"].ToString(); txtMiscRate = iReader["mischourrate"] == DBNull.Value ? "25.00" : iReader["mischourrate"].ToString(); txtOverHeadRate = iReader["overheadrate"] == DBNull.Value ? "24.11" : iReader["overheadrate"].ToString(); txtMarkUpPercent = iReader["profit_markup"] == DBNull.Value ? "15.00" : iReader["profit_markup"].ToString(); txtDrawingDate = iReader["drawingdate"] == DBNull.Value ? "" : iReader["drawingdate"].ToString(); txtTypeOfWork = iReader["typeofwork"] == DBNull.Value ? "" : iReader["typeofwork"].ToString(); } Chunk chunkHeading; if (txtprjname.Length >= 30) { chunkHeading = new Chunk(txtprjname + " ", fonts[15]); } else { chunkHeading = new Chunk(txtprjname + " ", fonts[15]); } String _modetype = IsFinancial == "Y" ? "Proposal" : "Scope"; Int32 _document_rev_number = GenerateseqNumberforDocs(Convert.ToInt32(EstNum), _modetype); _filename = DateTime.Now.ToString("MM-dd-yyyy") + "-" + txtprjname.Replace("."," ").Trim() + " Architectural Millwork - WhitfieldCo " + _modetype + "-REV 0" + _document_rev_number + ".pdf"; //if (File.Exists(HttpContext.Current.Server.MapPath("~/attachments/") + _filename)) //If the file exists, create new one. //{ // //File.Delete(HttpContext.Current.Server.MapPath("~/attachments/") + _filename); // char[] splitchar = { '.' }; // string[] strArr = null; // strArr = _filename.Split(splitchar); // String _filenmTest = strArr[0]; // int intIndexSubstring = 0; // intIndexSubstring = _filenmTest.IndexOf("-REV#"); // _filename = DateTime.Now.ToString("MM-dd-yyyy") + "-" + txtprjname.Replace(".", " ").Trim() + " Architectural Millwork - WhitfieldCo " + _modetype +"-REV#0" + (Convert.ToInt32(_filenmTest.Substring(intIndexSubstring).Substring(5)) + 1).ToString() + ".pdf"; //} //FileStream MyStream; //MyStream = new FileStream(HttpContext.Current.Server.MapPath("~/attachments/") + _filename, FileMode.Create); //PdfWriter.GetInstance(document, new FileStream(HttpContext.Current.Server.MapPath("~/attachments/") + _filename, FileMode.Create)); //using (StreamWriter sw = File.CreateText(mappath + "patientquery.txt")) using ( MyStream = new FileStream(HttpContext.Current.Server.MapPath("~/attachments/") + _filename, FileMode.Create)) //using (FileStream MyStream = File.Create(HttpContext.Current.Server.MapPath("~/attachments/") + _filename)) //new FileStream(HttpContext.Current.Server.MapPath("~/attachments/") + _filename, FileMode.Create) { PdfWriter.GetInstance(document, MyStream); //attachments document.AddAuthor("Whitfield Corporation"); document.AddSubject("Proposal Generator"); iTextSharp.text.Image img = this.DoGetImageFile(HttpContext.Current.Server.MapPath("~/assets/img/TWC Primary Logo1.JPG")); img.ScalePercent(50); Chunk ck = new Chunk(img, 0, -5); HeaderFooter headerRight = new HeaderFooter(new Phrase(chunkHeading), new Phrase(ck)); document.Header = headerRight; headerRight.Alignment = iTextSharp.text.Rectangle.ALIGN_RIGHT; headerRight.Border = iTextSharp.text.Rectangle.NO_BORDER; // we Add a Footer that will show up on PAGE 1 Phrase phFooter = new Phrase("The Whitfield Corporation, Incorporated ", fonts[15]); phFooter.Add(new Phrase("P.O. Box 0385, Fulton, MD 20759 ", fonts[8])); phFooter.Add(new Phrase("Main: 301 483 0791 Fax: 301 483 0792 ", fonts[8])); phFooter.Add(new Phrase("\nDelivering on Promises", fonts[11])); // HeaderFooter footer = new HeaderFooter(phFooter, false); footer.Border = iTextSharp.text.Rectangle.NO_BORDER; footer.Alignment = iTextSharp.text.Rectangle.ALIGN_CENTER; document.Footer = footer; // step 3: we open the document document.Open(); // we Add a Header that will show up on PAGE 2 DateTime dt = DateTime.Now; //Chapters and Sections int ChapterSequence = 1; document.NewPage(); iTextSharp.text.Font chapterFont = FontFactory.GetFont(FontFactory.TIMES_ROMAN, 16, iTextSharp.text.Font.BOLD, iTextSharp.text.Color.BLACK); iTextSharp.text.Font sectionFont = FontFactory.GetFont(FontFactory.TIMES_ROMAN, 12, iTextSharp.text.Font.NORMAL, iTextSharp.text.Color.BLACK); iTextSharp.text.Font subsectionFont = FontFactory.GetFont(FontFactory.TIMES_ROMAN, 14, iTextSharp.text.Font.BOLD, iTextSharp.text.Color.BLACK); //Chapter 1 Overview Paragraph cTitle = new Paragraph(_modetype, chapterFont); Chapter chapter = new Chapter(cTitle, ChapterSequence); Paragraph ChapterDate = new Paragraph(dt.ToString("\nMMMM dd, yyyy \n\n"), fonts[8]); Paragraph ChapterRef = new Paragraph("RE: " + txtprjname + "\n\n", fonts[8]); Paragraph ChapterText1; if (txtTypeOfWork.Trim() == "Time & Material") { ChapterText1 = new Paragraph("Whitfield proposes to complete the scope of work on a Time & Material basis per the rates included in the Item Breakdown section of this proposal.\n\n", fonts[8]); } else { ChapterText1 = new Paragraph("Whitfield proposes to furnish all materials and perform all labor necessary, including " + txtTypeOfWork + ", to complete the following scope of work as per the Scope of Work breakdown.\n\n", fonts[8]); } String _fnlAmt = ""; String amtWithnoDecimal = ""; if (txtbasebid != "") { string[] txtBaseBidStr = txtbasebid.Split('.'); custom.util.NumberToEnglish num = new custom.util.NumberToEnglish(); _fnlAmt = num.changeCurrencyToWords(txtBaseBidStr[0].Replace("$", "").Trim()); amtWithnoDecimal = txtBaseBidStr[0] + ".00"; } contingency _cont = new contingency(); if (IsFinancial == "Y") { Paragraph ChapterText2; if (txtTypeOfWork.Trim() == "Time & Material") { ChapterText2 = new Paragraph("The Material cost in the amount of " + _fnlAmt + " Dollars and No Cents (" + Convert.ToDecimal(amtWithnoDecimal).ToString("C") + ") includes all profit markup and assumes a construction start on approximately " + Convert.ToDateTime(txtConstStdate).ToString("MMMM dd, yyyy") + " with a completion on or around " + Convert.ToDateTime(txtConstEndDate).ToString("MMMM dd, yyyy") + " .\n\n", fonts[8]); //ChapterText2.Add(new Phrase(new Chunk("This cost is in addition to any Time & Material cost and will be calculated on a unit price basis as included in the Item Breakdown section of this proposal for any time extension beyond the agreed upon construction schedule as included in this proposal.\n\n", FontFactory.GetFont(FontFactory.TIMES_ROMAN, 10, iTextSharp.text.Font.ITALIC | iTextSharp.text.Font.BOLD, iTextSharp.text.Color.BLACK)))); } else { ChapterText2 = new Paragraph("This proposal assumes all of the above work completed by " + Convert.ToDateTime(txtConstEndDate).ToString("MMMM dd, yyyy") + " for the sum of ", FontFactory.GetFont(FontFactory.TIMES_ROMAN, 8, iTextSharp.text.Font.ITALIC | iTextSharp.text.Font.BOLD, iTextSharp.text.Color.BLACK)); ChapterText2.Add(new Phrase(new Chunk(" " + _fnlAmt + "Dollars and No Cents (" + Convert.ToDecimal(amtWithnoDecimal).ToString("C") + ").\n\n", FontFactory.GetFont(FontFactory.TIMES_ROMAN, 8, iTextSharp.text.Font.ITALIC | iTextSharp.text.Font.BOLD, iTextSharp.text.Color.BLACK)))); } chapter.Add(ChapterDate); chapter.Add(ChapterRef); chapter.Add(ChapterText1); chapter.Add(ChapterText2); // Chapter Item Breakdown DataSet dsCont = _cont.FetchProjectItemBreakdown(Convert.ToInt32(EstNum)); if (dsCont.Tables[0].Rows.Count > 0) { Paragraph cBreakDown = new Paragraph("Item Breakdown", chapterFont); chapter.Add(cBreakDown); DataTable myValues; myValues = dsCont.Tables[0]; int icntBreakDown = 1; foreach (DataRow dRow in myValues.Rows) { String _cntlDesc = dRow["Description"] == DBNull.Value ? "" : dRow["Description"].ToString(); String _cntlAmt = dRow["Amount"] == DBNull.Value ? "" : dRow["Amount"].ToString(); Paragraph itemAlternatives = new Paragraph(icntBreakDown.ToString() + ". " + _cntlDesc + "...." + _cntlAmt, fonts[8]); icntBreakDown++; chapter.Add(itemAlternatives); } } // Chapter Alternatives DataSet dsAlternatives = _cont.FetchAlternatives(Convert.ToInt32(EstNum)); if (dsAlternatives.Tables[0].Rows.Count > 0) { Paragraph c = new Paragraph("\nAlternates", fonts[14]); chapter.Add(c); DataTable myValues; myValues = dsAlternatives.Tables[0]; int icntAlternatives = 1; foreach (DataRow dRow in myValues.Rows) { String _altType = dRow["Type"] == DBNull.Value ? "" : dRow["Type"].ToString(); String _cntlDesc = dRow["Description"] == DBNull.Value ? "" : dRow["Description"].ToString(); String _cntlAmt = dRow["Amount"] == DBNull.Value ? "" : dRow["Amount"].ToString(); Paragraph itemAlternatives = new Paragraph(icntAlternatives.ToString() + ". " + _altType + ":" + _cntlDesc + "...." + _cntlAmt, fonts[8]); icntAlternatives++; chapter.Add(itemAlternatives); } } //document.Add(chapter); //Chapters and Sections Declarations End. } //**********************Chapter for Itemized Scope of Work Begins //ChapterSequence++; Paragraph cAssumptions = new Paragraph("\nItemized Scope of Work", chapterFont); chapter.Add(cAssumptions); //Chapter chapterAssumptions = new Chapter(cAssumptions, ChapterSequence); //Paragraph AssumptionsHeading = new Paragraph("Scope of Work\n\n", sectionFont); Paragraph AssumptionsText1 = new Paragraph("Provided hereto is an itemized clarification of the proposed scope. It has been developed and derived from the pricing documents to clarify various assumptions that were considered while compiling this estimate. The General Conditions (listed last) occur throughout the scope of work and apply to “typical applications”, which are subsequently itemized in the corresponding breakdown. " + ".\n\n", fonts[8]); //AssumptionsText1.Add(new Phrase(new Chunk("Proposed price includes " + txtTypeOfWork + ".\n\n", FontFactory.GetFont(FontFactory.TIMES_ROMAN, 10, iTextSharp.text.Font.BOLD, iTextSharp.text.Color.BLACK)))); //chapterAssumptions.Add(AssumptionsHeading); chapter.Add(AssumptionsText1); DataSet dsScope = _wc.GetWorkOrders(EstNum); if (dsScope.Tables[0].Rows.Count > 0) { LoadScopeOfWork(chapter, dsScope, fonts[14]); } Paragraph DrawingsPara1 = new Paragraph("Drawings:", fonts[14]); chapter.Add(DrawingsPara1); Paragraph itemDrawing = new Paragraph(txtprjname + " drawings prepared by " + _wc.GetArchitectName(Convert.ToInt32(prjArch)) + " dated " + txtDrawingDate + ".", fonts[8]); chapter.Add(itemDrawing); DataSet dsSpecs = _cont.FetchAmendmenList(Convert.ToInt32(EstNum)); if (dsSpecs.Tables[0].Rows.Count > 0) { Paragraph DrawingsPara = new Paragraph("\nAdditional Documents:", fonts[14]); chapter.Add(DrawingsPara); DataTable MyTerms; MyTerms = dsSpecs.Tables[0]; int icntamendments = 1; foreach (DataRow dRow in MyTerms.Rows) { String _AmedmentsType = dRow["type"] == DBNull.Value ? "" : dRow["type"].ToString(); String _AmedmentNumber = dRow["amendment_number"] == DBNull.Value ? "" : dRow["amendment_number"].ToString(); String _AmedmentDate = dRow["amendment_date"] == DBNull.Value ? "" : dRow["amendment_date"].ToString(); String amendment_impact = dRow["amendment_impact"] == DBNull.Value ? "" : dRow["amendment_impact"].ToString(); //if (_AmedmentsType == "Amendment") //{ if (amendment_impact.ToLower() == "yes") { Paragraph itemAmendment = new Paragraph(icntamendments.ToString() + ". " + _AmedmentsType + " " + _AmedmentNumber + " dated " + _AmedmentDate + " impacts this scope of work.", fonts[8]); chapter.Add(itemAmendment); //Amendment 001 dated 11/19/2010; This Amendment has no impact to this scope of work. } else { Paragraph itemAmendment = new Paragraph(icntamendments.ToString() + ". " + _AmedmentsType + " " + _AmedmentNumber + " dated " + _AmedmentDate + " does not impact this scope of work.", fonts[8]); chapter.Add(itemAmendment); } //} //else //{ // Paragraph itemAmendment = new Paragraph(icntamendments.ToString() + ". " + _AmedmentsType + " " + _AmedmentNumber + " " + _AmedmentDate, fonts[8]); // chapter.Add(itemAmendment); //} icntamendments++; } } //Qualifications DataSet dsConditions = _wc.GetSpecExcl(Convert.ToInt32(EstNum)); if (dsConditions.Tables[0].Rows.Count > 0) { Paragraph DrawingsPara = new Paragraph("\nQualifications:", fonts[14]); chapter.Add(DrawingsPara); int icnt = 1; DataTable MyConditions; MyConditions = dsConditions.Tables[0]; int tQualid = 0; foreach (DataRow dRow in MyConditions.Rows) { if (Convert.ToInt32(dRow["qual_id"].ToString()) != tQualid) { Paragraph itemheading = new Paragraph(dRow["gName1"].ToString(), fonts[9]); chapter.Add(itemheading); } String _cntlDesc = dRow["description"] == DBNull.Value ? "" : dRow["description"].ToString(); Paragraph itemTerms = new Paragraph(icnt.ToString() + ". " + _cntlDesc, fonts[8]); chapter.Add(itemTerms); tQualid = Convert.ToInt32(dRow["qual_id"].ToString()); icnt++; } } // document.Add(chapter); //************************Chapter for Itemized Scope of Work Ends //*******Chapter Terms Begins******************** //ChapterSequence++; Paragraph cTerms = new Paragraph("\nTerms", fonts[14]); //Chapter chapterTerms = new Chapter(cTerms, ChapterSequence); chapter.Add(cTerms); //Chapter chapterTerms = new Chapter(cTerms, ChapterSequence); DataSet dsTerms = _wc.GetTerms(Convert.ToInt32(EstNum)); if (dsTerms.Tables[0].Rows.Count > 0) { DataTable MyTerms; MyTerms = dsTerms.Tables[0]; int icntTerms = 1; foreach (DataRow dRow in MyTerms.Rows) { String _cntlDesc = dRow["description"] == DBNull.Value ? "" : dRow["description"].ToString(); Paragraph itemTerms = new Paragraph(icntTerms.ToString() + ". " + _cntlDesc, fonts[8]); chapter.Add(itemTerms); icntTerms++; } } Paragraph ChapterFooterText1 = new Paragraph("\nAll or part of the contract amount may be subject to change pending completion delay beyond agreed completion date and/or if changes to quantities are made. All agreements must be in writing prior to execution of any work.\n\n", fonts[8]); ChapterFooterText1.Add(Chunk.NEWLINE); ChapterFooterText1.Add(new Chunk("Respectfully submitted, ", fonts[8])); ChapterFooterText1.Add(new Chunk(" ")); ChapterFooterText1.Add(new Chunk("Accepted By:, ", fonts[8])); ChapterFooterText1.Add(Chunk.NEWLINE); ChapterFooterText1.Add(new Chunk("The Whitfield Co., Inc., ", fonts[8])); ChapterFooterText1.Add(new Chunk(" ")); ChapterFooterText1.Add(new Chunk("________________________ Date_________", fonts[8])); ChapterFooterText1.Add(Chunk.NEWLINE); ChapterFooterText1.Add(new Chunk("Jammie Whitfield, ", fonts[8])); ChapterFooterText1.Add(new Chunk(" ")); ChapterFooterText1.Add(new Chunk("Name, Title", fonts[8])); //Paragraph ChapterFooterText2 = new Paragraph("Respectfully submitted,", fonts[8]); //Paragraph ChapterFooterText3 = new Paragraph("The Whitfield Co., Inc.\n\n", fonts[8]); //Paragraph ChapterFooterText4 = new Paragraph("Jammie Whitfield,", fonts[8]); //Paragraph ChapterFooterText5 = new Paragraph("Estimator", fonts[8]); chapter.Add(ChapterFooterText1); // Paragraph ChapterFooterText2 = new Paragraph("Respectfully submitted,", fonts[8]); // Paragraph ChapterFooterText3 = new Paragraph("The Whitfield Co., Inc.\n\n", fonts[8]); //Paragraph ChapterFooterText4 = new Paragraph("Jammie Whitfield,\n\n", fonts[8]); //Paragraph ChapterFooterText5 = new Paragraph("Accepted By:\n\n", fonts[8]); // Paragraph ChapterFooterText6 = new Paragraph("________________________ Date__________", fonts[8]); // Paragraph ChapterFooterText7 = new Paragraph("Name, Title", fonts[8]); chapter.Add(ChapterFooterText1); // chapter.Add(ChapterFooterText2); // chapter.Add(ChapterFooterText3); // chapter.Add(ChapterFooterText4); // chapter.Add(ChapterFooterText5); document.Add(chapter); //document.Add(new Chunk("Respectfully submitted, ", fonts[8])); //document.Add(new Chunk(" ")); //document.Add(new Chunk("Accepted By:, ", fonts[8])); //document.Add(Chunk.NEWLINE); //document.Add(new Chunk("The Whitfield Co., Inc., ", fonts[8])); //document.Add(new Chunk(" ")); //document.Add(new Chunk("________________________ Date_________", fonts[8])); //document.Add(Chunk.NEWLINE); //document.Add(new Chunk("Jammie Whitfield, ", fonts[8])); //document.Add(new Chunk(" ")); //document.Add(new Chunk("Name, Title", fonts[8])); //*******Chapter Terms Ends******************** document.Close(); //MyStream.Flush(); //MyStream.Close(); //MyStream.Dispose(); //} SetupEmailDocs(Convert.ToInt32(EstNum), _document_rev_number, _filename, _modetype); sendEmail(EstNum, _filename, IsFinancial); } } catch (DocumentException ex) { HttpResponse objResponse = HttpContext.Current.Response; objResponse.Write(ex.Message); } finally { if (MyStream != null) { MyStream.Close(); MyStream.Dispose(); } } //Response.Buffer = true; //Response.Clear(); //Write pdf byes to outputstream //Response.OutputStream.Write(m.GetBuffer(), 0, m.GetBuffer().Length); //Response.OutputStream.Flush(); //Response.End(); }
public void GeneratePDF(DataSet _ms) { String rpt_date = ""; String Daily_notes = ""; String Daily_comments = ""; String Change_order_notes = ""; DataTable dtPDFData = _ms.Tables[0]; foreach (DataRow dRow in dtPDFData.Rows) { rpt_date = dRow["rpt_date"] == DBNull.Value ? "" : dRow["rpt_date"].ToString(); Daily_notes = dRow["Daily_notes"] == DBNull.Value ? "" : dRow["Daily_notes"].ToString(); Daily_comments = dRow["Daily_comments"] == DBNull.Value ? "" : dRow["Daily_comments"].ToString(); Change_order_notes = dRow["Change_order_notes"] == DBNull.Value ? "" : dRow["Change_order_notes"].ToString(); } MemoryStream m = new MemoryStream(); //Document document = new Document(); Document document = new Document(PageSize.A4.Rotate(), 50, 50, 50, 50); try { Response.ContentType = "application/pdf"; Response.AddHeader("content-disposition","attachment;filename=DailyProjectReport.pdf"); //PdfWriter.GetInstance(document, new FileStream("HarishTesting.pdf", FileMode.Create)); PdfWriter writer = PdfWriter.GetInstance(document, m); writer.CloseStream = false; document.AddAuthor("Whitfield Corporation"); document.AddSubject("Daily Production REPORT"); Phrase phrase4 = new Phrase(); phrase4.Add(BuildNewCellSpanRows("Whitfield Corporation Daily Production Report for ", rpt_date)); HeaderFooter headerFooter2 = new HeaderFooter(phrase4, false); headerFooter2.Border = 0; HeaderFooter headerFooter1 = new HeaderFooter(new Phrase("Page: ", FontFactory.GetFont("Times-Roman", 8.0F, 0, new iTextSharp.text.Color(0, 0, 0))), true); headerFooter1.Border = 0; document.Footer = headerFooter1; document.Header = headerFooter2; document.Open(); iTextSharp.text.Table table1 = new iTextSharp.text.Table(2); table1.Padding = 4.0F; table1.Spacing = 0.0F; float[] fArr2 = new float[] { 24.0F, 24.0F }; float[] fArr1 = fArr2; table1.WidthPercentage = 100.0F; Cell cell = new Cell(new Phrase("General Information", FontFactory.GetFont(FontFactory.HELVETICA, 18, iTextSharp.text.Font.BOLD))); cell.HorizontalAlignment = 1; cell.VerticalAlignment = 1; cell.Leading = 8.0F; cell.Colspan = 2; cell.Border = 0; cell.BackgroundColor = new iTextSharp.text.Color(190, 190, 190); table1.AddCell(cell); table1.DefaultCellBorderWidth = 1.0F; table1.DefaultRowspan = 1; table1.DefaultHorizontalAlignment = 0; //table1.AddCell(BuildNewCell("Report Date:", rpt_date.Trim())); //cell = new Cell(BuildNewCell("Daily Notes:", Daily_notes)); //cell.Colspan = 2; //table1.AddCell(cell); cell = new Cell(BuildNewCell("Daily Comments:", Daily_comments)); cell.Colspan = 2; table1.AddCell(cell); //cell = new Cell(BuildNewCell("Change Order Notes:", Change_order_notes)); //cell.Colspan = 2; //table1.AddCell(cell); //table1.AddCell(""); document.Add(table1); document.Add(GenerateCoreReport(rpt_date)); } catch (DocumentException) { throw; } document.Close(); Response.Buffer = true; Response.Clear(); //Write pdf byes to outputstream Response.OutputStream.Write(m.GetBuffer(), 0, m.GetBuffer().Length); Response.OutputStream.Flush(); Response.End(); }
public static string generarPdf(Hashtable htFacturaxion, HttpContext hc) { string pathPdf = htFacturaxion["rutaDocumentoPdf"].ToString(); FileStream fs = new FileStream(pathPdf, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite); try { DAL dal = new DAL(); _ci.NumberFormat.CurrencyDecimalDigits = 2; ElectronicDocument electronicDocument = (ElectronicDocument)htFacturaxion["electronicDocument"]; Data objTimbre = (Data)htFacturaxion["objTimbre"]; timbrar = Convert.ToBoolean(htFacturaxion["timbrar"]); pathPdf = htFacturaxion["rutaDocumentoPdf"].ToString(); Int64 idCfdi = Convert.ToInt64(htFacturaxion["idCfdi"]); #region "Obtenemos los datos del CFDI y Campos Opcionales" StringBuilder sbOpcionalEncabezado = new StringBuilder(); DataTable dtOpcEnc = new DataTable(); StringBuilder sbOpcionalDetalle = new StringBuilder(); DataTable dtOpcDet = new DataTable(); StringBuilder sbDataEmisor = new StringBuilder(); DataTable dtDataEmisor = new DataTable(); sbOpcionalEncabezado. Append("SELECT "). Append("campo3 AS ordenCompra, "). Append("campo7 AS numCliente, "). Append("campo8 AS NombreSuc, "). Append("campo19 AS pedido, "). Append("campo20 AS division, "). Append("campo21 AS efectuarPago, "). Append("campo22 AS direccionPie, "). Append("campo23 AS paraConsultas, "). Append("campo26 AS cantidadLetra, "). Append("campo27 AS zona, "). Append("campo28 AS vencimiento, "). Append("campo29 AS corporateCode, "). Append("campo31 AS hyperion, "). Append("campo32 AS INTERICOM, "). Append("campo30 AS oldCorporateCode, "). Append("campo33 AS referencia, "). Append("campo34 AS fechaRefDoc, "). Append("campo36 AS codigoCorporativo, "). Append("campo37 AS codigoCorporativoAnt, "). Append("campo38 AS clienteNo, "). Append("campo39 AS contacto, "). Append("campo40 AS observaciones, "). Append("campo41 AS NoAp, "). Append("campo42 AS AnoAp, "). Append("' ' AS [ENTREGADO-A-NOMBRE], "). Append("campo10 + ' ' + campo11 + ' ' + "). Append("campo12 AS [ENTREGADO-A-CALLE], "). Append("campo13 AS [ENTREGADO-A-COLONIA], "). Append("campo18 AS [ENTREGADO-A-CP], "). Append("campo15 AS [ENTREGADO-A-MUNIC], "). Append("campo14 AS [ENTREGADO-A-LOCAL], "). Append("campo16 AS [ENTREGADO-A-ESTADO], "). Append("campo17 AS [ENTREGADO-A-PAIS] "). Append("FROM opcionalEncabezado "). Append("WHERE idCFDI = @0 AND ST = 1 "); sbOpcionalDetalle. Append("SELECT "). Append("COALESCE(campo1, '') AS codeLocal, "). Append("COALESCE(campo3, '') AS lote, "). Append("COALESCE(campo4, '') AS cantidad, "). Append("COALESCE(campo5, '') AS expiracion, "). Append("COALESCE(campo6, '') AS taxRate, "). Append("COALESCE(campo7, '') AS taxPaid, "). Append("COALESCE(campo10, '') AS codeOracle, "). Append("COALESCE(campo11, '') AS codeISPC, "). Append("COALESCE(campo12, '') AS codeImpuesto, "). Append("COALESCE(campo13, '') AS centroCostos, "). Append("COALESCE(campo14, '') AS clinico, "). Append("COALESCE(campo15, '') AS proyecto, "). Append("COALESCE(campo16, '') AS cantidadReal, "). Append("COALESCE(campo17, '') AS descuento, "). Append("COALESCE(campo18, '') AS codBarras "). Append("FROM opcionalDetalle "). Append("WHERE idCFDI = @0 "); sbDataEmisor.Append("SELECT nombreSucursal FROM sucursales WHERE idSucursal = @0 "); dtOpcEnc = dal.QueryDT("DS_FE", sbOpcionalEncabezado.ToString(), "F:I:" + idCfdi, hc); dtOpcDet = dal.QueryDT("DS_FE", sbOpcionalDetalle.ToString(), "F:I:" + idCfdi, hc); dtDataEmisor = dal.QueryDT("DS_FE", sbDataEmisor.ToString(), "F:I:" + htFacturaxion["idSucursalEmisor"].ToString(), hc); if (dtOpcDet.Rows.Count == 0) { for (int i = 1; i <= electronicDocument.Data.Conceptos.Count; i++) { dtOpcDet.Rows.Add("", "0.00"); } } #endregion #region "Extraemos los datos del CFDI" Hashtable htDatosCfdi = new Hashtable(); htDatosCfdi.Add("nombreEmisor", electronicDocument.Data.Emisor.Nombre.Value); htDatosCfdi.Add("rfcEmisor", electronicDocument.Data.Emisor.Rfc.Value); htDatosCfdi.Add("nombreReceptor", electronicDocument.Data.Receptor.Nombre.Value); htDatosCfdi.Add("rfcReceptor", electronicDocument.Data.Receptor.Rfc.Value); htDatosCfdi.Add("sucursal", dtDataEmisor.Rows[0]["nombreSucursal"]); htDatosCfdi.Add("serie", electronicDocument.Data.Serie.Value); htDatosCfdi.Add("folio", electronicDocument.Data.Folio.Value); htDatosCfdi.Add("fechaCfdi", electronicDocument.Data.Fecha.Value); htDatosCfdi.Add("UUID", objTimbre.Uuid.Value); #region "Dirección Emisor" StringBuilder sbDirEmisor1 = new StringBuilder(); StringBuilder sbDirEmisor2 = new StringBuilder(); StringBuilder sbDirEmisor3 = new StringBuilder(); if (electronicDocument.Data.Emisor.Domicilio.Calle.Value.Length > 0) { sbDirEmisor1.Append(electronicDocument.Data.Emisor.Domicilio.Calle.Value).Append(" "); } if (electronicDocument.Data.Emisor.Domicilio.NumeroExterior.Value.Length > 0) { sbDirEmisor1.Append(electronicDocument.Data.Emisor.Domicilio.NumeroExterior.Value).Append(", "); } if (electronicDocument.Data.Emisor.Domicilio.NumeroInterior.Value.Length > 0) { sbDirEmisor1.Append(" ").Append(electronicDocument.Data.Emisor.Domicilio.NumeroInterior.Value).Append(", "); } if (electronicDocument.Data.Emisor.Domicilio.Colonia.Value.Length > 0) { sbDirEmisor2.Append(electronicDocument.Data.Emisor.Domicilio.Colonia.Value).Append(", "); } if (electronicDocument.Data.Emisor.Domicilio.Localidad.Value.Length > 0) { sbDirEmisor2.Append(electronicDocument.Data.Emisor.Domicilio.Localidad.Value); } if (electronicDocument.Data.Emisor.Domicilio.Municipio.Value.Length > 0) { sbDirEmisor3.Append(electronicDocument.Data.Emisor.Domicilio.Municipio.Value).Append(", "); } if (electronicDocument.Data.Emisor.Domicilio.Estado.Value.Length > 0) { sbDirEmisor3.Append(electronicDocument.Data.Emisor.Domicilio.Estado.Value).Append(" "); } if (electronicDocument.Data.Emisor.Domicilio.CodigoPostal.Value.Length > 0) { sbDirEmisor3.Append("CP ").Append(electronicDocument.Data.Emisor.Domicilio.CodigoPostal.Value).Append(", "); } sbDirEmisor3.Append(electronicDocument.Data.Emisor.Domicilio.Pais.Value); #endregion #region "Dirección Sucursal Expedido En" StringBuilder sbDirExpedido1 = new StringBuilder(); StringBuilder sbDirExpedido2 = new StringBuilder(); StringBuilder sbDirExpedido3 = new StringBuilder(); if (electronicDocument.Data.Emisor.ExpedidoEn.Calle.Value.Length > 0) { sbDirExpedido1.Append(electronicDocument.Data.Emisor.ExpedidoEn.Calle.Value).Append(" "); } if (electronicDocument.Data.Emisor.ExpedidoEn.NumeroExterior.Value.Length > 0) { sbDirExpedido1.Append(" ").Append(electronicDocument.Data.Emisor.ExpedidoEn.NumeroExterior.Value).Append(", "); } if (electronicDocument.Data.Emisor.ExpedidoEn.NumeroInterior.Value.Length > 0) { sbDirExpedido1.Append(" ").Append(electronicDocument.Data.Emisor.ExpedidoEn.NumeroInterior.Value); } if (electronicDocument.Data.Emisor.ExpedidoEn.Colonia.Value.Length > 0) { sbDirExpedido2.Append(electronicDocument.Data.Emisor.ExpedidoEn.Colonia.Value).Append(", "); } if (electronicDocument.Data.Emisor.ExpedidoEn.Localidad.Value.Length > 0) { sbDirExpedido2.Append(electronicDocument.Data.Emisor.ExpedidoEn.Localidad.Value); } if (electronicDocument.Data.Emisor.ExpedidoEn.Municipio.Value.Length > 0) { sbDirExpedido3.Append(electronicDocument.Data.Emisor.ExpedidoEn.Municipio.Value).Append(", "); } if (electronicDocument.Data.Emisor.ExpedidoEn.Estado.Value.Length > 0) { sbDirExpedido3.Append(electronicDocument.Data.Emisor.ExpedidoEn.Estado.Value).Append(" "); } if (electronicDocument.Data.Emisor.ExpedidoEn.CodigoPostal.Value.Length > 0) { sbDirExpedido3.Append("CP ").Append(electronicDocument.Data.Emisor.ExpedidoEn.CodigoPostal.Value).Append(", "); } sbDirExpedido3.Append(electronicDocument.Data.Emisor.ExpedidoEn.Pais.Value); #endregion #region "Dirección Receptor" StringBuilder sbDirReceptor1 = new StringBuilder(); StringBuilder sbDirReceptor2 = new StringBuilder(); StringBuilder sbDirReceptor3 = new StringBuilder(); if (electronicDocument.Data.Receptor.Domicilio.Calle.Value.Length > 0) { sbDirReceptor1.Append(electronicDocument.Data.Receptor.Domicilio.Calle.Value).Append(" "); } if (electronicDocument.Data.Receptor.Domicilio.NumeroExterior.Value.Length > 0) { sbDirReceptor1.Append(" ").Append(electronicDocument.Data.Receptor.Domicilio.NumeroExterior.Value).Append(" "); } if (electronicDocument.Data.Receptor.Domicilio.NumeroInterior.Value.Length > 0) { sbDirReceptor1.Append(" ").Append(electronicDocument.Data.Receptor.Domicilio.NumeroInterior.Value); } if (electronicDocument.Data.Receptor.Domicilio.Colonia.Value.Length > 0) { sbDirReceptor2.Append(electronicDocument.Data.Receptor.Domicilio.Colonia.Value).Append(", "); } if (electronicDocument.Data.Receptor.Domicilio.Localidad.Value.Length > 0) { sbDirReceptor2.Append(electronicDocument.Data.Receptor.Domicilio.Localidad.Value); } if (electronicDocument.Data.Receptor.Domicilio.Municipio.Value.Length > 0) { sbDirReceptor3.Append(electronicDocument.Data.Receptor.Domicilio.Municipio.Value).Append(", "); } if (electronicDocument.Data.Receptor.Domicilio.Estado.Value.Length > 0) { sbDirReceptor3.Append(electronicDocument.Data.Receptor.Domicilio.Estado.Value).Append(" "); } if (electronicDocument.Data.Receptor.Domicilio.CodigoPostal.Value.Length > 0) { sbDirReceptor3.Append("CP ").Append(electronicDocument.Data.Receptor.Domicilio.CodigoPostal.Value).Append(", "); } sbDirReceptor3.Append(electronicDocument.Data.Receptor.Domicilio.Pais.Value); #endregion htDatosCfdi.Add("direccionEmisor1", sbDirEmisor1.ToString()); htDatosCfdi.Add("direccionEmisor2", sbDirEmisor2.ToString()); htDatosCfdi.Add("direccionEmisor3", sbDirEmisor3.ToString()); htDatosCfdi.Add("direccionExpedido1", sbDirExpedido1.ToString()); htDatosCfdi.Add("direccionExpedido2", sbDirExpedido2.ToString()); htDatosCfdi.Add("direccionExpedido3", sbDirExpedido3.ToString()); htDatosCfdi.Add("direccionReceptor1", sbDirReceptor1.ToString()); htDatosCfdi.Add("direccionReceptor2", sbDirReceptor2.ToString()); htDatosCfdi.Add("direccionReceptor3", sbDirReceptor3.ToString()); #endregion #region "Creamos el Objeto Documento y Tipos de Letra" Document document = new Document(PageSize.LETTER, 15, 15, 15, 40); document.AddAuthor("Facturaxion"); document.AddCreator("r3Take"); document.AddCreationDate(); //FileStream fs = new FileStream(pathPdf, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite); pdfPageEventHandlerPfizer pageEventHandler = new pdfPageEventHandlerPfizer(); PdfWriter writer = PdfWriter.GetInstance(document, fs); writer.SetFullCompression(); writer.ViewerPreferences = PdfWriter.PageModeUseNone; writer.PageEvent = pageEventHandler; writer.SetPdfVersion(PdfWriter.PDF_VERSION_1_7); //document.Open(); HTC = hc; pathIMGLOGO = @"C:\Inetpub\repositorioFacturaxion\imagesFacturaEspecial\PFI730206632\logo-pfizer.jpg"; azul = new Color(13, 142, 244); blanco = new Color(255, 255, 255); Link = new Color(7, 73, 208); gris = new Color(13, 142, 244); grisOX = new Color(74, 74, 74); rojo = new Color(230, 7, 7); lbAzul = new Color(5, 146, 230); EM = BaseFont.CreateFont(@"C:\Windows\Fonts\VERDANA.TTF", BaseFont.WINANSI, BaseFont.NOT_EMBEDDED); f5 = new Font(EM, 5, Font.NORMAL, grisOX); f5B = new Font(EM, 5, Font.BOLD, grisOX); f5BBI = new Font(EM, 5, Font.BOLDITALIC, grisOX); f6 = new Font(EM, 6, Font.NORMAL, grisOX); f6B = new Font(EM, 6, Font.BOLD, grisOX); f6L = new Font(EM, 6, Font.BOLD, Link); f5L = new Font(EM, 5, Font.BOLD, lbAzul); titulo = new Font(EM, 6, Font.BOLD, blanco); folio = new Font(EM, 6, Font.BOLD, rojo); dSaltoLinea = new Chunk("\n\n "); #endregion #region "Generamos el Docuemto" string RFC = string.Empty; RFC = htDatosCfdi["rfcEmisor"].ToString(); switch (RFC) { case "PFI730206632": #region "Docuemto PFI730206632" switch (htDatosCfdi["serie"].ToString()) { case "E": case "G": htDatosCfdi.Add("tipoDoc", "FACTURA"); formatoEGFH(document, electronicDocument, objTimbre, pageEventHandler, dtOpcEnc, dtOpcDet, htDatosCfdi, HTC); break; case "F": case "H": htDatosCfdi.Add("tipoDoc", "NOTA DE CRÉDITO"); formatoEGFH(document, electronicDocument, objTimbre, pageEventHandler, dtOpcEnc, dtOpcDet, htDatosCfdi, HTC); break; case "A": case "C": case "I": case "K": case "M": htDatosCfdi.Add("tipoDoc", "FACTURA"); formatoABCDIJKLM(document, electronicDocument, objTimbre, pageEventHandler, idCfdi, dtOpcEnc, dtOpcDet, htDatosCfdi, HTC); break; case "B": case "D": case "J": case "L": case "N": htDatosCfdi.Add("tipoDoc", "NOTA DE CRÉDITO"); formatoABCDIJKLM(document, electronicDocument, objTimbre, pageEventHandler, idCfdi, dtOpcEnc, dtOpcDet, htDatosCfdi, HTC); break; //case "N": // htDatosCfdi.Add("tipoDoc", "NOTA DE CRÉDITO"); // formatoN(document, pageEventHandler, dtOpcEnc, dtOpcDet, htDatosCfdi, HTC); // break; default: break; } break; #endregion case "P&U960326AG7": htDatosCfdi.Add("tipoDoc", "FACTURA"); PYU960326AG7(document, electronicDocument, objTimbre, pageEventHandler, dtOpcEnc, dtOpcDet, htDatosCfdi, HTC); break; case "PME970204V63": #region "Documento PME970204V63" switch (htDatosCfdi["serie"].ToString()) { case "A": htDatosCfdi.Add("tipoDoc", "FACTURA"); formatoABCDIJKLM(document, electronicDocument, objTimbre, pageEventHandler, idCfdi, dtOpcEnc, dtOpcDet, htDatosCfdi, HTC); break; case "B": htDatosCfdi.Add("tipoDoc", "NOTA DE CRÉDITO"); formatoABCDIJKLM(document, electronicDocument, objTimbre, pageEventHandler, idCfdi, dtOpcEnc, dtOpcDet, htDatosCfdi, HTC); break; } break; #endregion case "SP&040526HD3": break; } #endregion document.Close(); writer.Close(); fs.Close(); string filePdfExt = pathPdf.Replace(_rutaDocs, _rutaDocsExt); string urlPathFilePdf = filePdfExt.Replace(@"\", "/"); //Subimos Archivo al Azure wAzure.azureUpDownLoad(1, pathPdf); return "1#" + urlPathFilePdf; } catch (Exception ex) { fs.Flush(); fs.Close(); File.Delete(pathPdf); return "0#" + ex.Message; } }
public static string GenerateHerinnering(Factuur factuur) { try { var filename = GenerateFileNameHerinnering(factuur); using (var fs = new FileStream(Path.Combine(HerinneringFolder.FullName, filename), FileMode.Create)) { var document = new Document(PageSize.A4, 25, 25, 30, 1); var writer = PdfWriter.GetInstance(document, fs); // Add meta information to the document document.AddAuthor("Dura - Vanseveren"); document.AddCreator("DuraFact"); document.AddKeywords("Herinnering"); document.AddSubject(string.Format("Herinnering voor factuur {0}", factuur.FactuurNummer)); document.AddTitle("Herinnering"); // Open the document to enable you to write to the document document.Open(); // Makes it possible to add text to a specific place in the document using // a X & Y placement syntax. var content = writer.DirectContent; // Add a footer template to the document // content.AddTemplate(PdfFooter(content, factuur), 30, 1); // Add a logo to the invoice var img = DuraLogo; img.ScalePercent(80); img.SetAbsolutePosition(40, 650); content.AddImage(img); // First we must activate writing content.BeginText(); // First we write out the header information AddKlantData(factuur, content); WriteText(content, string.Format("Tielt, {0}", DateTime.Now.ToShortDateString()), 40, 600, 10); WriteText(content, "Herinnering", 40, 550, 20, true); WriteText(content, "Geachte heer/mevrouw", 40, 520, 10); WriteText(content, string.Format("Wij hebben bij u een betalingsachterstand van {0:C} geconstateerd.", factuur.TotaalIncl), 40, 500, 10); WriteText(content, "Dit bedrag heeft betrekking op de onderstaande factuur:", 40, 485, 10); const int aantalMargin = 230, ehprijsMargin = 300, totaalMargin = 460; WriteText(content, "Factuur", 140, 460, 12, true, PdfContentByte.ALIGN_RIGHT); WriteText(content, "Datum", aantalMargin, 460, 12, true, PdfContentByte.ALIGN_RIGHT); WriteText(content, "Bedrag", ehprijsMargin, 460, 12, true, PdfContentByte.ALIGN_RIGHT); WriteText(content, "Betalingskenmerk", totaalMargin, 460, 12, true, PdfContentByte.ALIGN_RIGHT); WriteText(content, factuur.FactuurNummer.ToString(), 140, 440, 10, false, PdfContentByte.ALIGN_RIGHT); WriteText(content, factuur.FacturatieDatum.ToShortDateString(), aantalMargin, 440, 10, false, PdfContentByte.ALIGN_RIGHT); WriteText(content, string.Format("{0:C}", factuur.TotaalIncl), ehprijsMargin, 440, 10, false, PdfContentByte.ALIGN_RIGHT); WriteText(content, factuur.FacturatieDatum.ToShortDateString(), totaalMargin, 440, 10, false, PdfContentByte.ALIGN_RIGHT); WriteText(content, string.Format("Wij verzoeken u nu vriendelijk het bovenstaande bedrag zulks ten bedrage van {0:C} te doen overmaken.", factuur.TotaalIncl), 40, 400, 10); WriteText(content, "Dit kan op rekeningnummer 733-0318587-69 bij KBC of 001-6090654-03 bij BNP Paribas Fortis onder vermelding", 40, 385, 10); WriteText(content, "van uw betalingskenmerk.", 40, 370, 10); WriteText(content, "Wanneer u vragen mocht hebben over deze herinnering, verzoeken wij u zo spoedig mogelijk contact op te nemen", 40, 355, 10); WriteText(content, "op het telefoonnummer (051) 40 34 77.", 40, 340, 10); WriteText(content, "Heeft u inmiddels uw betalingsachterstand voldaan, dan is deze herinnering voor u niet meer van toepassing.", 40, 325, 10); WriteText(content, "Hoogachtend,", 40, 280, 10); WriteText(content, "Filip Vanseveren", 40, 180, 10); // End the writing of text content.EndText(); // Close the document, the writer and the filestream! document.Close(); writer.Close(); fs.Close(); return Path.Combine(HerinneringFolder.FullName, filename); } } catch { return string.Empty; } }
public static byte[] CrearRecibo(string Nombre, string RFC, Dictionary <string, string> conceptos, string direccion, string telefono, float Total, bool leyenda, string Imagen, bool Moneda) { Font font = new Font(Font.FontFamily.HELVETICA, 6, Font.NORMAL); Font sellos = new Font(Font.FontFamily.HELVETICA, 5, Font.NORMAL); Font textBold = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 7); DateTime now = DateTime.Now; iTextSharp.text.Document doc = new iTextSharp.text.Document(iTextSharp.text.PageSize.LETTER); MemoryStream memStream = new MemoryStream(); iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(doc, memStream); doc.AddTitle("Recibo Electronico"); doc.AddCreator("Avenzo Proteccion"); doc.AddAuthor("Cristian Santiago Rosas"); doc.Open(); iTextSharp.text.Image avenzo = iTextSharp.text.Image.GetInstance(Imagen); iTextSharp.text.pdf.PdfPTable Header = new iTextSharp.text.pdf.PdfPTable(12); float[] widths = new float[] { .8f, .8f, .8f, .8f, .8f, .8f, .8f, .8f, .8f, .8f, .8f, .8f }; iTextSharp.text.Rectangle page = doc.PageSize; Header.WidthPercentage = 80; Header.LockedWidth = true; Header.SetWidths(widths); Header.TotalWidth = page.Width - 90; //--------------------------------------------- //-----------CABEZERA DEL DOCUMENTO------------ //--------------------------------------------- iTextSharp.text.pdf.PdfPCell cell = new iTextSharp.text.pdf.PdfPCell();//--Logo cell.AddElement(avenzo); cell.Colspan = 4; cell.Border = BORDER; iTextSharp.text.pdf.PdfPCell cell2 = new iTextSharp.text.pdf.PdfPCell();//--Domicilio Fiscal cell2.AddElement(new iTextSharp.text.Paragraph("AVENZO BUSINESS GROUP S de RL de CV" + "\n" + "ABG1512109U1" + "\nDomicilio Fiscal\n" + "AVENIDA GRANDES LAGOS 19702 6\nFRACC. EL LAGO 22210\nTIJUANA, Baja California Mexico" + "\nTel. 6645266573", new Font(Font.FontFamily.HELVETICA, 7, Font.BOLD))); cell2.Colspan = 4; cell2.Border = BORDER; cell2.HorizontalAlignment = 1; Header.AddCell(cell); Header.AddCell(cell2); iTextSharp.text.pdf.PdfPCell cell51 = new iTextSharp.text.pdf.PdfPCell(); cell51.Phrase = new Phrase("", textBold); cell51.HorizontalAlignment = Element.ALIGN_CENTER; cell51.Colspan = 4; cell51.Border = 0; Header.AddCell(cell51); iTextSharp.text.pdf.PdfPCell salto = new iTextSharp.text.pdf.PdfPCell(); salto.AddElement(new Chunk("\n")); salto.Colspan = 12; salto.Border = BORDER; Header.AddCell(salto); //--------------------------------------------- //------------DATOS CLIENTE------------------- //--------------------------------------------- iTextSharp.text.pdf.PdfPCell cell4 = new iTextSharp.text.pdf.PdfPCell();//--Domicilio Fiscal cell4.Colspan = 1; cell4.Border = BORDER; cell4.PaddingTop = 0; cell4.PaddingBottom = 0; cell4.AddElement(new Paragraph("Cliente:", textBold)); iTextSharp.text.pdf.PdfPCell cell5 = new iTextSharp.text.pdf.PdfPCell();//--Domicilio Fiscal cell5.Colspan = 2; cell5.PaddingTop = 0; cell5.PaddingBottom = 0; cell5.Border = BORDER; cell5.AddElement(new Paragraph(Nombre, font)); iTextSharp.text.pdf.PdfPCell cell6 = new iTextSharp.text.pdf.PdfPCell();//--Domicilio Fiscal cell6.Colspan = 2; cell6.Border = BORDER; cell6.PaddingTop = 0; cell6.PaddingBottom = 0; cell6.AddElement(new Paragraph("", textBold)); iTextSharp.text.pdf.PdfPCell cell7 = new iTextSharp.text.pdf.PdfPCell();//--Domicilio Fiscal cell7.Colspan = 7; cell7.Border = BORDER; cell7.PaddingTop = 0; cell7.PaddingBottom = 0; cell7.AddElement(new Paragraph("", font)); iTextSharp.text.pdf.PdfPCell cell8 = new iTextSharp.text.pdf.PdfPCell();//--Domicilio Fiscal cell8.Colspan = 1; cell8.Border = BORDER; cell8.PaddingTop = 0; cell8.PaddingBottom = 0; cell8.AddElement(new Paragraph("RFC:", textBold)); iTextSharp.text.pdf.PdfPCell cell9 = new iTextSharp.text.pdf.PdfPCell();//--Domicilio Fiscal cell9.Colspan = 2; cell9.Border = BORDER; cell9.PaddingTop = 0; cell9.PaddingBottom = 0; cell9.AddElement(new Paragraph(RFC, font)); iTextSharp.text.pdf.PdfPCell cell10 = new iTextSharp.text.pdf.PdfPCell(); cell10.Colspan = 2; cell10.Border = BORDER; cell10.PaddingBottom = 0; cell10.PaddingTop = 0; cell10.AddElement(new Paragraph("Lugar de Expedición:", textBold)); iTextSharp.text.pdf.PdfPCell cell11 = new iTextSharp.text.pdf.PdfPCell(); cell11.Colspan = 3; cell11.Border = BORDER; cell11.PaddingTop = 0; cell11.PaddingBottom = 0; cell11.AddElement(new Paragraph("TIJUANA, Baja California", font)); iTextSharp.text.pdf.PdfPCell cell12 = new iTextSharp.text.pdf.PdfPCell(); cell12.AddElement(new Paragraph("Fecha de Expedicion:", textBold)); cell12.Colspan = 2; cell12.Border = BORDER; cell12.PaddingBottom = 0; cell12.PaddingTop = 0; iTextSharp.text.pdf.PdfPCell cell13 = new iTextSharp.text.pdf.PdfPCell(); cell13.Colspan = 3; cell13.Border = BORDER; cell13.PaddingTop = 0; cell13.PaddingBottom = 0; DateTime time = DateTime.Now; System.Globalization.CultureInfo ci = new System.Globalization.CultureInfo("es-MX"); cell13.AddElement(new Paragraph(time.ToString("dd", ci) + " de " + time.ToString("MMMM", ci) + " del " + time.ToString("yyyy", ci), font)); //--- iTextSharp.text.pdf.PdfPCell cell14 = new iTextSharp.text.pdf.PdfPCell(); cell14.Colspan = 1; cell14.Rowspan = 2; cell14.PaddingTop = 0; cell14.PaddingBottom = 0; cell14.Border = BORDER; cell14.AddElement(new Paragraph("Direccion:", textBold)); iTextSharp.text.pdf.PdfPCell cell15 = new iTextSharp.text.pdf.PdfPCell(); cell15.Colspan = 2; cell15.Rowspan = 2; cell15.Border = BORDER; cell15.PaddingBottom = 0; cell15.PaddingTop = 0; if (direccion.Split('|').Count() == 1) { cell15.AddElement(new Paragraph(direccion, font)); } else { cell15.AddElement(new Paragraph(direccion.Split('|')[0] + direccion.Split('|')[1] + direccion.Split('|')[2], font)); } iTextSharp.text.pdf.PdfPCell cell16 = new iTextSharp.text.pdf.PdfPCell(); cell16.Colspan = 2; cell16.PaddingTop = 0; cell16.PaddingBottom = 0; cell16.AddElement(new Paragraph("Mes de Pago:", textBold)); cell16.Border = BORDER; iTextSharp.text.pdf.PdfPCell cell17 = new iTextSharp.text.pdf.PdfPCell(); cell17.PaddingBottom = 0; cell17.PaddingTop = 0; cell17.Colspan = 3; cell17.Border = BORDER; cell17.AddElement(new Paragraph("" + time.ToString("MMMM", ci).ToUpper(), font)); iTextSharp.text.pdf.PdfPCell cell18 = new iTextSharp.text.pdf.PdfPCell(); cell18.AddElement(new Paragraph("", textBold)); cell18.Colspan = 2; cell18.Border = BORDER; cell18.PaddingTop = 0; cell18.PaddingBottom = 0; iTextSharp.text.pdf.PdfPCell cell19 = new iTextSharp.text.pdf.PdfPCell(); cell19.Colspan = 2; cell19.Border = BORDER; cell19.PaddingBottom = 0; cell19.PaddingTop = 0; cell19.AddElement(new Paragraph("", font)); iTextSharp.text.pdf.PdfPCell cell20 = new iTextSharp.text.pdf.PdfPCell(); cell20.Colspan = 2; cell20.Border = BORDER; cell20.PaddingTop = 0; cell20.PaddingBottom = 0; cell20.AddElement(new Paragraph("", textBold)); iTextSharp.text.pdf.PdfPCell cell21 = new iTextSharp.text.pdf.PdfPCell(); cell21.Colspan = 3; cell21.Border = BORDER; cell21.PaddingTop = 0; cell21.PaddingBottom = 0; cell21.AddElement(new Paragraph("", font)); iTextSharp.text.pdf.PdfPCell cell22 = new iTextSharp.text.pdf.PdfPCell(); cell22.Colspan = 2; cell22.Border = BORDER; cell22.PaddingTop = 0; cell22.PaddingBottom = 0; cell22.AddElement(new Paragraph("No. Cuenta Pago:", textBold)); iTextSharp.text.pdf.PdfPCell cell23 = new iTextSharp.text.pdf.PdfPCell(); cell23.Colspan = 2; cell23.Border = BORDER; cell23.PaddingTop = 0; cell23.PaddingBottom = 0; cell23.AddElement(new Paragraph("", font)); //---------------------------------------------- //-----------------PRODUCTOS-------------------- //---------------------------------------------- iTextSharp.text.pdf.PdfPCell cell24 = new iTextSharp.text.pdf.PdfPCell(); cell24.Colspan = 1; cell24.AddElement(new Paragraph("Cantidad", textBold)); iTextSharp.text.pdf.PdfPCell cell25 = new iTextSharp.text.pdf.PdfPCell(); cell25.Colspan = 1; cell25.AddElement(new Paragraph("Unidad de Medida", textBold)); iTextSharp.text.pdf.PdfPCell cell26 = new iTextSharp.text.pdf.PdfPCell(); cell26.Colspan = 6; cell26.HorizontalAlignment = Element.ALIGN_CENTER; cell26.VerticalAlignment = Element.ALIGN_CENTER; cell26.AddElement(new Paragraph("Descripcion", textBold)); iTextSharp.text.pdf.PdfPCell cell27 = new iTextSharp.text.pdf.PdfPCell(); cell27.Colspan = 2; cell27.AddElement(new Paragraph("Producto Unitario", textBold)); iTextSharp.text.pdf.PdfPCell cell28 = new iTextSharp.text.pdf.PdfPCell(); cell28.Colspan = 2; cell28.HorizontalAlignment = Element.ALIGN_CENTER; cell28.VerticalAlignment = Element.ALIGN_CENTER; cell28.AddElement(new Paragraph("Importe", textBold)); //----------------------------------------------- iTextSharp.text.pdf.PdfPCell cell29 = new iTextSharp.text.pdf.PdfPCell(); cell29.AddElement(new Paragraph(conceptos["cantidad"], font)); cell29.Colspan = 1; iTextSharp.text.pdf.PdfPCell cell30 = new iTextSharp.text.pdf.PdfPCell(); cell30.AddElement(new Paragraph(conceptos["unidad"], font)); cell30.Colspan = 1; iTextSharp.text.pdf.PdfPCell cell31 = new iTextSharp.text.pdf.PdfPCell(); cell31.AddElement(new Paragraph(conceptos["descripcion"], font)); cell31.Colspan = 6; iTextSharp.text.pdf.PdfPCell cell32 = new iTextSharp.text.pdf.PdfPCell(); cell32.AddElement(new Paragraph(conceptos["valorUnitario"], font)); cell32.Colspan = 2; iTextSharp.text.pdf.PdfPCell cell33 = new iTextSharp.text.pdf.PdfPCell(); cell33.AddElement(new Paragraph(conceptos["importe"], font)); cell33.Colspan = 2; cell33.FixedHeight = 200f; //------------------------------------------------------- //----------------------TOTAL---------------------------- //------------------------------------------------------- iTextSharp.text.pdf.PdfPCell cell34 = new iTextSharp.text.pdf.PdfPCell(); cell34.Colspan = 2; cell34.Rowspan = 3; cell34.Border = BORDER; cell34.PaddingBottom = 0; cell34.PaddingTop = 0; cell34.AddElement(new Paragraph("")); iTextSharp.text.pdf.PdfPCell cell35 = new iTextSharp.text.pdf.PdfPCell(); cell35.Colspan = 7; cell35.Border = BORDER; cell35.Rowspan = 3; cell35.PaddingTop = 0; cell35.PaddingBottom = 0; NumLetra nl = new NumLetra(); cell35.AddElement(new Paragraph("IMPORTE CON LETRA: " + nl.Convertir("" + Total, true, Moneda), textBold)); iTextSharp.text.pdf.PdfPCell cell36 = new iTextSharp.text.pdf.PdfPCell(); cell36.Colspan = 2; cell36.Border = BORDER; cell36.PaddingBottom = 0; cell36.PaddingTop = 0; cell36.Phrase = new Phrase("SubTotal:", textBold); cell36.HorizontalAlignment = Element.ALIGN_RIGHT; cell36.VerticalAlignment = Element.ALIGN_BOTTOM; iTextSharp.text.pdf.PdfPCell cell37 = new iTextSharp.text.pdf.PdfPCell(); cell37.Colspan = 1; cell37.Border = BORDER; cell37.PaddingTop = 0; cell37.PaddingBottom = 0; cell37.AddElement(new Paragraph("$ " + ((Total / 1.16)).ToString("f2"), font)); //-- iTextSharp.text.pdf.PdfPCell cell38 = new iTextSharp.text.pdf.PdfPCell(); cell38.Colspan = 2; cell38.PaddingBottom = 0; cell38.PaddingTop = 0; cell38.Border = BORDER; cell38.Phrase = new Phrase("IVA(IVA 16.00%):", textBold); cell38.HorizontalAlignment = Element.ALIGN_RIGHT; cell38.VerticalAlignment = Element.ALIGN_BOTTOM; iTextSharp.text.pdf.PdfPCell cell39 = new iTextSharp.text.pdf.PdfPCell(); cell39.Colspan = 1; cell39.PaddingTop = 0; cell39.PaddingBottom = 0; cell39.Border = BORDER; cell39.AddElement(new Paragraph("$ " + (Total - (Total / 1.16)).ToString("f2"), font)); //--- iTextSharp.text.pdf.PdfPCell cell40 = new iTextSharp.text.pdf.PdfPCell(); cell40.Colspan = 2; cell40.Border = BORDER; cell40.VerticalAlignment = Element.ALIGN_BOTTOM; cell40.Phrase = new Phrase("Total:", textBold); cell40.PaddingBottom = 0; cell40.PaddingTop = 0; cell40.HorizontalAlignment = Element.ALIGN_RIGHT; iTextSharp.text.pdf.PdfPCell cell41 = new iTextSharp.text.pdf.PdfPCell(); cell41.Colspan = 1; cell41.Border = BORDER; cell41.PaddingTop = 0; cell41.PaddingBottom = 0; cell41.AddElement(new Paragraph("$ " + Total.ToString("f2"), font)); //--------------------------------------------------------------------- iTextSharp.text.pdf.PdfPCell cell42 = new iTextSharp.text.pdf.PdfPCell(); cell42.Colspan = 12; cell42.Border = BORDER; cell42.AddElement(new Paragraph("CONDICIONES GENERALES", textBold)); iTextSharp.text.pdf.PdfPCell cell43 = new iTextSharp.text.pdf.PdfPCell(); cell43.Colspan = 12; cell43.Border = BORDER; cell43.Rowspan = 9; string condiciones = "1.- Unicamente se atenderán productos comercializados por Avenzo Business Group S.de R.L.de C.V."; condiciones = condiciones + "\n2.- Todos los equipos cuentan con 1(un) año de garantía después de su fecha de facturación, excepto que se indique lo contrario en la factura."; condiciones = condiciones + "\n3.- Esta garantía es valida solo hasta el " + time.ToString("dd", ci) + " de " + time.ToString("MMMM", ci) + " del " + (time.AddYears(1).ToString("yyyy", ci)); condiciones = condiciones + "\n4.- Es indispensable indicar la descripción clara del problema.No se aceptará equipo a reparación y / o garantía con descripciones tales como \"NO FUNCIONA\", \"NO SIRVE\", etc."; condiciones = condiciones + "\n5.- Se recomienda conservar su factura o recibo de compra como protección adicional ya que puede sustituir a la póliza de garantía en caso de que ésta se extravíe o exista alguna discrepancia para comprobar la vigencia de la póliza."; condiciones = condiciones + "\n6.- Avenzo Business Group S.R.L.de C.V.se compromete a cambiar el producto defectuoso o en caso que se haya descontinuado cambiarlo por uno nuevo igual, similar o bien se ofrecerá una nota de crédito por el equipo a valor actual, cuando no sea posible la reparación a consecuencia de un defecto de fabricación previo diagnostico realizado en las oficinas sin ningún cargo para el cliente."; condiciones = condiciones + "\n7.- El tiempo de cambio no será mayor de 30(treinta) dias naturales contados a partir de la fecha de recepción del producto."; condiciones = condiciones + "\n\nNOTA: Esta garantía incluye los gastos de transportación internos del producto que se deriven en el cumplimiento de la misma."; cell43.AddElement(new Paragraph(condiciones, font)); iTextSharp.text.pdf.PdfPCell cell44 = new iTextSharp.text.pdf.PdfPCell(); cell44.Colspan = 12; cell44.Border = BORDER; cell44.AddElement(new Paragraph("EXEPCIONES Y RESTRICCIONES", textBold)); iTextSharp.text.pdf.PdfPCell cell45 = new iTextSharp.text.pdf.PdfPCell(); cell45.Colspan = 12; cell45.Rowspan = 9; cell45.Border = BORDER; string casos = "\na. La garantía No cubre desperfectos ocacionados:\n •Por Variaciones de voltaje(equipo quemado)."; casos = casos + "\n •Equipo mutilado en cables, accesorios o cualquiera de sus partes."; casos = casos + "\n •Cuando se demuestre que se hizo algun cambio ala instalación original o se ha hecho mal uso del equipo (de acuerdo a manuales)."; casos = casos + "\nb. Para servicio posterior al periodo de garantia o por equipo dañada que no aplica la garantia Avenzo ofrecerá"; casos = casos + "\n •Reparación en un periodo de 30-90 días previa cotización autorizaada por el distribuidor."; casos = casos + "\n •Remplazar el equipo ofreciendo el máximo descuento."; cell45.AddElement(new Paragraph("Avenzo Business Group S.de R.L.de C.V. SE EXIME DE HACER EFECTIVA ESTA PÓLIZA DE GARANTIA EN LOS SIGUINTES CASOS:" + casos, font)); Header.AddCell(cell4); Header.AddCell(cell5); Header.AddCell(cell6); Header.AddCell(cell7); Header.AddCell(cell8); Header.AddCell(cell9); Header.AddCell(cell10); Header.AddCell(cell11); Header.AddCell(cell12); Header.AddCell(cell13); Header.AddCell(cell14); Header.AddCell(cell15); Header.AddCell(cell16); Header.AddCell(cell17); Header.AddCell(cell18); Header.AddCell(cell19); Header.AddCell(cell20); Header.AddCell(cell21); Header.AddCell(cell22); Header.AddCell(cell23); Header.AddCell(salto); Header.AddCell(cell24); Header.AddCell(cell25); Header.AddCell(cell26); Header.AddCell(cell27); Header.AddCell(cell28); Header.AddCell(cell29); Header.AddCell(cell30); Header.AddCell(cell31); Header.AddCell(cell32); Header.AddCell(cell33); Header.AddCell(cell34); Header.AddCell(cell35); Header.AddCell(cell36); Header.AddCell(cell37); Header.AddCell(cell38); Header.AddCell(cell39); Header.AddCell(cell40); Header.AddCell(cell41); Header.AddCell(salto); if (leyenda == true) { Header.AddCell(cell42); Header.AddCell(cell43); Header.AddCell(cell44); Header.AddCell(cell45); } doc.Add(Header); doc.Close(); writer.Close(); return(memStream.ToArray()); }
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/"); }
public ActionResult PDFStatQuestion(int id) { List<Stat> stats = context.Stats.Where(i => i.QuestionId == id).ToList(); //On récupère les infos sur la question Question question = context.Questions.Find(id); ViewData["Question"] = question; // ArrayList listStatQuestion = new ArrayList(); foreach (var answer in question.Answers) { object[] obj = new object[] { answer.AnswerLabel, 0 }; listStatQuestion.Add(obj); } foreach (var stat in stats) { foreach (object[] obj in listStatQuestion) { if (obj[0] == stat.answer.AnswerLabel) { obj[1] = Convert.ToInt32(obj[1]) + 1; break; } } } //Affichage PDF Document myDocument = new Document(PageSize.A4); PdfWriter.GetInstance(myDocument, new FileStream("C:\\wamp\\www\\FormOnline\\FormOnline\\docs\\ExportStatQuestion" + question.QuestionId + ".pdf", FileMode.Create)); myDocument.Open(); #region Entetes myDocument.AddAuthor("FormOnline"); myDocument.AddCreationDate(); myDocument.AddTitle("Export PDF des statistiques questions"); #endregion PdfPTable table = new PdfPTable(2); //Entetes table PdfPCell cell = new PdfPCell(new Phrase("Export PDF des statistiques de la question : " + question.QuestionLabel)); cell.Colspan = 2; cell.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right cell.BackgroundColor = BaseColor.LIGHT_GRAY; PdfPCell cellForm = new PdfPCell(new Phrase("Formulaire : " + question.form.Title)); cellForm.Colspan = 2; cellForm.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right PdfPCell cellQuest = new PdfPCell(new Phrase("Question : " + question.QuestionLabel)); cellQuest.Colspan = 2; cellQuest.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right cellQuest.BackgroundColor = BaseColor.LIGHT_GRAY; table.AddCell(cell); table.AddCell(cellForm); table.AddCell(cellQuest); table.AddCell("Réponse"); table.AddCell("Nb"); int cpt = 0; //Pour chaque stats foreach (object[] obj in listStatQuestion) { PdfPCell cellA = new PdfPCell(new Phrase(obj[0].ToString())); PdfPCell cellNb = new PdfPCell(new Phrase(obj[1].ToString())); //Effet de style 1 ligne sur 2 if (cpt % 2 == 0) { cellA.BackgroundColor = BaseColor.LIGHT_GRAY; cellNb.BackgroundColor = BaseColor.LIGHT_GRAY; } table.AddCell(cellA); table.AddCell(cellNb); cpt++; } myDocument.Add(table); myDocument.Close(); ViewData["listStatQuestion"] = listStatQuestion; //Retourne à la page index des stats return RedirectToAction("StatQuestion", "Stat", new { id = question.QuestionId }); }
//------------FACTURA------------------------------- public static void CrearFactura(string PATH, string Archivo) { var Datos = LeerCFDI(PATH + Archivo + ".xml"); Font font = new Font(Font.FontFamily.HELVETICA, 6, Font.NORMAL); Font sellos = new Font(Font.FontFamily.HELVETICA, 5, Font.NORMAL); Font textBold = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 7); iTextSharp.text.Document doc = new iTextSharp.text.Document(iTextSharp.text.PageSize.LETTER); iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(doc, new FileStream(PATH + Archivo + ".pdf", FileMode.Create)); doc.AddTitle("Factura Electronica"); doc.AddCreator("Avenzo Proteccion"); doc.AddAuthor("Cristian Santiago Rosas"); doc.Open(); iTextSharp.text.Image avenzo = iTextSharp.text.Image.GetInstance("~/Images/Avenzo_Logo_Header.png"); iTextSharp.text.pdf.PdfPTable Header = new iTextSharp.text.pdf.PdfPTable(12); float[] widths = new float[] { .8f, .8f, .8f, .8f, .8f, .8f, .8f, .8f, .8f, .8f, .8f, .8f }; iTextSharp.text.Rectangle page = doc.PageSize; Header.WidthPercentage = 80; Header.LockedWidth = true; Header.SetWidths(widths); Header.TotalWidth = page.Width - 90; //--------------------------------------------- //-----------CABEZERA DEL DOCUMENTO------------ //--------------------------------------------- iTextSharp.text.pdf.PdfPCell cell = new iTextSharp.text.pdf.PdfPCell();//--Logo cell.AddElement(avenzo); cell.Colspan = 4; cell.Border = BORDER; iTextSharp.text.pdf.PdfPCell cell2 = new iTextSharp.text.pdf.PdfPCell();//--Domicilio Fiscal cell2.AddElement(new iTextSharp.text.Paragraph(Datos["EmisorNombre"] + "\n" + Datos["EmisorRFC"] + "\nDomicilio Fiscal\n" + Datos["DomicilioFiscal"] + "\nTel. 6645266573", new Font(Font.FontFamily.HELVETICA, 5, Font.BOLD))); cell2.Colspan = 4; cell2.Border = BORDER; cell2.HorizontalAlignment = 1; Header.AddCell(cell); Header.AddCell(cell2); iTextSharp.text.pdf.PdfPCell cell51 = new iTextSharp.text.pdf.PdfPCell(); cell51.Phrase = new Phrase("Factura No: " + Datos["folio"] + "\nFOLIO FISCAL (UUID):\n" + Datos["UUID"] + "\nNO. DE SERIE DEL CERTIFICADO DEL SAT:\n" + Datos["noCertificadoSAT"] + "\nNO. DE SERIE DEL CERTIFICADO DEL EMISOR:\n" + Datos["noCertificado"] + "\nFECHA Y HORA DE CERTIFICACIÓN:\n" + Datos["FechaTimbrado"] + "\nFECHA Y HORA DE EMISIÓN DE CFDI:\n" + Datos["FechaComprobante"], textBold); cell51.HorizontalAlignment = Element.ALIGN_CENTER; cell51.Colspan = 4; Header.AddCell(cell51); iTextSharp.text.pdf.PdfPCell salto = new iTextSharp.text.pdf.PdfPCell(); salto.AddElement(new Chunk("\n")); salto.Colspan = 12; salto.Border = BORDER; Header.AddCell(salto); //--------------------------------------------- //------------DATOS CLIENTE------------------- //--------------------------------------------- iTextSharp.text.pdf.PdfPCell cell4 = new iTextSharp.text.pdf.PdfPCell();//--Domicilio Fiscal cell4.Colspan = 1; cell4.Border = BORDER; cell4.PaddingTop = 0; cell4.PaddingBottom = 0; cell4.AddElement(new Paragraph("Cliente:", textBold)); iTextSharp.text.pdf.PdfPCell cell5 = new iTextSharp.text.pdf.PdfPCell();//--Domicilio Fiscal cell5.Colspan = 2; cell5.PaddingTop = 0; cell5.PaddingBottom = 0; cell5.Border = BORDER; cell5.AddElement(new Paragraph(Datos["ReceptorNombre"], font)); iTextSharp.text.pdf.PdfPCell cell6 = new iTextSharp.text.pdf.PdfPCell();//--Domicilio Fiscal cell6.Colspan = 2; cell6.Border = BORDER; cell6.PaddingTop = 0; cell6.PaddingBottom = 0; cell6.AddElement(new Paragraph("Régimen Fiscal:", textBold)); iTextSharp.text.pdf.PdfPCell cell7 = new iTextSharp.text.pdf.PdfPCell();//--Domicilio Fiscal cell7.Colspan = 7; cell7.Border = BORDER; cell7.PaddingTop = 0; cell7.PaddingBottom = 0; cell7.AddElement(new Paragraph(Datos["Regimen"], font)); iTextSharp.text.pdf.PdfPCell cell8 = new iTextSharp.text.pdf.PdfPCell();//--Domicilio Fiscal cell8.Colspan = 1; cell8.Border = BORDER; cell8.PaddingTop = 0; cell8.PaddingBottom = 0; cell8.AddElement(new Paragraph("RFC:", textBold)); iTextSharp.text.pdf.PdfPCell cell9 = new iTextSharp.text.pdf.PdfPCell();//--Domicilio Fiscal cell9.Colspan = 2; cell9.Border = BORDER; cell9.PaddingTop = 0; cell9.PaddingBottom = 0; cell9.AddElement(new Paragraph(Datos["ReceptorRFC"], font)); iTextSharp.text.pdf.PdfPCell cell10 = new iTextSharp.text.pdf.PdfPCell(); cell10.Colspan = 2; cell10.Border = BORDER; cell10.PaddingBottom = 0; cell10.PaddingTop = 0; cell10.AddElement(new Paragraph("Lugar de Expedición:", textBold)); iTextSharp.text.pdf.PdfPCell cell11 = new iTextSharp.text.pdf.PdfPCell(); cell11.Colspan = 3; cell11.Border = BORDER; cell11.PaddingTop = 0; cell11.PaddingBottom = 0; cell11.AddElement(new Paragraph(Datos["LugarExpedicion"], font)); iTextSharp.text.pdf.PdfPCell cell12 = new iTextSharp.text.pdf.PdfPCell(); cell12.AddElement(new Paragraph("Fecha de Expedicion:", textBold)); cell12.Colspan = 2; cell12.Border = BORDER; cell12.PaddingBottom = 0; cell12.PaddingTop = 0; iTextSharp.text.pdf.PdfPCell cell13 = new iTextSharp.text.pdf.PdfPCell(); cell13.Colspan = 3; cell13.Border = BORDER; cell13.PaddingTop = 0; cell13.PaddingBottom = 0; DateTime time = DateTime.Parse(Datos["FechaComprobante"]); System.Globalization.CultureInfo ci = new System.Globalization.CultureInfo("es-MX"); cell13.AddElement(new Paragraph(time.ToString("dd", ci) + " de " + time.ToString("MMMM", ci) + " del " + time.ToString("yyyy", ci), font)); //--- iTextSharp.text.pdf.PdfPCell cell14 = new iTextSharp.text.pdf.PdfPCell(); cell14.Colspan = 1; cell14.Rowspan = 2; cell14.PaddingTop = 0; cell14.PaddingBottom = 0; cell14.Border = BORDER; cell14.AddElement(new Paragraph("Direccion:", textBold)); iTextSharp.text.pdf.PdfPCell cell15 = new iTextSharp.text.pdf.PdfPCell(); cell15.Colspan = 2; cell15.Rowspan = 2; cell15.Border = BORDER; cell15.PaddingBottom = 0; cell15.PaddingTop = 0; cell15.AddElement(new Paragraph(Datos["ReceptorDomicilio"], font)); iTextSharp.text.pdf.PdfPCell cell16 = new iTextSharp.text.pdf.PdfPCell(); cell16.Colspan = 2; cell16.PaddingTop = 0; cell16.PaddingBottom = 0; cell16.AddElement(new Paragraph("Forma De Pago:", textBold)); cell16.Border = BORDER; iTextSharp.text.pdf.PdfPCell cell17 = new iTextSharp.text.pdf.PdfPCell(); cell17.PaddingBottom = 0; cell17.PaddingTop = 0; cell17.Colspan = 3; cell17.Border = BORDER; cell17.AddElement(new Paragraph(Datos["formaDePago"], font)); iTextSharp.text.pdf.PdfPCell cell18 = new iTextSharp.text.pdf.PdfPCell(); cell18.AddElement(new Paragraph("Clave Moneda:", textBold)); cell18.Colspan = 2; cell18.Border = BORDER; cell18.PaddingTop = 0; cell18.PaddingBottom = 0; iTextSharp.text.pdf.PdfPCell cell19 = new iTextSharp.text.pdf.PdfPCell(); cell19.Colspan = 2; cell19.Border = BORDER; cell19.PaddingBottom = 0; cell19.PaddingTop = 0; cell19.AddElement(new Paragraph(Datos["Moneda"], font)); iTextSharp.text.pdf.PdfPCell cell20 = new iTextSharp.text.pdf.PdfPCell(); cell20.Colspan = 2; cell20.Border = BORDER; cell20.PaddingTop = 0; cell20.PaddingBottom = 0; cell20.AddElement(new Paragraph("Método de Pago:", textBold)); iTextSharp.text.pdf.PdfPCell cell21 = new iTextSharp.text.pdf.PdfPCell(); cell21.Colspan = 3; cell21.Border = BORDER; cell21.PaddingTop = 0; cell21.PaddingBottom = 0; cell21.AddElement(new Paragraph(Datos["metodoDePago"], font)); iTextSharp.text.pdf.PdfPCell cell22 = new iTextSharp.text.pdf.PdfPCell(); cell22.Colspan = 2; cell22.Border = BORDER; cell22.PaddingTop = 0; cell22.PaddingBottom = 0; cell22.AddElement(new Paragraph("NumCtaPago:", textBold)); iTextSharp.text.pdf.PdfPCell cell23 = new iTextSharp.text.pdf.PdfPCell(); cell23.Colspan = 2; cell23.Border = BORDER; cell23.PaddingTop = 0; cell23.PaddingBottom = 0; cell23.AddElement(new Paragraph(Datos["NumCtaPago"], font)); //---------------------------------------------- //-----------------PRODUCTOS-------------------- //---------------------------------------------- iTextSharp.text.pdf.PdfPCell cell24 = new iTextSharp.text.pdf.PdfPCell(); cell24.Colspan = 1; cell24.AddElement(new Paragraph("Cantidad", textBold)); iTextSharp.text.pdf.PdfPCell cell25 = new iTextSharp.text.pdf.PdfPCell(); cell25.Colspan = 1; cell25.AddElement(new Paragraph("Unidad de Medida", textBold)); iTextSharp.text.pdf.PdfPCell cell26 = new iTextSharp.text.pdf.PdfPCell(); cell26.Colspan = 6; cell26.HorizontalAlignment = Element.ALIGN_CENTER; cell26.VerticalAlignment = Element.ALIGN_CENTER; cell26.AddElement(new Paragraph("Descripcion", textBold)); iTextSharp.text.pdf.PdfPCell cell27 = new iTextSharp.text.pdf.PdfPCell(); cell27.Colspan = 2; cell27.AddElement(new Paragraph("Producto Unitario", textBold)); iTextSharp.text.pdf.PdfPCell cell28 = new iTextSharp.text.pdf.PdfPCell(); cell28.Colspan = 2; cell28.HorizontalAlignment = Element.ALIGN_CENTER; cell28.VerticalAlignment = Element.ALIGN_CENTER; cell28.AddElement(new Paragraph("Importe", textBold)); //----------------------------------------------- iTextSharp.text.pdf.PdfPCell cell29 = new iTextSharp.text.pdf.PdfPCell(); cell29.AddElement(new Paragraph(Datos["cantidad"], font)); cell29.Colspan = 1; iTextSharp.text.pdf.PdfPCell cell30 = new iTextSharp.text.pdf.PdfPCell(); cell30.AddElement(new Paragraph(Datos["unidad"], font)); cell30.Colspan = 1; iTextSharp.text.pdf.PdfPCell cell31 = new iTextSharp.text.pdf.PdfPCell(); cell31.AddElement(new Paragraph(Datos["descripcion"], font)); cell31.Colspan = 6; iTextSharp.text.pdf.PdfPCell cell32 = new iTextSharp.text.pdf.PdfPCell(); cell32.AddElement(new Paragraph(Datos["valorUnitario"], font)); cell32.Colspan = 2; iTextSharp.text.pdf.PdfPCell cell33 = new iTextSharp.text.pdf.PdfPCell(); cell33.AddElement(new Paragraph(Datos["importe"], font)); cell33.Colspan = 2; cell33.FixedHeight = 200f; //------------------------------------------------------- //----------------------TOTAL---------------------------- //------------------------------------------------------- iTextSharp.text.pdf.PdfPCell cell34 = new iTextSharp.text.pdf.PdfPCell(); cell34.Colspan = 2; cell34.Rowspan = 3; cell34.Border = BORDER; cell34.PaddingBottom = 0; cell34.PaddingTop = 0; cell34.AddElement(new Paragraph("")); iTextSharp.text.pdf.PdfPCell cell35 = new iTextSharp.text.pdf.PdfPCell(); cell35.Colspan = 7; cell35.Border = BORDER; cell35.Rowspan = 3; cell35.PaddingTop = 0; cell35.PaddingBottom = 0; NumLetra nl = new NumLetra(); cell35.AddElement(new Paragraph("IMPORTE CON LETRA: " + nl.Convertir(Datos["total"], true, false), textBold)); iTextSharp.text.pdf.PdfPCell cell36 = new iTextSharp.text.pdf.PdfPCell(); cell36.Colspan = 2; cell36.Border = BORDER; cell36.PaddingBottom = 0; cell36.PaddingTop = 0; cell36.Phrase = new Phrase("SubTotal:", textBold); cell36.HorizontalAlignment = Element.ALIGN_RIGHT; cell36.VerticalAlignment = Element.ALIGN_BOTTOM; iTextSharp.text.pdf.PdfPCell cell37 = new iTextSharp.text.pdf.PdfPCell(); cell37.Colspan = 1; cell37.Border = BORDER; cell37.PaddingTop = 0; cell37.PaddingBottom = 0; cell37.AddElement(new Paragraph("$ " + Datos["subTotal"], font)); //-- iTextSharp.text.pdf.PdfPCell cell38 = new iTextSharp.text.pdf.PdfPCell(); cell38.Colspan = 2; cell38.PaddingBottom = 0; cell38.PaddingTop = 0; cell38.Border = BORDER; cell38.Phrase = new Phrase("IVA(IVA 16.00%):", textBold); cell38.HorizontalAlignment = Element.ALIGN_RIGHT; cell38.VerticalAlignment = Element.ALIGN_BOTTOM; iTextSharp.text.pdf.PdfPCell cell39 = new iTextSharp.text.pdf.PdfPCell(); cell39.Colspan = 1; cell39.PaddingTop = 0; cell39.PaddingBottom = 0; cell39.Border = BORDER; cell39.AddElement(new Paragraph("$ " + Datos["totalImpuestosTrasladados"], font)); //--- iTextSharp.text.pdf.PdfPCell cell40 = new iTextSharp.text.pdf.PdfPCell(); cell40.Colspan = 2; cell40.Border = BORDER; cell40.VerticalAlignment = Element.ALIGN_BOTTOM; cell40.Phrase = new Phrase("Total:", textBold); cell40.PaddingBottom = 0; cell40.PaddingTop = 0; cell40.HorizontalAlignment = Element.ALIGN_RIGHT; iTextSharp.text.pdf.PdfPCell cell41 = new iTextSharp.text.pdf.PdfPCell(); cell41.Colspan = 1; cell41.Border = BORDER; cell41.PaddingTop = 0; cell41.PaddingBottom = 0; cell41.AddElement(new Paragraph("$ " + Datos["total"], font)); //--------------------------------------------------------- //-------------------CDFI SELLOS--------------------------- //--------------------------------------------------------- iTextSharp.text.pdf.PdfPCell cell42 = new iTextSharp.text.pdf.PdfPCell(); cell42.Colspan = 10; cell42.Border = BORDER; cell42.Phrase = new Phrase("SELLO DIGITAL DEL CFDI", textBold); iTextSharp.text.pdf.BarcodeQRCode QR = new iTextSharp.text.pdf.BarcodeQRCode(Datos["QR"], 300, 300, null); Image img = QR.GetImage(); img.SetDpi(1400, 1400); iTextSharp.text.pdf.PdfPCell cell43 = new iTextSharp.text.pdf.PdfPCell(); cell43.Colspan = 2; cell43.Border = BORDER; cell43.Rowspan = 9; cell43.VerticalAlignment = Element.ALIGN_TOP; cell43.AddElement(img); iTextSharp.text.pdf.PdfPCell cell44 = new iTextSharp.text.pdf.PdfPCell(); cell44.Colspan = 10; cell44.Phrase = new Phrase(Datos["selloCFD"], sellos); iTextSharp.text.pdf.PdfPCell cell45 = new iTextSharp.text.pdf.PdfPCell(); cell45.Colspan = 10; cell45.Phrase = new Phrase("SELLO DIGITAL DEL SAT", textBold); cell45.Border = BORDER; iTextSharp.text.pdf.PdfPCell cell46 = new iTextSharp.text.pdf.PdfPCell(); cell46.Phrase = new Phrase(Datos["SelloSAT"], sellos); cell46.Colspan = 10; iTextSharp.text.pdf.PdfPCell cell47 = new iTextSharp.text.pdf.PdfPCell(); cell47.Phrase = new Phrase("CADENA ORIGINAL DEL COMPLEMENTO DE CERTIFICACIÓN DIGITAL DEL SAT", textBold); cell47.Border = BORDER; cell47.Colspan = 10; iTextSharp.text.pdf.PdfPCell cell48 = new iTextSharp.text.pdf.PdfPCell(); cell48.Colspan = 10; cell48.Phrase = new Phrase(Datos["CadenaOriginal"], sellos); iTextSharp.text.pdf.PdfPCell cell49 = new iTextSharp.text.pdf.PdfPCell(); cell49.Colspan = 10; cell49.Phrase = new Phrase(""); cell49.Border = BORDER; Header.AddCell(cell4); Header.AddCell(cell5); Header.AddCell(cell6); Header.AddCell(cell7); Header.AddCell(cell8); Header.AddCell(cell9); Header.AddCell(cell10); Header.AddCell(cell11); Header.AddCell(cell12); Header.AddCell(cell13); Header.AddCell(cell14); Header.AddCell(cell15); Header.AddCell(cell16); Header.AddCell(cell17); Header.AddCell(cell18); Header.AddCell(cell19); Header.AddCell(cell20); Header.AddCell(cell21); Header.AddCell(cell22); Header.AddCell(cell23); Header.AddCell(salto); Header.AddCell(cell24); Header.AddCell(cell25); Header.AddCell(cell26); Header.AddCell(cell27); Header.AddCell(cell28); Header.AddCell(cell29); Header.AddCell(cell30); Header.AddCell(cell31); Header.AddCell(cell32); Header.AddCell(cell33); Header.AddCell(cell34); Header.AddCell(cell35); Header.AddCell(cell36); Header.AddCell(cell37); Header.AddCell(cell38); Header.AddCell(cell39); Header.AddCell(cell40); Header.AddCell(cell41); Header.AddCell(salto); Header.AddCell(cell49); Header.AddCell(cell43); Header.AddCell(cell42); Header.AddCell(cell44); Header.AddCell(cell49); Header.AddCell(cell45); Header.AddCell(cell46); Header.AddCell(cell49); Header.AddCell(cell47); Header.AddCell(cell48); doc.Add(Header); doc.Close(); writer.Close(); }
protected void SonucYazdır_Click(object sender, EventArgs e) { MongoClient client = new MongoClient(); var database = client.GetDatabase("hastane"); var collection = database.GetCollection <yatanhastalar>("yatanhastalar"); var servislistesi = collection.Find(x => x._id != null).ToList().SelectMany(x => x.ServisList).ToList(); var hastalistesi = servislistesi.SelectMany(x => x.HastaList).ToList().Where(x => x._id == ObjectId.Parse(ddlHasta2.SelectedValue)).ToList().FirstOrDefault(); var sonuc = database.GetCollection <islemsonuc>("sonuclistesi").Find(x => x._id == ObjectId.Parse(ddlsonuctarih.SelectedValue) && x.sonuc_cesidi == "Laboratuvar").ToList().SelectMany(x => x.SonucList).ToList(); #region Font seç BaseFont trArial = BaseFont.CreateFont(@"C:\WINDOWS\Fonts\tahoma.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); iTextSharp.text.Font fontArial = new iTextSharp.text.Font(trArial, 10, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.DARK_GRAY); iTextSharp.text.Font fontArialHeader = new iTextSharp.text.Font(trArial, 13, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLACK); iTextSharp.text.Font fontArialbold = new iTextSharp.text.Font(trArial, 9, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.DARK_GRAY); iTextSharp.text.Font fontArialboldgeneral = new iTextSharp.text.Font(trArial, 10, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLACK); #endregion #region Sonuç pdf oluştur iTextSharp.text.Document pdfFile = new iTextSharp.text.Document(); PdfWriter.GetInstance(pdfFile, new FileStream("C:\\Users\\Önder\\Desktop\\Yeni klasör\\Kan Sonucu (" + hastalistesi.hasta_adi + " " + hastalistesi.hasta_soyadi + " " + ddlsonuctarih.SelectedItem.Text + ").pdf", FileMode.Create)); pdfFile.Open(); #endregion #region Sonuç oluşturan bilgileri pdfFile.AddCreator("Önder"); //Oluşturan kişinin isminin eklenmesi pdfFile.AddCreationDate(); //Oluşturulma tarihinin eklenmesi pdfFile.AddAuthor("Laboratuvar"); //Yazarın isiminin eklenmesi pdfFile.AddHeader("Başlık", "PDF UYGULAMASI OLUSTUR"); pdfFile.AddTitle("Sonuç Raporu"); //Başlık ve title eklenmesi #endregion #region Sonuç firma resmi ve tarihi oluştur iTextSharp.text.Image jpgimg = iTextSharp.text.Image.GetInstance(@"C:/Users/Önder/Desktop/Önder Fatih Buhurcu Staj Projesi/WebApplicationHastane/WebApplicationHastane/login/images/İsimsiz-1.png"); jpgimg.ScalePercent(35); jpgimg.Alignment = iTextSharp.text.Image.LEFT_ALIGN; PdfPTable pdfTableHeader = new PdfPTable(3); pdfTableHeader.TotalWidth = 500f; pdfTableHeader.LockedWidth = true; pdfTableHeader.DefaultCell.Border = Rectangle.NO_BORDER; PdfPCell cellheader1 = new PdfPCell(jpgimg); cellheader1.HorizontalAlignment = PdfPCell.ALIGN_LEFT; cellheader1.VerticalAlignment = PdfPCell.ALIGN_BOTTOM; cellheader1.FixedHeight = 60f; cellheader1.Border = 0; pdfTableHeader.AddCell(cellheader1); PdfPCell cellheader2 = new PdfPCell(new Phrase("SONUÇ RAPORU", fontArialHeader)); cellheader2.HorizontalAlignment = PdfPCell.ALIGN_CENTER; cellheader2.VerticalAlignment = PdfPCell.ALIGN_MIDDLE; cellheader2.FixedHeight = 60f; cellheader2.Border = 0; pdfTableHeader.AddCell(cellheader2); PdfPCell cellheader3 = new PdfPCell(new Phrase(DateTime.Now.ToShortDateString(), fontArial)); cellheader3.HorizontalAlignment = PdfPCell.ALIGN_RIGHT; cellheader3.VerticalAlignment = PdfPCell.ALIGN_MIDDLE; cellheader3.FixedHeight = 60f; cellheader3.Border = 0; pdfTableHeader.AddCell(cellheader3); #endregion Phrase p = new Phrase("\n"); Paragraph yazi = new Paragraph("Hasta TC: " + hastalistesi.hasta_tc + "\nHasta Adı: " + hastalistesi.hasta_adi + "\nHasta Soyadı: " + hastalistesi.hasta_soyadi + "\n\n\n"); #region Tabloyu Oluştur PdfPTable pdfTable = new PdfPTable(2); pdfTable.TotalWidth = 500f; pdfTable.LockedWidth = true; pdfTable.HorizontalAlignment = 1; pdfTable.DefaultCell.Padding = 5; pdfTable.DefaultCell.BorderColor = iTextSharp.text.BaseColor.GRAY; foreach (var item in sonuc) { pdfTable.AddCell(new Phrase(item.tahlil_adi, fontArialboldgeneral)); pdfTable.AddCell(new Phrase(item.sonuc, fontArial)); } #endregion #region Pdfe yaz ve dosyayı kapat if (pdfFile.IsOpen() == false) { pdfFile.Open(); } pdfFile.Add(pdfTableHeader); pdfFile.Add(p); pdfFile.Add(yazi); pdfFile.Add(pdfTable); pdfFile.Close(); #endregion }
/// <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); } }
private void BuildPDF(Dictionary<string, ISPage> pageMap, string baseRoom, Dictionary<string, int> chapterPageMap, bool fakeRun) { if (fakeRun) { ISPageHtmlParser.BuildAllISPages(pageMap, baseRoom, filePath).Wait(); } //now that we have all the pages, we'll have to clean them up and decide on pages Dictionary<string, int> ISPageToPhysicalPageMap = new Dictionary<string, int>(); int currentPage = 1; int currentChapter = 1; Random r = new Random(123456); List<string> pagesLeft = new List<string>(pageMap.Count); foreach (string x in pageMap.Keys) { pagesLeft.Add(x); } using (MemoryStream memStream = new MemoryStream()) { Document pdfDoc = new Document(); iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDoc, memStream); HeaderFooter evnt = new HeaderFooter(); if (fakeRun) { evnt.pageByTitle = chapterPageMap; } else { evnt.pageByTitle = new Dictionary<string, int>(); } if (!fakeRun) { writer.PageEvent = evnt; } pdfDoc.Open(); pdfDoc.AddAuthor("test"); pdfDoc.AddTitle("testTitle"); while (pagesLeft.Any()) { string pageToAdd = pagesLeft.First(); if (currentPage > 1) { pagesLeft.Skip(r.Next(pagesLeft.Count)).First(); } pagesLeft.Remove(pageToAdd); if (fakeRun) { chapterPageMap.Add(pageToAdd, writer.PageNumber + 1); } ISPageToPhysicalPageMap.Add(pageToAdd, currentPage); var chapter = GetPDFPage(pageMap[pageToAdd], int.Parse(pageToAdd), chapterPageMap); pdfDoc.Add(chapter); int actualPageLength = fakeRun ? 1 : chapterPageMap[pageToAdd]; currentPage += actualPageLength; currentChapter++; } pdfDoc.Close(); writer.Close(); if (!fakeRun) { File.WriteAllBytes(Path.Combine(filePath, fileName), memStream.GetBuffer()); } } }
public void PrintPDF() { SaveFileDialog saveFileDialog = new SaveFileDialog() { Filter = "pdf|*.pdf" }; saveFileDialog.ShowDialog(); string fileName = saveFileDialog.FileName; iTextSharp.text.Document oDoc = new iTextSharp.text.Document(PageSize.A4, 25, 25, 30, 30); try { PdfWriter.GetInstance(oDoc, new FileStream(fileName, FileMode.Create)); oDoc.Open(); //Meta data oDoc.AddAuthor("Dariusz Momot & Łukasz Kudzia"); oDoc.AddCreator("NutritionApp"); oDoc.AddTitle("Grocery List"); //Fonts Font titleFont = FontFactory.GetFont("Verdana", 8, Font.ITALIC); titleFont.Color = BaseColor.DARK_GRAY; Font cellFonnt = FontFactory.GetFont(FontFactory.COURIER, 12, BaseColor.DARK_GRAY); //Title Paragraph title = new Paragraph("Your grocery list from " + DateTime.Now, titleFont); title.Alignment = Element.ALIGN_CENTER; oDoc.Add(title); oDoc.Add(new Paragraph("\n")); oDoc.Add(new Paragraph("\n")); //Table PdfPTable table = new PdfPTable(3); foreach (var item in GroceryList) { table.AddCell(item.Count.ToString()); table.AddCell(item.Units.ToString()); table.AddCell(item.Name); } table.HorizontalAlignment = Element.ALIGN_CENTER; table.PaddingTop = 20f; oDoc.Add(table); oDoc.Add(new Paragraph("\n")); oDoc.Add(new Paragraph("\n")); Paragraph foter = new Paragraph("Create by NutritionApp", titleFont); oDoc.Add(foter); } catch (Exception e) { MessageBox.Show(e.Message, "Cannot save your list", MessageBoxButton.OK, MessageBoxImage.Warning); } finally { oDoc.Close(); } }
protected void GeneratePDF() { // Refresh the summary grid else there will be nothing to generate (no postback) this.PopulateGrid(); // Create and initialize a new document object iTextSharp.text.Document document = new iTextSharp.text.Document(iTextSharp.text.PageSize.LEGAL, 24, 24, 24, 24); document.PageSize.Rotate(); System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(); try { // Create an instance of the writer object iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, memoryStream); // Add some meta information to the document Label lblPageTitle = (Label)(this.Page.Master.FindControl("lblDefaultMasterPageTitle")); document.AddAuthor(lblPageTitle.Text); document.AddSubject(this.lblReportTitle.Text); // Open the document document.Open(); // Create a table to match our current summary grid iTextSharp.text.Table table = null; if (this.DateRangeType == DateRangeTypes.UserSpecified) table = new iTextSharp.text.Table(6); else if (this.DateRangeType == DateRangeTypes.Daily) table = new iTextSharp.text.Table(7); else table = new iTextSharp.text.Table(8); table.TableFitsPage = true; // Apply spacing/padding/borders/column widths to the table table.Padding = 2; table.Spacing = 0; table.DefaultCellBorderWidth = 1; if (this.DateRangeType == DateRangeTypes.UserSpecified) { float[] headerwidths1 = { 30, 30, 30, 30, 30, 30 }; table.Widths = headerwidths1; } else if (this.DateRangeType == DateRangeTypes.Daily) { float[] headerwidths2 = { 40, 30, 30, 30, 30, 30, 30 }; table.Widths = headerwidths2; } else { float[] headerwidths3 = { 40, 30, 30, 30, 30, 30, 30, 35 }; table.Widths = headerwidths3; } table.Width = 100; // Add report title spanning all columns iTextSharp.text.Font titleFont = new iTextSharp.text.Font(Font.GetFamilyIndex("Tahoma"), 6, Font.BOLD); titleFont.Color = new iTextSharp.text.Color(System.Drawing.Color.Firebrick); iTextSharp.text.Cell titleCell = new iTextSharp.text.Cell(); titleCell.SetHorizontalAlignment("Left"); titleCell.SetVerticalAlignment("Top"); titleCell.BackgroundColor = new iTextSharp.text.Color(System.Drawing.Color.White); titleCell.BorderWidth = 0; if (this.DateRangeType == DateRangeTypes.UserSpecified) titleCell.Colspan = 6; else if (this.DateRangeType == DateRangeTypes.Daily) titleCell.Colspan = 7; else titleCell.Colspan = 8; titleCell.AddElement(new iTextSharp.text.Phrase(this.lblReportTitle.Text, titleFont)); table.AddCell(titleCell); // Add table headers for (int i = 0; i < this.grdRaveForm.Columns.Count; i++) { iTextSharp.text.Font headerCellFont = new iTextSharp.text.Font(Font.GetFamilyIndex("Tahoma"), 8, Font.NORMAL + Font.UNDERLINE); headerCellFont.Color = new iTextSharp.text.Color(System.Drawing.Color.White); iTextSharp.text.Cell headerCell = new iTextSharp.text.Cell(); headerCell.SetHorizontalAlignment("Left"); headerCell.SetVerticalAlignment("Top"); headerCell.BackgroundColor = new iTextSharp.text.Color(System.Drawing.Color.SteelBlue); headerCell.BorderColor = new iTextSharp.text.Color(System.Drawing.Color.White); headerCell.AddElement(new iTextSharp.text.Phrase(this.grdRaveForm.Columns[i].HeaderText, headerCellFont)); table.AddCell(headerCell); } table.EndHeaders(); // Add data to the table int j = 0; int k = 0; string phrase = ""; foreach (System.Data.DataRow row in this._pdfDataTable.Rows) { j++; // Increment the row counter k = 0; // Reset the column counter for the new row foreach (System.Data.DataColumn col in this._pdfDataTable.Columns) { k++; // Increment the column counter iTextSharp.text.Font cellFont = new iTextSharp.text.Font(Font.GetFamilyIndex("Tahoma"), 6, Font.NORMAL); if (j % 2 == 0) { cellFont.Color = new iTextSharp.text.Color(System.Drawing.Color.DarkRed); } else { cellFont.Color = new iTextSharp.text.Color(System.Drawing.Color.Black); } iTextSharp.text.Cell cell = new iTextSharp.text.Cell(); cell.SetHorizontalAlignment("Left"); cell.SetVerticalAlignment("Top"); cell.BorderColor = new iTextSharp.text.Color(System.Drawing.Color.White); if (j % 2 == 0) { cell.BackgroundColor = new iTextSharp.text.Color(System.Drawing.Color.LightGray); } else { cell.BackgroundColor = new iTextSharp.text.Color(System.Drawing.Color.White); } // Generate formatted phrase for cell. switch (col.ColumnName) { case "SummaryDate": case "MaxDate": phrase = String.Format("{0,10:MM/dd/yyyy}", row[col]); break; case "AvgSecs": case "StdDevSecs": phrase = String.Format("{0:F2}", row[col]); break; case "FormIDCount": phrase = String.Format("{0:G}", row[col]); break; default: phrase = row[col].ToString(); break; } cell.AddElement(new iTextSharp.text.Phrase(phrase, cellFont)); table.AddCell(cell); } } // Add the table to the document document.Add(table); // Close the document document.Close(); // Show the document Response.Clear(); Response.AddHeader("content-disposition", "attachment;filename=" + Enum.GetName(typeof(DateRangeTypes), this.DateRangeType) + "Performance" + ((DropDownList)this.Page.Master.FindControl("ddlReport")).SelectedItem.Text.Replace(" ", String.Empty) + ".pdf"); Response.ContentType = "application/pdf"; Response.BinaryWrite(memoryStream.ToArray()); Response.End(); } catch (Exception xcptn) { Response.Write(xcptn.Message); } }
private void GenerateReportButtonResultsView_Click(object sender, EventArgs e) { if (RepDirTextBox.Text == "" || RepDirTextBox.Text == "Set the folder where the pdf reports will be stored") { MessageBox.Show("Please select a folder on configuration tab to save the reports."); } else { GenerateReportResultsViewClicked = true; try { // event fired when the contextual menu was clicked //ToolStripMenuItem mi = (ToolStripMenuItem)e.ClickedItem; // mi : item clicked in the contextual menu // VStream tvs = (VStream)mi.Tag; if (ReportNameResultsViewtextBox.Text == "") { MessageBox.Show("Report Title section cannot be empty, please enter a title to display in .pdf report."); } else { //CreatePDFFile(); string reportname = SaveReportAstextBox.Text; if (reportname == "") { MessageBox.Show("Save Report As section cannot be empty, please enter a file name."); } else { IList Ltvs = ResultListView.GetSelectedObjects(); if (Ltvs.Count == 0) { MessageBox.Show("Please select a video to generate a report."); } else { // string imagefoldercreate = AppDomain.CurrentDomain.BaseDirectory + "Reports"; // Directory.CreateDirectory(imagefoldercreate); if (Directory.Exists(RepDirTextBox.Text)) { Document pdfdoc = new Document(iTextSharp.text.PageSize.LETTER, 40, 10, 42, 35); //string pdfFilePath = AppDomain.CurrentDomain.BaseDirectory + "Reports\\" + reportname + ".pdf"; string pdfFilePath = RepDirTextBox.Text + reportname + ".pdf"; PdfWriter wri = PdfWriter.GetInstance(pdfdoc, new FileStream(pdfFilePath, FileMode.Create)); pdfdoc.Open();//Open Document to write Paragraph par = new Paragraph(" "); int i = 0; //reportdatedisplayed = false; //GenerateReportResultsViewClicked = true; foreach (object tvs in Ltvs) { try { if (CreateMultiplePDFFile(reportname, (VStream)tvs, pdfdoc)) i++; par.SpacingBefore = 10f; Paragraph parend = new Paragraph("------------------------------------------------------------------------------------------------------------------------------------------"); pdfdoc.Add(parend); } catch { } } if (i == 1) { MessageBox.Show("PDF report for " + i + " video generated successfully. Located in " + RepDirTextBox.Text); } if (i > 1) { MessageBox.Show("PDF report for " + i + " videos generated successfully. Located in " + RepDirTextBox.Text); } // par.Alignment = Element.ALIGN_CENTER; //Anchor anchor1 = new Anchor("Help", iTextSharp.text.FontFactory.GetFont(iTextSharp.text.FontFactory.HELVETICA, 12, iTextSharp.text.Font.NORMAL, new iTextSharp.text.BaseColor(0, 0, 255))); //anchor1.Reference = "http://www.path1.com"; //anchor1.Name = "left"; //par.Add(anchor1); //par.Add("/"); //Anchor anchor2 = new Anchor("Contact", iTextSharp.text.FontFactory.GetFont(iTextSharp.text.FontFactory.HELVETICA, 12, iTextSharp.text.Font.NORMAL, new iTextSharp.text.BaseColor(0, 0, 255))); //anchor2.Reference = "http://www.path1.com"; //anchor2.Name = "middle"; //par.Add(anchor2); //par.Add("/"); //Anchor anchor3 = new Anchor("Whatever we want to show", iTextSharp.text.FontFactory.GetFont(iTextSharp.text.FontFactory.HELVETICA, 12, iTextSharp.text.Font.NORMAL, new iTextSharp.text.BaseColor(0, 0, 255))); //anchor3.Reference = "http://www.path1.com"; //anchor3.Name = "middle"; //par.Add(anchor3); //par.Alignment = Element.ALIGN_CENTER; //doc.Add(par); pdfdoc.AddAuthor("Path1"); pdfdoc.AddTitle("v.Cortex Report"); pdfdoc.AddSubject("This report is created by v.Cortex"); docopened = false; pdfdoc.Close(); } } } } } catch (Exception ex) { MessageBox.Show(ex.Message); } } }
public LibroAtrasos(AufenPortalReportesDataContext db, EMPRESA empresa, vw_Ubicacione departamento, DateTime FechaDesde, DateTime FechaHasta, string path, string rut) { //Nombre del archivo y ubiación en el árbol de carpetas NombreArchivo = String.Format("{0}/{1}/LibroAtrasos.pdf", empresa.Descripcion, departamento.Descripcion); // Vamos a buscar los datos que nos permitirtán armar elreporte IEnumerable<sp_LibroAsistenciaResult> resultadoLibroAtrasos = db.sp_LibroAsistencia( FechaDesde.ToString("yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture), FechaHasta.ToString("yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture), int.Parse(empresa.Codigo).ToString(), departamento.Codigo, rut).ToList(); IEnumerable<LibroAsistenciaDTO> libroAtrasos = Mapper.Map<IEnumerable<sp_LibroAsistenciaResult>, IEnumerable<LibroAsistenciaDTO>>(resultadoLibroAtrasos) .Where(x =>x.Entrada.HasValue && x.Salida.HasValue && x.SalidaTeorica.HasValue && x.EntradaTeorica.HasValue && x.Entrada > x.EntradaTeorica); // Comenzaremos a crear el reporte if (libroAtrasos.Any()) { Configuracion(); Document doc = new Document(iTextSharp.text.PageSize.LETTER, 10, 10, 50, 35); using (var ms = new MemoryStream()) { PdfWriter pdfWriter = PdfWriter.GetInstance(doc, ms); pdfWriter.PageEvent = new Header(empresa, path); doc.Open(); foreach (var reporte in libroAtrasos.GroupBy(x => new { x.Rut, x.IdDepartamento, x.IdEmpresa })) { var empleado = db.vw_Empleados.FirstOrDefault(x => x.IdEmpresa == empresa.Codigo && x.IdUbicacion == reporte.Key.IdDepartamento && x.Codigo == reporte.Key.Rut); if (empleado == null) { empleado = new vw_Empleado(); } doc.AddAuthor("Aufen"); doc.AddCreationDate(); doc.AddCreator("Aufen"); doc.AddTitle("Libro de Atrasos"); // Texto Paragraph parrafo = new Paragraph(); parrafo.Add(new Paragraph( String.Format("Departamento: {1}, Fecha de Reporte: {0}", DateTime.Now.ToShortDateString(), departamento.SucursalPlanta), Normal) { Alignment = Element.ALIGN_CENTER }); parrafo.Add(new Paragraph("Informe de Atrasos por Área", Titulo) { Alignment = Element.ALIGN_CENTER }); doc.Add(parrafo); doc.Add(new Phrase()); doc.Add(new Phrase()); PdfPTable informacionPersonal = new PdfPTable(new float[] { 1,5}); informacionPersonal.AddCell(new PdfPCell(new Phrase("Rut:", Normal))); informacionPersonal.AddCell(new PdfPCell(new Phrase(empleado.RutAufen, NormalNegrita))); informacionPersonal.AddCell(new PdfPCell(new Phrase("Nombre:", Normal))); informacionPersonal.AddCell(new PdfPCell(new Phrase(empleado.NombreCompleto, NormalNegrita))); informacionPersonal.AddCell(new PdfPCell(new Phrase("Centro de Costos:", Normal))); informacionPersonal.AddCell(new PdfPCell(new Phrase(String.Empty, NormalNegrita))); doc.Add(new Phrase()); doc.Add(informacionPersonal); // tabla PdfPTable tabla = new PdfPTable(new float[] {2, 2, 2, 2, 2, 2, 2, 4 }); // Primera lìnea cabecera tabla.AddCell(new PdfPCell(new Phrase("Fecha", Chico)) { Rowspan = 2 }); //tabla.AddCell(new PdfPCell(new Phrase("Empleado", Chico)) { Colspan = 3 }); tabla.AddCell(new PdfPCell(new Phrase("Horario", Chico)) { Colspan = 2 }); tabla.AddCell(new PdfPCell(new Phrase("Marcas", Chico)) { Colspan = 2 }); tabla.AddCell(new PdfPCell(new Phrase("Horas Trabajadas", Chico)) { Colspan = 2 }); tabla.AddCell(new PdfPCell(new Phrase("Autorizaciones", Chico))); // Segunda lìnea cabecera //tabla.AddCell(new PdfPCell(new Phrase("Rut", Chico))); //tabla.AddCell(new PdfPCell(new Phrase("Apellidos", Chico))); //tabla.AddCell(new PdfPCell(new Phrase("Nombres", Chico))); tabla.AddCell(new PdfPCell(new Phrase("Ing.", Chico))); tabla.AddCell(new PdfPCell(new Phrase("Sal.", Chico))); tabla.AddCell(new PdfPCell(new Phrase("Ing.", Chico))); tabla.AddCell(new PdfPCell(new Phrase("Sal.", Chico))); tabla.AddCell(new PdfPCell(new Phrase("Atrasos", Chico))); tabla.AddCell(new PdfPCell(new Phrase("H.T.N.", Chico))); tabla.AddCell(new PdfPCell(new Phrase("Permisos", Chico))); foreach (var atraso in reporte) { TimeSpan tiempoAtraso = (atraso.Salida.HasValue && atraso.Entrada.HasValue ? atraso.Salida.Value.Subtract(atraso.Entrada.Value) : new TimeSpan(0)) - (atraso.SalidaTeorica.HasValue && atraso.EntradaTeorica.HasValue ? atraso.SalidaTeorica.Value.Subtract(atraso.EntradaTeorica.Value) : new TimeSpan(0)); TimeSpan tiempoNormal = atraso.SalidaTeorica.HasValue && atraso.EntradaTeorica.HasValue ? atraso.SalidaTeorica.Value.Subtract(atraso.EntradaTeorica.Value) : new TimeSpan(0); tabla.AddCell(new PdfPCell(new Phrase(atraso.Fecha.Value.ToString("ddd dd/MM"), Chico)) { HorizontalAlignment = Element.ALIGN_LEFT }); //tabla.AddCell(new PdfPCell(new Phrase(atraso.Rut.ToStringConGuion(), Chico))); //tabla.AddCell(new PdfPCell(new Phrase(atraso.Apellidos, Chico))); //tabla.AddCell(new PdfPCell(new Phrase(atraso.Nombres, Chico))); tabla.AddCell(new PdfPCell(new Phrase(atraso.Entrada.HasValue ? atraso.Entrada.Value.ToString("HH:mm") : String.Empty, Chico))); tabla.AddCell(new PdfPCell(new Phrase(atraso.Salida.HasValue ? atraso.Salida.Value.ToString("HH:mm") : String.Empty, Chico))); tabla.AddCell(new PdfPCell(new Phrase(atraso.EntradaTeorica.HasValue ? atraso.EntradaTeorica.Value.ToString("HH:mm") : String.Empty, Chico))); tabla.AddCell(new PdfPCell(new Phrase(atraso.SalidaTeorica.HasValue ? atraso.SalidaTeorica.Value.ToString("HH:mm") : String.Empty, Chico))); tabla.AddCell(new PdfPCell(new Phrase(atraso.printAtraso, Chico))); tabla.AddCell(new PdfPCell(new Phrase("", Chico))); tabla.AddCell(new PdfPCell(new Phrase(atraso.Observacion, Chico))); } tabla.AddCell(new PdfPCell(new Phrase("Total", ChicoNegrita)) { Colspan=5 }); //TODO: aqí va la suma de astrasos tabla.AddCell(new PdfPCell(new Phrase(reporte.CalculaAtrasoEntrada(), Chico))); //TODO: aqí va la suma de H.T.N. tabla.AddCell(new PdfPCell(new Phrase("", Chico))); tabla.AddCell(new PdfPCell(new Phrase("", Chico))); doc.Add(tabla); doc.NewPage(); } doc.Close(); _Archivo = ms.ToArray(); } } }
private void generateReport() { try { String equipmentName = ""; document = new Document(PageSize.LETTER); String FilePath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory) + "\\Resources\\" + inspectionType.Text + "_" + DateTime.Today.ToString("yyyy-MM-dd") +".pdf"; PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(FilePath, FileMode.OpenOrCreate)); document.Open(); document.AddTitle("Report"); document.AddSubject("Equipment Report"); document.AddKeywords("Csharp, PDF, iText"); document.AddAuthor(""); document.AddCreator(""); iTextSharp.text.Image pdfLogo = iTextSharp.text.Image.GetInstance(AppDomain.CurrentDomain.BaseDirectory + "\\Resources\\" + "logo.JPG"); pdfLogo.Alignment = iTextSharp.text.Image.ALIGN_RIGHT; pdfLogo.ScaleAbsolute(150, 85); document.Add(pdfLogo); Paragraph preface = new Paragraph("Fire-Alert" + "\n" + "Report of " + inspectionType.Text + "\n", TimesTitle); preface.Alignment = Element.ALIGN_CENTER; document.Add(preface); document.Add(new Paragraph(" ")); #region Inspection table PdfPTable inspectionTable = new PdfPTable(1); if (inspectionType.Text.Contains("Extinguisher")) equipmentName = "Extinguisher"; else if (inspectionType.Text.Contains("Hose")) equipmentName = "FireHoseCabinet"; else if (inspectionType.Text.Contains("Light")) equipmentName = "EmergencyLight"; // Load XML inspection file from resources string url = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory) + "\\Resources\\inspection.xml"; XmlDocument doc = new System.Xml.XmlDocument(); doc.Load(url); XmlElement docElement = doc.DocumentElement; // loop through all childNodes XmlNode start = docElement.FirstChild; // franchisee foreach (XmlNode c1 in start) // contracts { foreach (XmlNode c2 in c1.ChildNodes) // addresses { // Skip if not matching contract ID if (Convert.ToInt32(c2.Attributes["id"].InnerText) == Convert.ToInt32(addressBox.SelectedValue)) { Console.WriteLine(Convert.ToInt32(c1.Attributes["id"].InnerText)); Console.WriteLine(Convert.ToInt32(addressBox.SelectedValue)); #region Address info table PdfPTable addrTable = new PdfPTable(4); addrTable.HorizontalAlignment = Element.ALIGN_LEFT; addrTable.TotalWidth = 530f; addrTable.LockedWidth = true; float[] addrWidths = new float[] { 50f, 100f, 50f, 100f }; addrTable.SetWidths(addrWidths); XmlAttributeCollection billTo = c1.ParentNode.Attributes; XmlAttributeCollection location = c2.Attributes; string[] billToAddr = billTo["address"].InnerText.Split(','); addCell(addrTable, "Bill To:", 1, 1, 0, BaseColor.WHITE, Times, PdfPCell.ALIGN_RIGHT); addCell(addrTable, billTo["name"].InnerText, 1, 1, 0, BaseColor.WHITE, TimesRegular, PdfPCell.ALIGN_LEFT); addCell(addrTable, "Location:", 1, 1, 0, BaseColor.WHITE, Times, PdfPCell.ALIGN_RIGHT); addCell(addrTable, location["contact"].InnerText, 1, 1, 0, BaseColor.WHITE, TimesRegular, PdfPCell.ALIGN_LEFT); addCell(addrTable, " ", 1, 1, 0, BaseColor.WHITE, Times, PdfPCell.ALIGN_RIGHT); addCell(addrTable, billToAddr[0], 1, 1, 0, BaseColor.WHITE, TimesRegular, PdfPCell.ALIGN_LEFT); addCell(addrTable, " ", 1, 1, 0, BaseColor.WHITE, Times, PdfPCell.ALIGN_RIGHT); addCell(addrTable, location["address"].InnerText, 1, 1, 0, BaseColor.WHITE, TimesRegular, PdfPCell.ALIGN_LEFT); addCell(addrTable, " ", 1, 1, 0, BaseColor.WHITE, Times, PdfPCell.ALIGN_RIGHT); addCell(addrTable, billToAddr[2] + "," + billToAddr[1], 1, 1, 0, BaseColor.WHITE, TimesRegular, PdfPCell.ALIGN_LEFT); addCell(addrTable, " ", 1, 1, 0, BaseColor.WHITE, Times, PdfPCell.ALIGN_RIGHT); addCell(addrTable, location["city"].InnerText, 1, 1, 0, BaseColor.WHITE, TimesRegular, PdfPCell.ALIGN_LEFT); addCell(addrTable, " ", 1, 1, 0, BaseColor.WHITE, Times, PdfPCell.ALIGN_RIGHT); addCell(addrTable, billToAddr[3], 1, 1, 0, BaseColor.WHITE, TimesRegular, PdfPCell.ALIGN_LEFT); addCell(addrTable, " ", 1, 1, 0, BaseColor.WHITE, Times, PdfPCell.ALIGN_RIGHT); addCell(addrTable, location["postalCode"].InnerText, 1, 1, 0, BaseColor.WHITE, TimesRegular, PdfPCell.ALIGN_LEFT); addCell(addrTable, "Tel:", 2, 1, 0, BaseColor.WHITE, Times, PdfPCell.ALIGN_RIGHT); addCell(addrTable, new Franchisee().getAddress(Convert.ToInt32(start.Attributes["id"].InnerText))[0], 2, 1, 0, BaseColor.WHITE, TimesRegular, PdfPCell.ALIGN_LEFT); String clientInfo = new Client().get(new ClientContract().getClient(addressBox.SelectedValue.ToString())); String[] client = new String[9]; client = clientInfo.Split(','); if (client.Length < 6) client = new String[6] {"", "", "", "", "", "No client found" }; addCell(addrTable, "Contact:", 1, 1, 0, BaseColor.WHITE, Times, PdfPCell.ALIGN_RIGHT); addCell(addrTable, client[5], 1, 1, 0, BaseColor.WHITE, TimesRegular, PdfPCell.ALIGN_LEFT); addCell(addrTable, "Tel:", 1, 1, 0, BaseColor.WHITE, Times, PdfPCell.ALIGN_RIGHT); addCell(addrTable, client[3], 1, 1, 0, BaseColor.WHITE, TimesRegular, PdfPCell.ALIGN_LEFT); addCell(addrTable, " ", 4, 4, 0, BaseColor.WHITE, TimesRegular, PdfPCell.ALIGN_LEFT); string technicianID = c2.Attributes["InspectorID"].InnerText; string technicianName = new Users().getName(Convert.ToInt32(technicianID)); if (technicianName == null || technicianName == "") technicianName = "Technician Not Found"; addCell(addrTable, "Technician: ", 2, 1, 0, BaseColor.WHITE, Times, PdfPCell.ALIGN_RIGHT); addCell(addrTable, technicianName, 2, 1, 0, BaseColor.WHITE, TimesRegular, PdfPCell.ALIGN_LEFT); addCell(addrTable, "Date: ", 2, 1, 0, BaseColor.WHITE, Times, PdfPCell.ALIGN_RIGHT); addCell(addrTable, DateTime.Now.ToString("MMMM d, yyyy"), 2, 1, 0, BaseColor.WHITE, TimesRegular, PdfPCell.ALIGN_LEFT); for (int i = 0; i < addrTable.Rows.Count; i++) for (int j = 0; j < addrTable.Rows[i].GetCells().Length; j++) { if (addrTable.Rows[i].GetCells()[j] == null) continue; if (j % 2 != 0) // Add bottom border to info cells addrTable.Rows[i].GetCells()[j].Border = iTextSharp.text.Rectangle.BOTTOM_BORDER; else // Remove bottom border from titles addrTable.Rows[i].GetCells()[j].Border = iTextSharp.text.Rectangle.NO_BORDER; } #endregion document.Add(addrTable); foreach (XmlNode c3 in c2.ChildNodes) // floors { foreach (XmlNode c4 in c3.ChildNodes) //rooms { bool isFirstEquipment = true; int itemNum = 1; foreach (XmlNode c5 in c4.ChildNodes) // equipment { if (c5.Name.Equals(equipmentName)) { #region Set up header if (isFirstEquipment) // Set up table header based on first piece of equipment { isFirstEquipment = false; inspectionTable = new PdfPTable(c5.Attributes.Count + c5.ChildNodes.Count + 1); inspectionTable.HorizontalAlignment = 0; inspectionTable.TotalWidth = 530f; inspectionTable.LockedWidth = true; float []iWidths = new float[c5.Attributes.Count + c5.ChildNodes.Count + 1]; iWidths[0] = 20f; for (int i = 1; i < iWidths.Length; i++) { if (i < c5.Attributes.Count + 1) iWidths[i] = 35f; else iWidths[i] = 20f; } inspectionTable.SetWidths(iWidths); createHeader(inspectionTable, c5); } #endregion addEquipmentRow(inspectionTable, c5, itemNum); itemNum++; } } } } } } } document.Add(new Paragraph(" ")); document.Add(inspectionTable); #endregion document.Close(); } catch (Exception ex) { MessageBox.Show("Could not display the document because " + ex.ToString()); } }
private void generate_Click(object sender, EventArgs e) { int cena = Int32.Parse(cena_txt.Text); int zadatek = Int32.Parse(zadatek_txt.Text); int pozostala = cena - zadatek; var desktopFolder = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); var fullFileName = Path.Combine(desktopFolder, "umowa.pdf"); FileStream fs = new FileStream(fullFileName, FileMode.Create, FileAccess.Write, FileShare.None); iTextSharp.text.Font timesBoldItalic = FontFactory.GetFont(FontFactory.TIMES_BOLDITALIC, BaseFont.CP1250, 11); iTextSharp.text.Font timesBold = FontFactory.GetFont(FontFactory.TIMES_BOLD, BaseFont.CP1250, 11); iTextSharp.text.Font times = FontFactory.GetFont(FontFactory.TIMES, BaseFont.CP1250, 11); Document doc = new Document(PageSize.A4, 40, 40, 20, 40); PdfWriter writer = PdfWriter.GetInstance(doc, fs); iTextSharp.text.Image flisy_1 = iTextSharp.text.Image.GetInstance("flisy_01.png"); doc.Open(); doc.SetMargins(40f, 40f, 40f, 40f); doc.AddTitle("Umowa Flisy"); doc.AddAuthor("Flisy"); // first image flisy_1.ScaleToFit(600f, 70f); flisy_1.Alignment = Element.ALIGN_CENTER; doc.Add(flisy_1); Paragraph title = new Paragraph("UMOWA O DZIEŁO", timesBoldItalic); title.Alignment = Element.ALIGN_CENTER; doc.Add(title); // &0 var zero_ph = new Phrase(); zero_ph.Add(new Chunk("Zawarta w dniu ", times)); zero_ph.Add(new Chunk(data_txt.Text, timesBold)); zero_ph.Add(new Chunk(" pomiędzy zespołem muzycznym FLISY reprezentowanym przez Arkadiusza Olka zamieszkałym w Gorzowie Wlkp.ul.Wiedeńska 1i / 15 zwanym w treści umowy wykonawcą, a organizatorem imprezy czyli ", times)); zero_ph.Add(new Chunk(zlece_txt.Text, timesBold)); zero_ph.Add(new Chunk(" zamieszkałym ", times)); zero_ph.Add(new Chunk(adr_zlece_txt.Text, timesBold)); zero_ph.Add(new Chunk(" zwanym w treści umowy zamawiającym.", times)); Paragraph zero = new Paragraph(zero_ph); zero.Alignment = Element.ALIGN_JUSTIFIED; zero.SetLeading(0.0f, 1.5f); doc.Add(zero); // &1 Paragraph one_amp = new Paragraph("&1", timesBold); one_amp.Alignment = Element.ALIGN_CENTER; one_amp.SetLeading(0.0f, 1.5f); doc.Add(one_amp); var one_ph = new Phrase(); one_ph.Add(new Chunk("Zamawiający zamawia wykonanie a wykonawca zobowiązuje się wykonać dzieło polegające na: \na) oprawie muzyczno - wokalnej uroczystości weselnej \nb) oprawie muzyczno-wokalnej uroczystości weselnej wraz z poprawinami \nc) oprawie muzyczno-wokalnej imprezy", times)); Paragraph one = new Paragraph(one_ph); one.Alignment = Element.ALIGN_JUSTIFIED; one.SetLeading(0.0f, 1.5f); doc.Add(one); // &2 Paragraph two_amp = new Paragraph("&2", timesBold); two_amp.Alignment = Element.ALIGN_CENTER; two_amp.SetLeading(0.0f, 1.5f); doc.Add(two_amp); var two_ph = new Phrase(); two_ph.Add(new Chunk("W terminie dnia ", times)); two_ph.Add(new Chunk(termin_txt.Text, timesBold)); two_ph.Add(new Chunk(" od godz. 16:00 do godz. 4:00 w miejscu ", times)); two_ph.Add(new Chunk(miejsce_txt.Text, timesBold)); two_ph.Add(new Chunk(".", times)); Paragraph two = new Paragraph(two_ph); two.Alignment = Element.ALIGN_JUSTIFIED; two.SetLeading(0.0f, 1.5f); doc.Add(two); // &3 Paragraph three_amp = new Paragraph("&3", timesBold); three_amp.Alignment = Element.ALIGN_CENTER; three_amp.SetLeading(0.0f, 1.5f); doc.Add(three_amp); var three_ph = new Phrase(); three_ph.Add(new Chunk("Za wykonanie dzieła zamawiający wypłaci wykonawcy wynagrodzenie w wysokości ", times)); three_ph.Add(new Chunk(cena_txt.Text + ",00", timesBold)); three_ph.Add(new Chunk(" słownie ", times)); three_ph.Add(new Chunk(String.Format("{0} {1}", Formatowanie.LiczbaSlownie(cena), Formatowanie.WalutaSlownie(cena, "PLN")), timesBold)); three_ph.Add(new Chunk(".", times)); Paragraph three = new Paragraph(three_ph); three.Alignment = Element.ALIGN_JUSTIFIED; three.SetLeading(0.0f, 1.5f); doc.Add(three); // &4 Paragraph four_amp = new Paragraph("&4", timesBold); four_amp.Alignment = Element.ALIGN_CENTER; four_amp.SetLeading(0.0f, 1.5f); doc.Add(four_amp); var four_ph = new Phrase(); four_ph.Add(new Chunk("Zadatek w kwocie ", times)); four_ph.Add(new Chunk(zadatek_txt.Text + ",00", timesBold)); four_ph.Add(new Chunk(" słownie ", times)); four_ph.Add(new Chunk(String.Format("{0} {1}", Formatowanie.LiczbaSlownie(zadatek), Formatowanie.WalutaSlownie(zadatek, "PLN")), timesBold)); four_ph.Add(new Chunk(" pobrano w dniu sporządzenia umowy. Do uregulowania pozostaje kwota ", times)); four_ph.Add(new Chunk(pozostala.ToString() + ",00", timesBold)); four_ph.Add(new Chunk(" słownie ", times)); four_ph.Add(new Chunk(String.Format("{0} {1}", Formatowanie.LiczbaSlownie(pozostala), Formatowanie.WalutaSlownie(pozostala, "PLN")), timesBold)); four_ph.Add(new Chunk(" która wypłacona będzie bezpośrednio po zakończeniu imprezy.", times)); Paragraph four = new Paragraph(four_ph); four.Alignment = Element.ALIGN_JUSTIFIED; four.SetLeading(0.0f, 1.5f); doc.Add(four); // &5 Paragraph five_amp = new Paragraph("&5", timesBold); five_amp.Alignment = Element.ALIGN_CENTER; five_amp.SetLeading(0.0f, 1.5f); doc.Add(five_amp); var five_ph = new Phrase(); five_ph.Add(new Chunk("Wykonawca nie może powierzyć dzieła innym osobom bez zgody zamawiającego. ", times)); Paragraph five = new Paragraph(five_ph); five.Alignment = Element.ALIGN_JUSTIFIED; five.SetLeading(0.0f, 1.5f); doc.Add(five); // &6 Paragraph six_amp = new Paragraph("&6", timesBold); six_amp.Alignment = Element.ALIGN_CENTER; six_amp.SetLeading(0.0f, 1.5f); doc.Add(six_amp); var six_ph = new Phrase(); six_ph.Add(new Chunk("Zamawiający jest jednocześnie organizatorem imprezy. ", times)); Paragraph six = new Paragraph(six_ph); six.Alignment = Element.ALIGN_JUSTIFIED; six.SetLeading(0.0f, 1.5f); doc.Add(six); // &7 Paragraph seven_amp = new Paragraph("&7", timesBold); seven_amp.Alignment = Element.ALIGN_CENTER; seven_amp.SetLeading(0.0f, 1.5f); doc.Add(seven_amp); var seven_ph = new Phrase(); seven_ph.Add(new Chunk("Zamawiający ponosi odpowiedzialność materialną za zniszczenie lub uszkodzenie sprzętu powstałe z winy osób nie będących członkami zespołu.", times)); Paragraph seven = new Paragraph(seven_ph); seven.Alignment = Element.ALIGN_JUSTIFIED; seven.SetLeading(0.0f, 1.5f); doc.Add(seven); // &8 Paragraph eight_amp = new Paragraph("&8", timesBold); eight_amp.Alignment = Element.ALIGN_CENTER; eight_amp.SetLeading(0.0f, 1.5f); doc.Add(eight_amp); var eight_ph = new Phrase(); eight_ph.Add(new Chunk("W przypadku rozwiązania umowy przez zamawiającego, zadatek przechodzi na rzecz wykonawcy. ", times)); Paragraph eight = new Paragraph(eight_ph); eight.Alignment = Element.ALIGN_JUSTIFIED; eight.SetLeading(0.0f, 1.5f); doc.Add(eight); // &9 Paragraph nine_amp = new Paragraph("&9", timesBold); nine_amp.Alignment = Element.ALIGN_CENTER; nine_amp.SetLeading(0.0f, 1.5f); doc.Add(nine_amp); var nine_ph = new Phrase(); nine_ph.Add(new Chunk("W przypadku rozwiązania umowy przez wykonawcę, zadatek w podwójnej wysokości przechodzi na rzecz zamawiającego.", times)); Paragraph nine = new Paragraph(nine_ph); nine.Alignment = Element.ALIGN_JUSTIFIED; nine.SetLeading(0.0f, 1.5f); doc.Add(nine); // &10 Paragraph ten_amp = new Paragraph("&10", timesBold); ten_amp.Alignment = Element.ALIGN_CENTER; ten_amp.SetLeading(0.0f, 1.5f); doc.Add(ten_amp); var ten_ph = new Phrase(); ten_ph.Add(new Chunk("W sprawach nie uregulowanych niniejszą umową mają zastosowanie przepisy kodeksu cywilnego.", times)); Paragraph ten = new Paragraph(ten_ph); ten.Alignment = Element.ALIGN_JUSTIFIED; ten.SetLeading(0.0f, 1.5f); doc.Add(ten); // &11 Paragraph eleven_amp = new Paragraph("&11", timesBold); eleven_amp.Alignment = Element.ALIGN_CENTER; eleven_amp.SetLeading(0.0f, 1.5f); doc.Add(eleven_amp); var eleven_ph = new Phrase(); eleven_ph.Add(new Chunk("Umowę sporządzono w dwóch jednobrzmiących egzemplarzach, po jednym dla każdej ze stron.", times)); Paragraph eleven = new Paragraph(eleven_ph); eleven.Alignment = Element.ALIGN_JUSTIFIED; eleven.SetLeading(0.0f, 1.5f); doc.Add(eleven); // signatures var signatures_ph = new Phrase(); signatures_ph.Add(new Chunk("\n\n (zamawiający) (wykonawca) ", times)); Paragraph signatures = new Paragraph(signatures_ph); signatures.Alignment = Element.ALIGN_JUSTIFIED; doc.Add(signatures); doc.Close(); System.Windows.Forms.MessageBox.Show("Umowa została wygenerowana."); }
//Export PDF des statistiques public ActionResult PDF() { List<Stat> stats = context.Stats.OrderBy(i => i.form.Title).ToList(); //Appel fonction tri stats ArrayList listStats = EnleveDoublonPlusComptage(stats); //Si erreur, redirection page erreur if(listStats == null) { RedirectToAction("Error", "Shared", ""); } Document myDocument = new Document(PageSize.A4); PdfWriter.GetInstance(myDocument, new FileStream("C:\\wamp\\www\\FormOnline\\FormOnline\\docs\\Export.pdf", FileMode.Create)); myDocument.Open(); #region Entetes myDocument.AddAuthor("FormOnline"); myDocument.AddCreationDate(); myDocument.AddTitle("Export PDF des statistiques"); #endregion PdfPTable table = new PdfPTable(4); //Entetes table PdfPCell cell = new PdfPCell(new Phrase("Export PDF des statistiques")); cell.Colspan = 4; cell.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right cell.BackgroundColor = BaseColor.LIGHT_GRAY; table.AddCell(cell); table.AddCell("Formulaire"); table.AddCell("Question"); table.AddCell("Réponse"); table.AddCell("Nb"); int cpt = 0; //Pour chaque stats foreach (object[] obj in listStats) { PdfPCell cellF = new PdfPCell(new Phrase(obj[0].ToString())); PdfPCell cellQ = new PdfPCell(new Phrase(obj[1].ToString())); PdfPCell cellA = new PdfPCell(new Phrase(obj[2].ToString())); PdfPCell cellNb = new PdfPCell(new Phrase(obj[3].ToString())); //Effet de style 1 ligne sur 2 if (cpt % 2 == 0) { cellF.BackgroundColor = BaseColor.LIGHT_GRAY; cellQ.BackgroundColor = BaseColor.LIGHT_GRAY; cellA.BackgroundColor = BaseColor.LIGHT_GRAY; cellNb.BackgroundColor = BaseColor.LIGHT_GRAY; } table.AddCell(cellF); table.AddCell(cellQ); table.AddCell(cellA); table.AddCell(cellNb); cpt++; } myDocument.Add(table); myDocument.Close(); ViewData["listStats"] = listStats; //Retourne à la page index des stats return View("Index",stats); }
private void button1_Click(object sender, EventArgs e) { if (openFile1.SafeFileName == "" || openFile2.SafeFileName == "") { MessageBox.Show("No haz seleccionado ningún PDF", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } MessageBox.Show("Se unira \"" + openFile1.SafeFileName + "\" con \"" + openFile2.SafeFileName + "\""); saveFile.Filter = "Adobe Acrobat Document PDF (*.pdf)|*.pdf"; saveFile.FilterIndex = 1; if (saveFile.ShowDialog() == DialogResult.OK) { MessageBox.Show("Se guardara en la siguiente ruta:\n" + saveFile.FileName); FileStream myStream = new FileStream(saveFile.FileName,FileMode.OpenOrCreate); PdfReader reader = new PdfReader(openFile1.FileName); PdfReader reader2 = new PdfReader(openFile2.FileName); Document document = new Document(reader.GetPageSizeWithRotation(1)); PdfCopy writer = new PdfCopy(document, myStream); document.Open(); document.AddCreationDate(); if (txtAutor.Text != null) { document.AddAuthor(txtAutor.Text); } if (txtHeader.Text != null) { document.AddHeader(txtHeader.Text, "Document"); } if (txtKeywords.Text != null) { document.AddKeywords(txtKeywords.Text); } document.AddProducer(); if (txtTitulo.Text != null) { document.AddTitle(txtTitulo.Text); } // Calculando incremento progressBar.Refresh(); int incremento = (int)(100 / (reader.NumberOfPages + reader2.NumberOfPages)); MessageBox.Show("Incremento es: " + incremento); for (int i = 1; i <= reader.NumberOfPages; i++) { writer.AddPage(writer.GetImportedPage(reader, i)); progressBar.PerformStep(); progressBar.Increment(++incremento); } progressBar.Increment(50); for (int i = 1; i <= reader2.NumberOfPages; i++) { writer.AddPage(writer.GetImportedPage(reader2, i)); progressBar.PerformStep(); } progressBar.Increment(100); document.Close(); } }
/// <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); }
void CreateRem() { string namefile = comboBox1.Text + "-Рем.pdf"; //var Документ = new iTextSharp.text.Document(); var Документ = new Document(); //создаем pdf документ iTextSharp.text. var Писатель = PdfWriter.GetInstance(Документ, new System.IO.FileStream(namefile, System.IO.FileMode.Create)); // в текущем каталоге, если файл есть - создаст новый Документ.SetPageSize(PageSize.A4.Rotate()); Документ.AddAuthor("Безверхий О.А."); Документ.AddTitle("Отчёт"); Документ.AddCreator("Программа учёта ТО и Ремонта"); Документ.Open(); //Rectangle rec2 = new Rectangle(PageSize.A4); //var БазовыйШрифт = BaseFont.CreateFont(@"C:\WINDOWS\Fonts\comic.ttf", "CP1251", BaseFont.EMBEDDED); var БазовыйШрифт = BaseFont.CreateFont(@"C:\WINDOWS\Fonts\times.ttf", "CP1251", BaseFont.EMBEDDED); var Шрифт = new Font(БазовыйШрифт, 12, iTextSharp.text.Font.NORMAL); Paragraph para = new Paragraph("КАРТА УЧЕТА РЕМОНТА " + comboBox2.Text.ToUpper() + "\n", Шрифт); para.Alignment = Element.ALIGN_CENTER; Документ.Add(para); para = new Paragraph(label2.Text, Шрифт); para.Alignment = Element.ALIGN_LEFT; Документ.Add(para); /*para = new Paragraph("МАРКА: КЗС-1218-40 гос. № А283БВ 28rus инв. № 27" + "\n", Шрифт); para.Alignment = Element.ALIGN_LEFT; Документ.Add(para); para = new Paragraph("МЕХАНИЗАТОР: Вася Петя" + "\n\n", Шрифт); Документ.Add(para);*/ /**/ para = new Paragraph("" + "\n", Шрифт); Документ.Add(para); /*var Tabla = new PdfPTable(6); Документ.Add(Tabla);*/ PdfPTable table = new PdfPTable(dataGridView1.Columns.Count); for (int j = 0; j < dataGridView1.Columns.Count; j++) { table.AddCell(new Phrase(dataGridView1.Columns[j].HeaderText, Шрифт)); } table.HeaderRows = 1; for (int i = 0; i < dataGridView1.Rows.Count; i++) { for (int k = 0; k < dataGridView1.Columns.Count; k++) { if (dataGridView1[k, i].Value != null) { table.AddCell(new Phrase(dataGridView1[k, i].Value.ToString(), Шрифт)); } } } Документ.Add(table); para = new Paragraph("" + "\n", Шрифт); Документ.Add(para); para = new Paragraph("Подпись руководителя: ", Шрифт); para.Alignment = Element.ALIGN_LEFT; Документ.Add(para); //Документ.Add(new iTextSharp.text.Paragraph("Текст после таблицы", Шрифт)); Документ.Close(); Писатель.Close(); System.Diagnostics.Process.Start(namefile); }
public static string generarPdf(Hashtable htFacturaxion, HttpContext hc) { string pathPdf = htFacturaxion["rutaDocumentoPdf"].ToString(); FileStream fs = new FileStream(pathPdf, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite); try { StringBuilder sbConfigFact = new StringBuilder(); StringBuilder sbConfigFactParms = new StringBuilder(); _ci.NumberFormat.CurrencyDecimalDigits = 2; DAL dal = new DAL(); ElectronicDocument electronicDocument = (ElectronicDocument)htFacturaxion["electronicDocument"]; Data objTimbre = (Data)htFacturaxion["objTimbre"]; bool timbrar = Convert.ToBoolean(htFacturaxion["timbrar"]); //string pathPdf = htFacturaxion["rutaDocumentoPdf"].ToString(); // Obtenemos el logo y plantilla StringBuilder sbLogo = new StringBuilder(); sbLogo. Append("SELECT S.rutaLogo, P.rutaEncabezado, P.rutaFooter "). Append("FROM sucursales S "). Append("LEFT OUTER JOIN tipoPlantillas P ON S.idTipoPlantilla = P.idTipoPlantilla AND P.ST = 1 "). Append("WHERE idSucursal = @0 AND S.ST = 1"); DataTable dtLogo = dal.QueryDT("DS_FE", sbLogo.ToString(), "F:I:" + htFacturaxion["idSucursalEmisor"], hc); string rutaLogo = dtLogo.Rows[0]["rutaLogo"].ToString(); string rutaHeader = dtLogo.Rows[0]["rutaEncabezado"].ToString(); string rutaFooter = dtLogo.Rows[0]["rutaFooter"].ToString(); //Obtenemos Rol de la empresa StringBuilder sbRol = new StringBuilder(); sbRol. Append("DECLARE @iduser INT; "). Append("SELECT DISTINCT @iduser = UxR.idUser FROM sucursales S "). Append("LEFT OUTER JOIN sucursalesXUsuario SxU ON S.idSucursal = SxU.idSucursal LEFT OUTER JOIN r3TakeCore.dbo.SYS_UserXRol UxR ON UxR.idUser = SxU.idUser "). Append("WHERE idEmpresa = @0 AND UxR.idRol IN(22,15) AND S.ST = 1 AND SxU.ST = 1; "). Append("SELECT UxR.idRol FROM r3TakeCore.dbo.SYS_UserXRol UxR WHERE idUser = @idUser"); //Rol 15 > MIT ; 22 > Facturizate int idRol = dal.ExecuteScalar("DS_FE", sbRol.ToString(), "F:S:" + htFacturaxion["idEmisor"], hc); sbConfigFactParms. Append("F:I:").Append(Convert.ToInt64(htFacturaxion["idSucursalEmisor"])). Append(";"). Append("F:I:").Append(Convert.ToInt32(htFacturaxion["tipoComprobante"])). Append(";"). Append("F:S:").Append(electronicDocument.Data.Total.Value). Append(";"). Append("F:I:").Append(Convert.ToInt32(htFacturaxion["idMoneda"])). Append(";"). Append("F:S:").Append(rutaLogo). Append(";"). Append("F:S:").Append(rutaHeader). Append(";"). Append("F:S:").Append(rutaFooter). Append(";"). Append("F:I:").Append(Convert.ToInt64(htFacturaxion["idEmisor"])); if (idRol == 15) { if (rutaHeader.Length > 0) { sbConfigFact. Append("SELECT @5 AS rutaTemplateHeader, @6 AS rutaTemplateFooter, @4 AS rutaLogo, objDesc, posX, posY, fontSize, dbo.convertNumToTextFunction( @2, @3) AS cantidadLetra, "). Append("logoPosX, logoPosY, headerPosX, headerPosY, footerPosX, footerPosY, conceptosColWidth, desgloseColWidth "). Append("FROM configuracionFacturas CF "). Append("LEFT OUTER JOIN sucursales S ON S.idSucursal = @0 "). Append("LEFT OUTER JOIN configuracionFactDet CFD ON CF.idConFact = CFD.idConFact "). Append("WHERE CF.ST = 1 AND CF.idEmpresa = -1 AND CF.idTipoComp = @1 AND idCFDProcedencia = 1 AND objDesc NOT LIKE 'nuevoLbl%' "); } else { sbConfigFact. Append("SELECT rutaTemplateHeader, rutaTemplateFooter, @4 AS rutaLogo, objDesc, posX, posY, fontSize, dbo.convertNumToTextFunction( @2, @3) AS cantidadLetra, "). Append("logoPosX, logoPosY, headerPosX, headerPosY, footerPosX, footerPosY, conceptosColWidth, desgloseColWidth "). Append("FROM configuracionFacturas CF "). Append("LEFT OUTER JOIN sucursales S ON S.idSucursal = @0 "). Append("LEFT OUTER JOIN configuracionFactDet CFD ON CF.idConFact = CFD.idConFact "). Append("WHERE CF.ST = 1 AND CF.idEmpresa = -1 AND CF.idTipoComp = @1 AND idCFDProcedencia = 1 AND objDesc NOT LIKE 'nuevoLbl%' "); } } else { sbConfigFact. Append("DECLARE @idEmpresa AS INT;"). Append("IF EXISTS (SELECT * FROM configuracionFacturas WHERE idEmpresa = @7) "). Append("SET @idEmpresa = @7; "). Append("ELSE "). Append("SET @idEmpresa = 0; "). Append("SELECT rutaTemplateHeader, rutaTemplateFooter, S.rutaLogo, objDesc, posX, posY, fontSize, dbo.convertNumToTextFunction( @2, @3) AS cantidadLetra, "). Append("logoPosX, logoPosY, headerPosX, headerPosY, footerPosX, footerPosY, conceptosColWidth, desgloseColWidth, S.nombreSucursal "). Append("FROM configuracionFacturas CF "). Append("LEFT OUTER JOIN sucursales S ON S.idSucursal = @0 "). Append("LEFT OUTER JOIN configuracionFactDet CFD ON CF.idConFact = CFD.idConFact "). Append("WHERE CF.ST = 1 AND CF.idEmpresa = @idEmpresa AND CF.idTipoComp = @1 AND idCFDProcedencia = 1 AND objDesc NOT LIKE 'nuevoLbl%' "); } DataTable dtConfigFact = dal.QueryDT("DS_FE", sbConfigFact.ToString(), sbConfigFactParms.ToString(), hc); // Creamos el Objeto Documento Document document = new Document(PageSize.LETTER, 25, 25, 25, 25); document.AddAuthor("Facturaxion"); document.AddCreator("r3Take"); document.AddCreationDate(); //FileStream fs = new FileStream(pathPdf, FileMode.Create); //FileStream fs = new FileStream(pathPdf, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite); PdfWriter writer = PdfWriter.GetInstance(document, fs); writer.SetPdfVersion(PdfWriter.PDF_VERSION_1_7); Chunk cSaltoLinea = new Chunk("\n"); Chunk cLineaSpace = new Chunk(cSaltoLinea + "________________________________________________________________________________________________________________________________________________________________________", new Font(Font.HELVETICA, 6, Font.BOLD)); Chunk cLineaDiv = new Chunk(cSaltoLinea + "________________________________________________________________________________________________________________________________________________________________________" + cSaltoLinea, new Font(Font.HELVETICA, 6, Font.BOLD)); Chunk cDataSpacer = new Chunk(" | ", new Font(Font.HELVETICA, 6, Font.BOLD)); BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); document.Open(); PdfContentByte cb = writer.DirectContent; cb.BeginText(); // Almacenamos en orden los objetos del Electronic Document para posteriormente añadidos al documento #region "Armamos las etiquetas que tienen posiciones absolutas para ser insertadas en el documento" Hashtable htDatosCfdi = new Hashtable(); // Armamos las direcciones #region "Dirección Emisor" StringBuilder sbDirEmisor1 = new StringBuilder(); StringBuilder sbDirEmisor2 = new StringBuilder(); StringBuilder sbDirEmisor3 = new StringBuilder(); if (electronicDocument.Data.Emisor.Domicilio.Calle.Value.Length > 0) { sbDirEmisor1.Append("Calle ").Append(electronicDocument.Data.Emisor.Domicilio.Calle.Value).Append(" "); } if (electronicDocument.Data.Emisor.Domicilio.NumeroExterior.Value.Length > 0) { sbDirEmisor1.Append(", No. Ext ").Append(electronicDocument.Data.Emisor.Domicilio.NumeroExterior.Value).Append(" "); } if (electronicDocument.Data.Emisor.Domicilio.NumeroInterior.Value.Length > 0) { sbDirEmisor1.Append(", No. Int ").Append(electronicDocument.Data.Emisor.Domicilio.NumeroInterior.Value); } if (electronicDocument.Data.Emisor.Domicilio.Colonia.Value.Length > 0) { sbDirEmisor2.Append("Col. ").Append(electronicDocument.Data.Emisor.Domicilio.Colonia.Value).Append(" "); } if (electronicDocument.Data.Emisor.Domicilio.CodigoPostal.Value.Length > 0) { sbDirEmisor2.Append(", C.P. ").Append(electronicDocument.Data.Emisor.Domicilio.CodigoPostal.Value).Append(" "); } if (electronicDocument.Data.Emisor.Domicilio.Localidad.Value.Length > 0) { sbDirEmisor2.Append(", ").Append(electronicDocument.Data.Emisor.Domicilio.Localidad.Value); } if (electronicDocument.Data.Emisor.Domicilio.Municipio.Value.Length > 0) { sbDirEmisor3.Append("Mpio. / Del. ").Append(electronicDocument.Data.Emisor.Domicilio.Municipio.Value).Append(" "); } if (electronicDocument.Data.Emisor.Domicilio.Estado.Value.Length > 0) { sbDirEmisor3.Append(", Estado ").Append(electronicDocument.Data.Emisor.Domicilio.Estado.Value).Append(" "); } sbDirEmisor3.Append(", ").Append(electronicDocument.Data.Emisor.Domicilio.Pais.Value); #endregion #region "Dirección Sucursal Expedido En" StringBuilder sbDirExpedido1 = new StringBuilder(); StringBuilder sbDirExpedido2 = new StringBuilder(); StringBuilder sbDirExpedido3 = new StringBuilder(); if (electronicDocument.Data.Emisor.ExpedidoEn.Calle.Value.Length > 0) { sbDirExpedido1.Append("Calle ").Append(electronicDocument.Data.Emisor.ExpedidoEn.Calle.Value).Append(" "); } if (electronicDocument.Data.Emisor.ExpedidoEn.NumeroExterior.Value.Length > 0) { sbDirExpedido1.Append(", No. Ext ").Append(electronicDocument.Data.Emisor.ExpedidoEn.NumeroExterior.Value).Append(" "); } if (electronicDocument.Data.Emisor.ExpedidoEn.NumeroInterior.Value.Length > 0) { sbDirExpedido1.Append(", No. Int ").Append(electronicDocument.Data.Emisor.ExpedidoEn.NumeroInterior.Value); } if (electronicDocument.Data.Emisor.ExpedidoEn.Colonia.Value.Length > 0) { sbDirExpedido2.Append("Col. ").Append(electronicDocument.Data.Emisor.ExpedidoEn.Colonia.Value).Append(" "); } if (electronicDocument.Data.Emisor.ExpedidoEn.CodigoPostal.Value.Length > 0) { sbDirExpedido2.Append(", C.P. ").Append(electronicDocument.Data.Emisor.ExpedidoEn.CodigoPostal.Value).Append(" "); } if (electronicDocument.Data.Emisor.ExpedidoEn.Localidad.Value.Length > 0) { sbDirExpedido2.Append(", ").Append(electronicDocument.Data.Emisor.ExpedidoEn.Localidad.Value); } if (electronicDocument.Data.Emisor.ExpedidoEn.Municipio.Value.Length > 0) { sbDirExpedido3.Append("Mpio. / Del. ").Append(electronicDocument.Data.Emisor.ExpedidoEn.Municipio.Value).Append(" "); } if (electronicDocument.Data.Emisor.ExpedidoEn.Estado.Value.Length > 0) { sbDirExpedido3.Append(", Estado ").Append(electronicDocument.Data.Emisor.ExpedidoEn.Estado.Value).Append(" "); } sbDirExpedido3.Append(", ").Append(electronicDocument.Data.Emisor.ExpedidoEn.Pais.Value); #endregion #region "Dirección Receptor" StringBuilder sbDirReceptor1 = new StringBuilder(); StringBuilder sbDirReceptor2 = new StringBuilder(); StringBuilder sbDirReceptor3 = new StringBuilder(); if (electronicDocument.Data.Receptor.Domicilio.Calle.Value.Length > 0) { sbDirReceptor1.Append("Calle ").Append(electronicDocument.Data.Receptor.Domicilio.Calle.Value).Append(" "); } if (electronicDocument.Data.Receptor.Domicilio.NumeroExterior.Value.Length > 0) { sbDirReceptor1.Append(", No. Ext ").Append(electronicDocument.Data.Receptor.Domicilio.NumeroExterior.Value).Append(" "); } if (electronicDocument.Data.Receptor.Domicilio.NumeroInterior.Value.Length > 0) { sbDirReceptor1.Append(", No. Int ").Append(electronicDocument.Data.Receptor.Domicilio.NumeroInterior.Value); } if (electronicDocument.Data.Receptor.Domicilio.Colonia.Value.Length > 0) { sbDirReceptor2.Append("Col. ").Append(electronicDocument.Data.Receptor.Domicilio.Colonia.Value).Append(" "); } if (electronicDocument.Data.Receptor.Domicilio.CodigoPostal.Value.Length > 0) { sbDirReceptor2.Append(", C.P. ").Append(electronicDocument.Data.Receptor.Domicilio.CodigoPostal.Value).Append(" "); } if (electronicDocument.Data.Receptor.Domicilio.Localidad.Value.Length > 0) { sbDirReceptor2.Append(", ").Append(electronicDocument.Data.Receptor.Domicilio.Localidad.Value); } if (electronicDocument.Data.Receptor.Domicilio.Municipio.Value.Length > 0) { sbDirReceptor3.Append("Mpio. / Del. ").Append(electronicDocument.Data.Receptor.Domicilio.Municipio.Value).Append(" "); } if (electronicDocument.Data.Receptor.Domicilio.Estado.Value.Length > 0) { sbDirReceptor3.Append(", Estado ").Append(electronicDocument.Data.Receptor.Domicilio.Estado.Value).Append(" "); } sbDirReceptor3.Append(", ").Append(electronicDocument.Data.Receptor.Domicilio.Pais.Value); #endregion htDatosCfdi.Add("rfcEmisor", electronicDocument.Data.Emisor.Rfc.Value); htDatosCfdi.Add("rfcEmpresa", electronicDocument.Data.Emisor.Rfc.Value); htDatosCfdi.Add("nombreEmisor", "Razón Social " + electronicDocument.Data.Emisor.Nombre.Value); htDatosCfdi.Add("empresa", "Razón Social " + electronicDocument.Data.Emisor.Nombre.Value); htDatosCfdi.Add("rfcReceptor", electronicDocument.Data.Receptor.Rfc.Value); htDatosCfdi.Add("rfcCliente", electronicDocument.Data.Receptor.Rfc.Value); htDatosCfdi.Add("nombreReceptor", "Razón Social " + electronicDocument.Data.Receptor.Nombre.Value); htDatosCfdi.Add("cliente", "Razón Social " + electronicDocument.Data.Receptor.Nombre.Value); htDatosCfdi.Add("sucursal", "Sucursal " + dtConfigFact.Rows[0]["nombreSucursal"]); htDatosCfdi.Add("serie", electronicDocument.Data.Serie.Value); htDatosCfdi.Add("folio", electronicDocument.Data.Folio.Value); htDatosCfdi.Add("fechaCfdi", electronicDocument.Data.Fecha.Value); htDatosCfdi.Add("fechaFactura", electronicDocument.Data.Fecha.Value); htDatosCfdi.Add("UUID", objTimbre.Uuid.Value); htDatosCfdi.Add("folioFiscal", objTimbre.Uuid.Value); htDatosCfdi.Add("direccionEmisor1", sbDirEmisor1.ToString()); htDatosCfdi.Add("direccionEmpresa1", sbDirEmisor1.ToString()); htDatosCfdi.Add("direccionEmisor2", sbDirEmisor2.ToString()); htDatosCfdi.Add("direccionEmpresa2", sbDirEmisor2.ToString()); htDatosCfdi.Add("direccionEmisor3", sbDirEmisor3.ToString()); htDatosCfdi.Add("direccionEmpresa3", sbDirEmisor3.ToString()); htDatosCfdi.Add("direccionExpedido1", sbDirExpedido1.ToString()); htDatosCfdi.Add("direccionSucursal1", sbDirExpedido1.ToString()); htDatosCfdi.Add("direccionExpedido2", sbDirExpedido2.ToString()); htDatosCfdi.Add("direccionSucursal2", sbDirExpedido2.ToString()); htDatosCfdi.Add("direccionExpedido3", sbDirExpedido3.ToString()); htDatosCfdi.Add("direccionSucursal3", sbDirExpedido3.ToString()); htDatosCfdi.Add("direccionReceptor1", sbDirReceptor1.ToString()); htDatosCfdi.Add("direccionCliente1", sbDirReceptor1.ToString()); htDatosCfdi.Add("direccionReceptor2", sbDirReceptor2.ToString()); htDatosCfdi.Add("direccionCliente2", sbDirReceptor2.ToString()); htDatosCfdi.Add("direccionReceptor3", sbDirReceptor3.ToString()); htDatosCfdi.Add("direccionCliente3", sbDirReceptor3.ToString()); // Leemos los objetos que se situaran en posiciones absolutas en el documento foreach (DataRow row in dtConfigFact.Rows) { cb.SetFontAndSize(bf, Convert.ToInt32(row["fontSize"])); cb.SetTextMatrix(Convert.ToSingle(row["posX"]), Convert.ToSingle(row["posY"])); cb.ShowText(htDatosCfdi[row["objDesc"].ToString()].ToString()); } ///////////////////////////////////////////////////////////// DataTable dtGetOptional = new DataTable(); dtGetOptional = dal.QueryDT("DS_FE", "SELECT idCFDI,campo1,campo2,campo3,campo4,campo5 FROM dbo.opcionalEncabezado WHERE idCFDI = @0", "F:I:" + htFacturaxion["idCfdi"], hc); if (dtGetOptional.Rows.Count > 0) { cb.SetFontAndSize(bf, 7); cb.SetTextMatrix(40, 606); cb.ShowText(dtGetOptional.Rows[0]["campo1"].ToString()); cb.SetFontAndSize(bf, 7); cb.SetTextMatrix(40, 597); cb.ShowText(dtGetOptional.Rows[0]["campo2"].ToString()); cb.SetFontAndSize(bf, 7); cb.SetTextMatrix(345, 615); cb.ShowText(dtGetOptional.Rows[0]["campo3"].ToString()); cb.SetFontAndSize(bf, 7); cb.SetTextMatrix(345, 606); cb.ShowText(dtGetOptional.Rows[0]["campo4"].ToString()); cb.SetFontAndSize(bf, 7); cb.SetTextMatrix(40, 597); cb.ShowText(dtGetOptional.Rows[0]["campo5"].ToString()); } //////////////////////////////////////////////////////////////////// #endregion cb.EndText(); #region "Generamos Quick Response Code" byte[] bytesQRCode = new byte[0]; if (timbrar) { // Generamos el Quick Response Code (QRCode) string re = electronicDocument.Data.Emisor.Rfc.Value; string rr = electronicDocument.Data.Receptor.Rfc.Value; string tt = String.Format("{0:F6}", electronicDocument.Data.Total.Value); string id = objTimbre.Uuid.Value; StringBuilder sbCadenaQRCode = new StringBuilder(); sbCadenaQRCode. Append("?"). Append("re=").Append(re). Append("&"). Append("rr=").Append(rr). Append("&"). Append("tt=").Append(tt). Append("&"). Append("id=").Append(id); BarcodeLib.Barcode.QRCode.QRCode barcode = new BarcodeLib.Barcode.QRCode.QRCode(); barcode.Data = sbCadenaQRCode.ToString(); barcode.ModuleSize = 3; barcode.LeftMargin = 0; barcode.RightMargin = 10; barcode.TopMargin = 0; barcode.BottomMargin = 0; barcode.Encoding = BarcodeLib.Barcode.QRCode.QRCodeEncoding.Auto; barcode.Version = BarcodeLib.Barcode.QRCode.QRCodeVersion.Auto; barcode.ECL = BarcodeLib.Barcode.QRCode.ErrorCorrectionLevel.L; bytesQRCode = barcode.drawBarcodeAsBytes(); } #endregion #region "Header" //Agregando Imagen de Encabezado de Página Image imgHeader = Image.GetInstance(dtConfigFact.Rows[0]["rutaTemplateHeader"].ToString()); imgHeader.ScalePercent(47f); double posXH = Convert.ToDouble(dtConfigFact.Rows[0]["headerPosX"].ToString()); double posYH = Convert.ToDouble(dtConfigFact.Rows[0]["headerPosY"].ToString()); double PXH = posXH; double PYH = posYH; imgHeader.SetAbsolutePosition(Convert.ToSingle(PXH), Convert.ToSingle(PYH)); document.Add(imgHeader); #endregion #region "Logotipo" //Agregando Imagen de Logotipo Image imgLogo = Image.GetInstance(dtConfigFact.Rows[0]["rutaLogo"].ToString()); float imgLogoWidth = 100; float imgLogoHeight = 50; imgLogo.ScaleAbsolute(imgLogoWidth, imgLogoHeight); imgLogo.SetAbsolutePosition(Convert.ToSingle(dtConfigFact.Rows[0]["logoPosX"]), Convert.ToSingle(dtConfigFact.Rows[0]["logoPosY"])); document.Add(imgLogo); #endregion #region "Espaciador entre Header y Conceptos" Paragraph pRelleno = new Paragraph(); Chunk cRelleno = new Chunk(); for (int lineas = 0; lineas < 12; lineas++) { cRelleno.Append("\n"); } pRelleno.Add(cRelleno); document.Add(pRelleno); #endregion #region "Añadimos Detalle de Conceptos" // Creamos la tabla para insertar los conceptos de detalle de la factura PdfPTable tableConceptos = new PdfPTable(5); int[] colWithsConceptos = new int[5]; String[] arrColWidthConceptos = dtConfigFact.Rows[0]["conceptosColWidth"].ToString().Split(new Char[] { ',' }); for (int i = 0; i < arrColWidthConceptos.Length; i++) { colWithsConceptos.SetValue(Convert.ToInt32(arrColWidthConceptos[i]), i); } tableConceptos.SetWidths(colWithsConceptos); tableConceptos.WidthPercentage = 93F; int numConceptos = electronicDocument.Data.Conceptos.Count; PdfPCell cellConceptos = new PdfPCell(); PdfPCell cellMontos = new PdfPCell(); for (int i = 0; i < numConceptos; i++) { cellConceptos = new PdfPCell(new Phrase(electronicDocument.Data.Conceptos[i].Cantidad.Value.ToString(), new Font(Font.HELVETICA, 7, Font.NORMAL))); cellConceptos.Border = 0; cellConceptos.HorizontalAlignment = PdfCell.ALIGN_LEFT; tableConceptos.AddCell(cellConceptos); cellConceptos = new PdfPCell(new Phrase(electronicDocument.Data.Conceptos[i].Unidad.Value, new Font(Font.HELVETICA, 7, Font.NORMAL))); cellConceptos.Border = 0; cellConceptos.HorizontalAlignment = PdfCell.ALIGN_LEFT; tableConceptos.AddCell(cellConceptos); cellConceptos = new PdfPCell(new Phrase(electronicDocument.Data.Conceptos[i].Descripcion.Value, new Font(Font.HELVETICA, 7, Font.NORMAL))); cellConceptos.Border = 0; tableConceptos.AddCell(cellConceptos); cellMontos = new PdfPCell(new Phrase(electronicDocument.Data.Conceptos[i].ValorUnitario.Value.ToString("C", _ci), new Font(Font.HELVETICA, 7, Font.NORMAL))); cellMontos.Border = 0; cellMontos.HorizontalAlignment = PdfCell.ALIGN_RIGHT; tableConceptos.AddCell(cellMontos); cellMontos = new PdfPCell(new Phrase(electronicDocument.Data.Conceptos[i].Importe.Value.ToString("C", _ci), new Font(Font.HELVETICA, 8, Font.NORMAL))); cellMontos.Border = 0; cellMontos.HorizontalAlignment = PdfCell.ALIGN_RIGHT; tableConceptos.AddCell(cellMontos); } document.Add(tableConceptos); #endregion #region "Espaciador entre Conceptos y Desglose" Paragraph pRelleno2 = new Paragraph(); Chunk cRelleno2 = new Chunk("\n"); pRelleno2.Add(cRelleno2); document.Add(pRelleno2); #endregion #region "Desglose" PdfPTable tableDesglose = new PdfPTable(3); int[] colWithsDesglose = new int[3]; String[] arrColWidthDesglose = dtConfigFact.Rows[0]["desgloseColWidth"].ToString().Split(new Char[] { ',' }); for (int i = 0; i < arrColWidthDesglose.Length; i++) { colWithsDesglose.SetValue(Convert.ToInt32(arrColWidthDesglose[i]), i); } tableDesglose.SetWidths(colWithsDesglose); tableDesglose.WidthPercentage = 93F; PdfPCell cellDesgloseRelleno = new PdfPCell(); PdfPCell cellDesgloseDescripcion = new PdfPCell(); PdfPCell cellDesgloseMonto = new PdfPCell(); //Armamnos el Hashtable que conntiene el desglose del Cfdi Hashtable htDesglose = new Hashtable(); ArrayList alDesgloseOrden = new ArrayList(); alDesgloseOrden.Add("Subtotal"); if (electronicDocument.Data.Descuento.Value != 0) { alDesgloseOrden.Add("Descuento"); } if (electronicDocument.Data.Impuestos.TotalTraslados.Value != 0) { alDesgloseOrden.Add("Impuestos Trasladados"); } if (electronicDocument.Data.Impuestos.TotalRetenciones.Value != 0) { alDesgloseOrden.Add("Impuestos Retenidos"); } alDesgloseOrden.Add("Total"); htDesglose.Add("Subtotal", electronicDocument.Data.SubTotal.Value.ToString("C", _ci)); htDesglose.Add("Descuento", electronicDocument.Data.Descuento.Value.ToString("C", _ci)); htDesglose.Add("Impuestos Trasladados", electronicDocument.Data.Impuestos.TotalTraslados.Value.ToString("C", _ci)); htDesglose.Add("Impuestos Retenidos", electronicDocument.Data.Impuestos.TotalRetenciones.Value.ToString("C", _ci)); htDesglose.Add("Total", electronicDocument.Data.Total.Value.ToString("C", _ci)); foreach (string desglose in alDesgloseOrden) { cellDesgloseRelleno = new PdfPCell(new Phrase(string.Empty, new Font(Font.HELVETICA, 7, Font.BOLD))); cellDesgloseRelleno.Border = 0; cellDesgloseDescripcion = new PdfPCell(new Phrase(desglose, new Font(Font.HELVETICA, 7, Font.BOLD))); cellDesgloseDescripcion.Border = 0; cellDesgloseMonto = new PdfPCell(new Phrase(htDesglose[desglose].ToString(), new Font(Font.HELVETICA, 7, Font.NORMAL))); cellDesgloseMonto.Border = 0; cellDesgloseMonto.HorizontalAlignment = PdfCell.ALIGN_RIGHT; tableDesglose.AddCell(cellDesgloseRelleno); tableDesglose.AddCell(cellDesgloseDescripcion); tableDesglose.AddCell(cellDesgloseMonto); } document.Add(tableDesglose); #endregion #region "Desglose Detalle" PdfPTable tableDesgloseDetalle = new PdfPTable(3); int[] colWithsDesgloseDetalle = new int[3]; string colDesgloseDetalle = "8,8,84"; String[] arrColWidthDesgloseDetalle = colDesgloseDetalle.Split(new Char[] { ',' }); for (int i = 0; i < arrColWidthDesgloseDetalle.Length; i++) { colWithsDesgloseDetalle.SetValue(Convert.ToInt32(arrColWidthDesgloseDetalle[i]), i); } tableDesgloseDetalle.SetWidths(colWithsDesgloseDetalle); tableDesgloseDetalle.WidthPercentage = 100F; #endregion #region "Creación e Inserción de Chunks en Paragraph" Paragraph pFooter = new Paragraph(); pFooter.KeepTogether = true; pFooter.Alignment = PdfCell.ALIGN_LEFT; pFooter.SetLeading(1.6f, 1.6f); //AZUL Font fontLbl = new Font(Font.HELVETICA, 6, Font.BOLD, new Color(43, 145, 175)); Font fontLbl = new Font(Font.HELVETICA, 6, Font.BOLD, new Color(25, 71, 6)); Font fontVal = new Font(Font.HELVETICA, 6, Font.NORMAL); string cantidadLetra = dtConfigFact.Rows[0]["cantidadLetra"].ToString(); Chunk cCantidadLetraVal = new Chunk(cantidadLetra, new Font(Font.HELVETICA, 7, Font.BOLD)); Chunk cTipoComprobanteLbl = new Chunk("Tipo de Comprobante: ", fontLbl); Chunk cTipoComprobanteVal = new Chunk(electronicDocument.Data.TipoComprobante.Value, fontVal); Chunk cFormaPagoLbl = new Chunk("Forma de Pago: ", fontLbl); Chunk cFormaPagoVal = new Chunk(electronicDocument.Data.FormaPago.Value, fontVal); Chunk cMetodoPagoLbl = new Chunk("Método de Pago: ", fontLbl); Chunk cMetodoPagoVal = new Chunk(electronicDocument.Data.MetodoPago.Value, fontVal); Chunk cMonedaLbl = new Chunk("Moneda: ", fontLbl); Chunk cMonedaVal = new Chunk(electronicDocument.Data.Moneda.Value, fontVal); if (electronicDocument.Data.TipoCambio.Value.Length == 0) electronicDocument.Data.TipoCambio.Value = "1"; Chunk cTasaCambioLbl = new Chunk("Tasa de Cambio: ", fontLbl); Chunk cTasaCambioVal = new Chunk(Convert.ToDouble(electronicDocument.Data.TipoCambio.Value).ToString("C", _ci), fontVal); Chunk cCertificadoLbl = new Chunk("Certificado del Emisor: ", fontLbl); Chunk cCertificadoVal = new Chunk(electronicDocument.Data.NumeroCertificado.Value, fontVal); Chunk cCadenaOriginalLbl = new Chunk("Cadena Original", fontLbl); Chunk cCadenaOriginalVal = new Chunk(electronicDocument.FingerPrint, fontVal); Chunk cCadenaOriginalPACLbl = new Chunk("Cadena Original del Complemento de Certificación Digital del SAT", fontLbl); Chunk cCadenaOriginalPACVal = new Chunk(electronicDocument.FingerPrintPac, fontVal); Chunk cSelloDigitalLbl = new Chunk("Sello Digital del Emisor", fontLbl); Chunk cSelloDigitalVal = new Chunk(electronicDocument.Data.Sello.Value, fontVal); string regimenes = ""; for (int u = 0; u < electronicDocument.Data.Emisor.Regimenes.Count; u++) regimenes += electronicDocument.Data.Emisor.Regimenes[u].Regimen.Value.ToString() + ","; Chunk cNoTarjetaLbl = new Chunk("No. Tarjeta: ", fontLbl); Chunk cNoTarjetaVal = new Chunk(electronicDocument.Data.NumeroCuentaPago.Value, fontVal); Chunk cExpedidoEnLbl = new Chunk("Expedido En: ", fontLbl); Chunk cExpedidoEnVal = new Chunk(electronicDocument.Data.LugarExpedicion.Value, fontVal); pFooter.Add(cCantidadLetraVal); pFooter.Add(cSaltoLinea); pFooter.Add(cTipoComprobanteLbl); pFooter.Add(cTipoComprobanteVal); pFooter.Add(cDataSpacer); pFooter.Add(cMonedaLbl); pFooter.Add(cMonedaVal); pFooter.Add(cDataSpacer); pFooter.Add(cTasaCambioLbl); pFooter.Add(cTasaCambioVal); pFooter.Add(cDataSpacer); if (htFacturaxion["noOrdenCompra"].ToString().Length > 0) { Chunk cOrdenCompraLbl = new Chunk("Orden de Compra: ", fontLbl); Chunk cOrdenCompraVal = new Chunk(htFacturaxion["noOrdenCompra"].ToString(), fontVal); pFooter.Add(cOrdenCompraLbl); pFooter.Add(cOrdenCompraVal); pFooter.Add(cDataSpacer); } pFooter.Add(cFormaPagoLbl); pFooter.Add(cFormaPagoVal); pFooter.Add(cDataSpacer); pFooter.Add(cMetodoPagoLbl); pFooter.Add(cMetodoPagoVal); if (electronicDocument.Data.NumeroCuentaPago.Value.ToString().Length > 0) { pFooter.Add(cDataSpacer); pFooter.Add(cNoTarjetaLbl); pFooter.Add(cNoTarjetaVal); } if (electronicDocument.Data.Emisor.Regimenes.Count > 0) { Chunk cRegimenLbl = new Chunk("Régimen Fiscal: ", fontLbl); Chunk cRegimenVal = new Chunk(regimenes.Substring(0, regimenes.Length - 1).ToString(), fontVal); pFooter.Add(cDataSpacer); pFooter.Add(cRegimenLbl); pFooter.Add(cRegimenVal); } if (electronicDocument.Data.FolioFiscalOriginal.Value.ToString().Length > 0) { Chunk cFolioOriginal1Lbl = new Chunk("Datos CFDI Original - Serie: ", fontLbl); Chunk cFolioOriginal1Val = new Chunk(electronicDocument.Data.SerieFolioFiscalOriginal.Value + " ", fontVal); Chunk cFolioOriginal2Lbl = new Chunk("Folio: ", fontLbl); Chunk cFolioOriginal2Val = new Chunk(electronicDocument.Data.FolioFiscalOriginal.Value + " ", fontVal); Chunk cFolioOriginal3Lbl = new Chunk("Fecha: ", fontLbl); Chunk cFolioOriginal3Val = new Chunk(electronicDocument.Data.FechaFolioFiscalOriginal.Value.ToString() + " ", fontVal); Chunk cFolioOriginal4Lbl = new Chunk("Monto: ", fontLbl); Chunk cFolioOriginal4Val = new Chunk(electronicDocument.Data.MontoFolioFiscalOriginal.Value.ToString(), fontVal); pFooter.Add(cSaltoLinea); pFooter.Add(cFolioOriginal1Lbl); pFooter.Add(cFolioOriginal1Val); pFooter.Add(cFolioOriginal2Lbl); pFooter.Add(cFolioOriginal2Val); pFooter.Add(cFolioOriginal3Lbl); pFooter.Add(cFolioOriginal3Val); pFooter.Add(cFolioOriginal4Lbl); pFooter.Add(cFolioOriginal4Val); } pFooter.Add(cLineaDiv); if (htFacturaxion["observaciones"].ToString().Length > 0) { Chunk cObsLbl = new Chunk("Observaciones ", fontLbl); Chunk cObsVal = new Chunk(htFacturaxion["observaciones"].ToString(), fontVal); pFooter.Add(cObsLbl); pFooter.Add(cSaltoLinea); pFooter.Add(cObsVal); pFooter.Add(cLineaDiv); } if (electronicDocument.Data.LugarExpedicion.Value.Length > 0) { pFooter.Add(cExpedidoEnLbl); pFooter.Add(cExpedidoEnVal); pFooter.Add(cLineaDiv); } pFooter.Add(cCertificadoLbl); pFooter.Add(cCertificadoVal); pFooter.Add(cLineaDiv); if (timbrar) { pFooter.Add(cCadenaOriginalPACLbl); pFooter.Add(cSaltoLinea); pFooter.Add(cCadenaOriginalPACVal); } else { pFooter.Add(cCadenaOriginalLbl); pFooter.Add(cSaltoLinea); pFooter.Add(cCadenaOriginalVal); } pFooter.Add(cLineaDiv); pFooter.Add(cSelloDigitalLbl); pFooter.Add(cSaltoLinea); pFooter.Add(cSelloDigitalVal); pFooter.Add(cLineaSpace); document.Add(pFooter); #endregion #region "Añadimos Código Bidimensional" if (timbrar) { Image imageQRCode = Image.GetInstance(bytesQRCode); imageQRCode.Alignment = (Image.TEXTWRAP | Image.ALIGN_LEFT); imageQRCode.ScaleToFit(90f, 90f); imageQRCode.IndentationLeft = 9f; imageQRCode.SpacingAfter = 9f; imageQRCode.BorderColorTop = Color.WHITE; document.Add(imageQRCode); pFooter.Clear(); #region "Creación e Inserción de Chunks de Timbrado en Paragraph" Chunk cFolioFiscalLbl = new Chunk("Folio Fiscal: ", fontLbl); Chunk cFolioFiscalVal = new Chunk(objTimbre.Uuid.Value, fontVal); Chunk cFechaTimbradoLbl = new Chunk("Fecha y Hora de Certificación: ", fontLbl); DateTime fechaTimbrado = Convert.ToDateTime(objTimbre.FechaTimbrado.Value); string formatoFechaTimbrado = fechaTimbrado.ToString("yyyy-MM-dd") + "T" + fechaTimbrado.ToString("HH:mm:ss"); Chunk cFechaTimbradoVal = new Chunk(formatoFechaTimbrado, fontVal); Chunk cCertificadoSatLbl = new Chunk("Certificado SAT: ", fontLbl); Chunk cCertificadoSatVal = new Chunk(objTimbre.NumeroCertificadoSat.Value, fontVal); Chunk cSelloDigitalSatLbl = new Chunk("Sello Digital SAT", fontLbl); Chunk cSelloDigitalSatVal = new Chunk(objTimbre.SelloSat.Value, fontVal); pFooter.Add(cSaltoLinea); pFooter.Add(cFolioFiscalLbl); pFooter.Add(cFolioFiscalVal); pFooter.Add(cDataSpacer); pFooter.Add(cCertificadoSatLbl); pFooter.Add(cCertificadoSatVal); pFooter.Add(cSaltoLinea); pFooter.Add(cFechaTimbradoLbl); pFooter.Add(cFechaTimbradoVal); pFooter.Add(cSaltoLinea); pFooter.Add(cSelloDigitalSatLbl); pFooter.Add(cSaltoLinea); pFooter.Add(cSelloDigitalSatVal); #endregion document.Add(pFooter); } #endregion #region "Añadimos leyenda de CFDI" Paragraph pLeyendaCfdi = new Paragraph(); string leyenda; if (timbrar) { leyenda = "Este documento es una representación impresa de un CFDI"; } else { leyenda = "Este documento es una representación impresa de un Comprobante Fiscal Digital"; } Chunk cLeyendaCfdi = new Chunk(leyenda, new Font(Font.HELVETICA, 8, Font.BOLD | Font.ITALIC)); pLeyendaCfdi.Add(cLeyendaCfdi); pLeyendaCfdi.SetLeading(1.6f, 1.6f); document.Add(pLeyendaCfdi); #endregion #region "Footer" //Agregando Imagen de Pie de Página Image imgFooter = Image.GetInstance(dtConfigFact.Rows[0]["rutaTemplateFooter"].ToString()); float imgFooterWidth = document.PageSize.Width - 70; float imgFooterHeight = imgFooter.Height / (imgFooter.Width / imgFooterWidth); imgFooter.ScaleAbsolute(imgFooterWidth, imgFooterHeight); imgFooter.SetAbsolutePosition(Convert.ToSingle(dtConfigFact.Rows[0]["footerPosX"]), Convert.ToSingle(dtConfigFact.Rows[0]["footerPosY"])); document.Add(imgFooter); // Si el rol del usuario es gratuito añadimos el footer las imagenes de facturaxion y r3take if (idRol == 16) { Image facturaxionImgFooter = Image.GetInstance(ConfigurationManager.AppSettings["logoFacturaxion"]); Image r3TakeImgFooter = Image.GetInstance(ConfigurationManager.AppSettings["logor3Take"]); facturaxionImgFooter.ScaleAbsolute(70, 25); r3TakeImgFooter.ScaleAbsolute(70, 25); facturaxionImgFooter.SetAbsolutePosition(25, 10); r3TakeImgFooter.SetAbsolutePosition(600, 10); document.Add(facturaxionImgFooter); document.Add(r3TakeImgFooter); } #endregion document.Close(); writer.Close(); fs.Close(); string filePdfExt = pathPdf.Replace(_rutaDocs, _rutaDocsExt); string urlPathFilePdf = filePdfExt.Replace(@"\", "/"); //Subimos Archivo al Azure string res = App_Code.com.Facturaxion.facturaEspecial.wAzure.azureUpDownLoad(1, pathPdf); return "1#" + urlPathFilePdf; } catch (Exception ex) { fs.Flush(); fs.Close(); File.Delete(pathPdf); return "0#" + ex.Message; } }