public ReportPdf(Stream Output, Layout Layout, Template Template, Dictionary<string, string> ConfigParams) : base(Output, Layout, Template, ConfigParams) { Rectangle pageSize = new Rectangle(mm2pt(Template.PageSize.Width), mm2pt(Template.PageSize.Height)); // Initialization m_Document = new Document(pageSize, mm2pt(Template.Margin.Left), mm2pt(Template.Margin.Right), mm2pt(Template.Margin.Top), mm2pt(Template.Margin.Bottom)); m_Writer = PdfWriter.GetInstance(m_Document, Output); m_Document.AddCreationDate(); m_Document.AddCreator("StrengthReport http://dev.progterv.info/strengthreport) and KeePass (http://keepass.info)"); m_Document.AddKeywords("report"); m_Document.AddTitle(Layout.Title+" (report)"); // Header HeaderFooter header = new HeaderFooter(new Phrase(Layout.Title+", "+DateTime.Now.ToString(), m_Template.ReportFooter.getFont()), false); header.Alignment = Template.ReportFooter.getAlignment(); m_Document.Header = header; // Footer HeaderFooter footer = new HeaderFooter(new Phrase(new Chunk("Page ", m_Template.ReportFooter.getFont())), new Phrase(new Chunk(".", m_Template.ReportFooter.getFont()))); footer.Alignment = Template.ReportFooter.getAlignment(); m_Document.Footer = footer; // TODO: Metadata // Open document m_Document.Open(); // Report Heading { PdfPTable reportTitle = new PdfPTable(1); PdfPCell titleCell = new PdfPCell(new Phrase(Layout.Title, m_Template.ReportHeader.getFont())); titleCell.Border = 0; titleCell.FixedHeight = mm2pt(m_Template.ReportHeader.Height); titleCell.VerticalAlignment = Element.ALIGN_MIDDLE; titleCell.HorizontalAlignment = m_Template.ReportHeader.getAlignment(); reportTitle.AddCell(titleCell); reportTitle.WidthPercentage = 100; m_Document.Add(reportTitle); } // Create main table m_Table = new PdfPTable(Layout.GetColumnWidths()); m_Table.WidthPercentage = 100; m_Table.HeaderRows = 1; foreach (LayoutElement element in Layout) { PdfPCell cell = new PdfPCell(new Phrase(element.Title, m_Template.Header.getFont())); cell.BackgroundColor = m_Template.Header.Background.ToColor(); cell.MinimumHeight = mm2pt(m_Template.Header.Height); cell.VerticalAlignment = Element.ALIGN_MIDDLE; m_Table.AddCell(cell); } m_colorRow = new CMYKColor[] { m_Template.Row.BackgroundA.ToColor(), m_Template.Row.BackgroundB.ToColor() }; }
/// <summary> /// Render all data add and writes it to the specified writer /// </summary> /// <param name="model"> /// The model to render /// </param> /// <param name="os"> /// The output to write to /// </param> public override void RenderAllTables(IDataSetModel model, Stream os) { // TODO check the number of horizontal & vertical key values to determine the orientation of the page var doc = new Document(this._pageSize, 80, 50, 30, 65); // This doesn't seem to do anything... doc.AddHeader(Markup.HTML_ATTR_STYLESHEET, "style/pdf.css"); doc.AddCreationDate(); doc.AddCreator("NSI .NET Client"); try { PdfWriter.GetInstance(doc, os); doc.Open(); this.WriteTableModels(model, doc); } catch (DocumentException ex) { Trace.Write(ex.ToString()); LogError.Instance.OnLogErrorEvent(ex.ToString()); } catch (DbException ex) { Trace.Write(ex.ToString()); LogError.Instance.OnLogErrorEvent(ex.ToString()); } finally { if (doc.IsOpen()) { doc.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(); }
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"); }
public PDFDocument(Stream stream, Rectangle pageSize) { DocumentStream = stream; Document = new Document(pageSize); PageEventHelper = new PageEventHelper(); Writer = PdfWriter.GetInstance(Document, stream); Writer.PageEvent = PageEventHelper; Document.Open(); Document.AddCreationDate(); }
public String TiffAsPDF(List <string> files, String targetPath) { try { if (files.Count > 0) { //ByteArrayOutputStream outfile = new ByteArrayOutputStream(); iTextSharp.text.Document document = null; iTextSharp.text.pdf.PdfWriter writer = null; foreach (string str2 in files) // iterate over files { iTextSharp.text.Image image = null; iTextSharp.text.pdf.RandomAccessFileOrArray ra = new iTextSharp.text.pdf.RandomAccessFileOrArray(GetFullPath(str2)); int pages = iTextSharp.text.pdf.codec.TiffImage.GetNumberOfPages(ra); for (int iPage = 1; iPage <= pages; iPage++) // iterate over tiff pages { image = iTextSharp.text.pdf.codec.TiffImage.GetTiffImage(ra, iPage); iTextSharp.text.Rectangle pageSize = new iTextSharp.text.Rectangle(image.PlainWidth, image.PlainHeight); if (document == null) { document = new iTextSharp.text.Document(pageSize); // initialize with a PageSize document.AddCreationDate(); writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, new System.IO.FileStream(GetFullPath(targetPath), System.IO.FileMode.Create)); writer.StrictImageSequence = true; document.Open(); } else { document.SetPageSize(pageSize); } //tiff.scaleToFit(800, 600); document.Add(image); document.NewPage(); } } document.Close(); //outfile.Flush(); return(""); } return("No Tiff files to process"); } catch (Exception exception) { return(exception.Message); } finally { // Do nothing; } }
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 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(); }
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(); /*-------------------------------------*/ }
/// <summary> /// Genera el informe /// </summary> public Document genera() { try { // HeaderAndFooter PdfPageEventHelper = new HeaderAndFooter(); /* using (Document document = new Document(PageSize.A4.Rotate())) * { * // step 2 * PdfWriter writer = PdfWriter.GetInstance(document, stream); * // step 3 * document.Open(); * // step 4 * DrawTimeTable(writer.DirectContentUnder); * DrawTimeSlots(writer.DirectContent); * }*/ //iTextSharp.text.PageSize.A4 //_document = new Document(PageSize.A4, 60, 60, 120, 80); //iTextSharp.text.Document doc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 30f, 30f, 30f, 30f); using (Document doc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 60, 60, 120, 80)) { doc.Open(); //metadatos doc.AddCreationDate(); doc.Add(new Paragraph("Hello World")); return(doc); } /* PdfWriter writer = PdfWriter.GetInstance(_document, this.getStream()); * writer.PageEvent = PdfPageEventHelper; * writer.CompressionLevel = PdfStream.BEST_COMPRESSION;*/ /*this.OnOpenDocument(this.getWriter(), this.getDocument()); //este evento aún no se ha podido enlazar * this.setPageEvent(this); * this.setCompressionLevel(PdfStream.BEST_COMPRESSION);*/ } catch (Exception ex) { return(null); } }
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(); }
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 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 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 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; } }
private void button4_Click(object sender, EventArgs e) { //Control ctl = this.dataGridView1; Control ctl = Control.FromHandle(this.dataGridView1.Handle); { Bitmap bt = new Bitmap(ctl.Width, ctl.Height); ctl.DrawToBitmap(bt, new System.Drawing.Rectangle(0, 0, bt.Width, bt.Height)); bt.Save("abc.gif",System.Drawing.Imaging.ImageFormat.Gif); Document document = new Document(PageSize.A4, 10,10, 10,10); PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(Application.StartupPath + @"\abcd.pdf", FileMode.Create)); writer.ViewerPreferences = (PdfWriter.CenterWindow | PdfWriter.FitWindow | PdfWriter.PageModeUseNone); document.Open(); //使用宋体字体 BaseFont baseFont = BaseFont.CreateFont("C:\\WINDOWS\\FONTS\\simsun.ttc,0", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); PdfContentByte cb = writer.DirectContent; Chapter chapter1 = new Chapter(new Paragraph("This is Chapter 1"), 1); Section section1 = chapter1.AddSection(20f, "Section 1.1", 2); Section section2 = chapter1.AddSection(20f, "Section 1.2", 2); Section subsection1 = section2.AddSection(20f, "Subsection 1.2.1", 3); Section subsection2 = section2.AddSection(20f, "Subsection 1.2.2", 3); Section subsubsection = subsection2.AddSection(20f, "Sub Subsection 1.2.2.1", 4); Chapter chapter2 = new Chapter(new Paragraph("This is Chapter 2"), 1); Section section3 = chapter2.AddSection("Section 2.1", 2); Section subsection3 = section3.AddSection("Subsection 2.1.1", 3); Section section4 = chapter2.AddSection("Section 2.2", 2); chapter1.BookmarkTitle = "Changed Title"; chapter1.BookmarkOpen = true; chapter2.BookmarkOpen = false; document.Add(chapter1); document.Add(chapter2); ZapfDingbatsList zlist = new ZapfDingbatsList(49, 15); zlist.Add("One"); zlist.Add("Two"); zlist.Add("Three"); zlist.Add("Four"); zlist.Add("Five"); document.Add(zlist); RomanList romanlist = new RomanList(true, 20); romanlist.IndentationLeft = 30f; romanlist.Add("One"); romanlist.Add("Two"); romanlist.Add("Three"); romanlist.Add("Four"); romanlist.Add("Five"); document.Add(romanlist); PdfPTable table1 = new PdfPTable(3); PdfPCell cell1 = new PdfPCell(new Phrase("Header spanning 3 columns")); cell1.Colspan = 3; cell1.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right table1.AddCell(cell1); table1.AddCell(cell1); table1.AddCell("Col 1 Row 2"); table1.AddCell("Col 2 Row 2"); table1.AddCell("Col 3 Row 2"); table1.SetWidths(new int[]{50,100,100}); table1.WidthPercentage = 100f; document.Add(table1); //using it = iTextSharp.text; //PdfPTable table2 = new PdfPTable(3); //table2.AddCell("Cell 1"); //PdfPCell cell2 = new PdfPCell(new it.Phrase("Cell 2", new Font(Font.HELVETICA, 8f, Font.NORMAL, Color.YELLOW))); //cell2.BackgroundColor = new Color(0, 150, 0); //cell2.BorderColor = new Color(255, 242, 0); //cell2.Border = Rectangle.BOTTOM_BORDER | Rectangle.TOP_BORDER; //cell2.BorderWidthBottom = 3f; //cell2.BorderWidthTop = 3f; //cell2.PaddingBottom = 10f; //cell2.PaddingLeft = 20f; //cell2.PaddingTop = 4f; //table2.AddCell(cell2); //table2.AddCell("Cell 3"); //document.Add(table2); System.Drawing.Image img = bt; MemoryStream mem = new MemoryStream(); img.Save(mem, System.Drawing.Imaging.ImageFormat.Gif); byte[] bytes = mem.ToArray(); iTextSharp.text.Image img2 = iTextSharp.text.Image.GetInstance(bytes); iTextSharp.text.Image img3 = iTextSharp.text.Image.GetInstance(bytes); img2.ScalePercent(100f); img3.ScalePercent(100f); img2.SetAbsolutePosition(50f, 400f); img3.SetAbsolutePosition(50f, 400f - img2.Height); //cb.AddImage(img2); //cb.AddImage(img3); cb.BeginText(); float Xleading = 27.5f; float Xdelta = 10f; float Yleading = 27.5f; float Ydelta = 20f; cb.SetLineWidth(4f); cb.MoveTo(Xleading, (842 - Yleading - Ydelta)); cb.LineTo((595f - Xleading), (842f - Yleading - Ydelta)); cb.Stroke(); cb.EndText(); document.NewPage(); //绘制近下方细直线上的文字 cb.BeginText(); BaseFont fbaseFont = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED); iTextSharp.text.Font font = new iTextSharp.text.Font(fbaseFont); cb.SetFontAndSize(fbaseFont,15); cb.SetColorFill(BaseColor.LIGHT_GRAY); PdfPCell cell = new PdfPCell(); PdfPTable table = new PdfPTable(5); cell.HorizontalAlignment = Element.ALIGN_LEFT; table.AddCell(cell); document.Add(table); document.AddAuthor("ms"); document.AddCreationDate(); document.AddTitle("TEST"); //document.Add(new Paragraph("", font)); //document.Add(new Paragraph(" 你好, PDF !", font)); //document.Add(new Paragraph(" 你好, PDF !", font)); //document.Add(new Paragraph(" 你好, PDF !", font)); cb.ShowTextAligned(Element.ALIGN_LEFT, "一二三 :", 50, 800f, 0); cb.ShowTextAligned(Element.ALIGN_LEFT, "一二三 :", 50, 770f, 0); cb.EndText(); cb.AddImage(img2); document.Close(); } Control.ControlCollection ctls = this.Controls; foreach (Control item in ctls) { item.Enabled = false; //item.Width += 100; } }
private void Speichern(string filename) { try { Document document = new Document(); PdfWriter.GetInstance(document, new FileStream(filename, FileMode.Create)); document.AddTitle("Webfuzzer Report"); document.AddCreationDate(); document.Open(); document.Add(new Paragraph("WebFuzzer Found URLs", FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 16, iTextSharp.text.Font.UNDERLINE))); document.Add(new Paragraph(" ")); foreach (ListViewItem item in listViewResult.Items) { document.Add(new Paragraph(item.SubItems[1].Text)); if (richTextBoxPOST.Text != string.Empty) { document.Add(new Paragraph("POST data: " + richTextBoxPOST.Text)); } document.Add(new Paragraph(" ")); } document.Close(); } catch (IOException) { MessageBox.Show("The file is in use. Please close all applications accessing this file and try again.", "Access not possible", MessageBoxButtons.OK); } catch (Exception ex) { Console.WriteLine("Fehler beim Speichern" + ex); } }
protected void btntetkikkaydet_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(ddlHasta.SelectedValue)).ToList(); var radyolojilistesi = hastalistesi.SelectMany(x => x.RadyolojiList).ToList().Where(x => x._id == ObjectId.Parse(ddlRadyoloji.SelectedValue)); var tetkiklistesi = radyolojilistesi.SelectMany(x => x.TetkiklerList).ToList().Where(x => x.tahlil_adi == ListBox1.SelectedItem.Text); var hst = hastalistesi.FirstOrDefault(); var rad = radyolojilistesi.FirstOrDefault(); #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\\Radyoloji Sonuç (" + hst.hasta_tc + " " + hst.hasta_adi + " " + hst.hasta_soyadi + " " + DateTime.UtcNow.ToShortDateString() + ").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("Radyoloji"); //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; 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: " + hst.hasta_tc + "\nHasta Adı: " + hst.hasta_adi + "\nHasta Soyadı: " + hst.hasta_soyadi + "\n\n\n"); #region Tabloyu Oluştur PdfPTable pdfTable = new PdfPTable(1); pdfTable.TotalWidth = 500f; pdfTable.LockedWidth = true; pdfTable.HorizontalAlignment = 1; pdfTable.DefaultCell.Padding = 5; pdfTable.DefaultCell.BorderColor = iTextSharp.text.BaseColor.GRAY; pdfTable.AddCell(new Phrase(ListBox1.SelectedItem.Text + " Sonucu", fontArialboldgeneral)); pdfTable.AddCell(new Phrase(sonucText.Value, 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 var filter = Builders <yatanhastalar> .Filter.ElemMatch(x => x.ServisList, Builders <servis> .Filter.ElemMatch(x => x.HastaList, Builders <hasta> .Filter.And(Builders <hasta> .Filter.Eq(x => x._id, ObjectId.Parse(ddlHasta.SelectedValue)), Builders <hasta> .Filter.ElemMatch(x => x.RadyolojiList, Builders <radyolojitetkikler> .Filter.And(Builders <radyolojitetkikler> .Filter.Eq(x => x._id, ObjectId.Parse(ddlRadyoloji.SelectedValue)), Builders <radyolojitetkikler> .Filter.ElemMatch(x => x.TetkiklerList, Builders <tetkikler> .Filter.Eq(x => x.tahlil_adi, ListBox1.SelectedItem.Text))))))); var update = Builders <yatanhastalar> .Update.Pull("ServisList.$[].HastaList.$[].RadyolojiList.$[].TetkiklerList", tetkiklistesi); collection.UpdateOne(filter, update); var sayı = radyolojilistesi.SelectMany(x => x.TetkiklerList).ToList(); if (sayı.Count == 0) { var filter2 = Builders <yatanhastalar> .Filter.ElemMatch(x => x.ServisList, Builders <servis> .Filter.ElemMatch(x => x.HastaList, Builders <hasta> .Filter.Eq(x => x._id, ObjectId.Parse(ddlHasta.SelectedValue)))); hst.hasta_radyoloji_durum = "Sonuçlandı"; var update2 = Builders <yatanhastalar> .Update.Set(b => b.ServisList, servislistesi); } }
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 }); }
public void ExtractPdf(DataGridView dataGridView, bool selectedParameter) { Phrase p = new Phrase("\n"); #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, 11, 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 Fatura pdf oluştur SaveFileDialog save = new SaveFileDialog(); save.OverwritePrompt = false; save.Title = "PDF Dosyaları"; save.DefaultExt = "pdf"; save.Filter = "pdf Dosyaları (*.pdf)|*.pdf|Tüm Dosyalar(*.*)|*.*"; if (save.ShowDialog() == DialogResult.OK) { iTextSharp.text.Document pdfFile = new iTextSharp.text.Document(); PdfWriter.GetInstance(pdfFile, new FileStream(save.FileName, FileMode.Create)); pdfFile.Open(); #region Fatura oluşturan bilgileri pdfFile.AddCreator("Hakedis"); //Oluşturan kişinin isminin eklenmesi pdfFile.AddCreationDate(); //Oluşturulma tarihinin eklenmesi pdfFile.AddAuthor("Hakedis" + applicationVersion); //Yazarın isiminin eklenmesi pdfFile.AddHeader(DateTime.Now.ToLongDateString(), "Hakediş " + DateTime.Now.ToLongDateString()); pdfFile.AddTitle("Hakediş Rapor"); //Başlık ve title eklenmesi #endregion #region Tablo Başlık tarih ve marka bilgileri PdfPTable markAndDateTable = new PdfPTable(2); markAndDateTable.TotalWidth = 250f; markAndDateTable.DefaultCell.Border = iTextSharp.text.Rectangle.NO_BORDER; PdfPCell markName = new PdfPCell(new Phrase("Hakediş " + applicationVersion, fontArialbold)); markName.HorizontalAlignment = Element.ALIGN_LEFT; markName.VerticalAlignment = Element.ALIGN_LEFT; markName.Border = 0; PdfPCell dateTimeReport = new PdfPCell(new Phrase(DateTime.Now.ToLongDateString(), fontArialbold)); dateTimeReport.VerticalAlignment = Element.ALIGN_RIGHT; dateTimeReport.HorizontalAlignment = Element.ALIGN_RIGHT; dateTimeReport.Border = 0; dateTimeReport.ExtraParagraphSpace = 5f; markAndDateTable.AddCell(markName); markAndDateTable.AddCell(dateTimeReport); #endregion #region Veri Tablosu İşlemleri #region Pdf Kolon Başlıklarını Belirleme int columnCount = dataGridView.Columns.Count; PdfPTable pdfColumnheader = new PdfPTable(columnCount - 2); pdfColumnheader.TotalWidth = 400f; pdfColumnheader.LockedWidth = true; pdfColumnheader.DefaultCell.Border = iTextSharp.text.Rectangle.NO_BORDER; if (selectedParameter == true) { for (int i = 0; i < columnCount; i++) { if (i != 0 && i != 1) { PdfPCell columnName = new PdfPCell(new Phrase(dataGridView.Columns[i].HeaderText, fontArialHeader)); columnName.HorizontalAlignment = PdfPCell.ALIGN_CENTER; columnName.VerticalAlignment = PdfPCell.ALIGN_MIDDLE; columnName.FixedHeight = 30f; columnName.Border = 1; pdfColumnheader.AddCell(columnName); } } } else { pdfColumnheader = new PdfPTable(columnCount - 1); for (int i = 0; i < columnCount; i++) { if (i != 0) { PdfPCell columnName = new PdfPCell(new Phrase(dataGridView.Columns[i].HeaderText, fontArialHeader)); columnName.HorizontalAlignment = PdfPCell.ALIGN_CENTER; columnName.VerticalAlignment = PdfPCell.ALIGN_MIDDLE; columnName.FixedHeight = 30f; columnName.Border = 1; pdfColumnheader.AddCell(columnName); } } } #region Satır işlemleri int rowsCount = dataGridView.Rows.Count; PdfPTable pdfDataTable = new PdfPTable(columnCount - 2); if (selectedParameter == true) { for (int i = 0; i <= rowsCount - 1; i++) { for (int j = 0; j < dataGridView.Rows[i].Cells.Count; j++) { if (j != 0 && j != 2) { PdfPCell cell2 = new PdfPCell(new Phrase(dataGridView.Rows[i].Cells[j].Value.ToString(), fontArial)); pdfDataTable.AddCell(cell2); } } } } else { pdfDataTable = new PdfPTable(columnCount - 1); for (int i = 0; i <= rowsCount - 1; i++) { for (int j = 0; j < dataGridView.Rows[i].Cells.Count; j++) { if (j != 0) { PdfPCell cell2 = new PdfPCell(new Phrase(dataGridView.Rows[i].Cells[j].Value.ToString(), fontArial)); pdfDataTable.AddCell(cell2); } } } } #endregion #region Toplam Bilgi Verileri PdfPTable tableTotalInfo = new PdfPTable(2); tableTotalInfo.TotalWidth = 250f; tableTotalInfo.LockedWidth = true; tableTotalInfo.DefaultCell.Border = iTextSharp.text.Rectangle.NO_BORDER; double totalManOfDay = 0; if (selectedParameter == true) { for (int i = 0; i < dataGridView.Rows.Count; i++) { totalManOfDay += double.Parse(dataGridView.Rows[i].Cells[6].Value.ToString()); } } else { for (int i = 0; i < dataGridView.Rows.Count; i++) { totalManOfDay += double.Parse(dataGridView.Rows[i].Cells[2].Value.ToString()); } } PdfPCell cellTotalManOfDay = new PdfPCell(new Phrase(totalManOfDay.ToString(), fontArial)); cellTotalManOfDay.HorizontalAlignment = Element.ALIGN_CENTER; cellTotalManOfDay.VerticalAlignment = Element.ALIGN_LEFT; PdfPCell cellTotal = new PdfPCell(new Phrase("Toplam İş Günü", fontArial)); cellTotal.HorizontalAlignment = Element.ALIGN_CENTER; cellTotal.VerticalAlignment = Element.ALIGN_LEFT; tableTotalInfo.AddCell(cellTotal); tableTotalInfo.AddCell(cellTotalManOfDay); #endregion #endregion #region Pdf Dosyasını yaz ve kapat if (pdfFile.IsOpen() == false) { pdfFile.Open(); } pdfFile.Add(markAndDateTable); pdfFile.Add(p); pdfFile.Add(pdfColumnheader); pdfFile.Add(p); pdfFile.Add(pdfDataTable); pdfFile.Add(p); pdfFile.Add(tableTotalInfo); //pdfFile.Add(p); //pdfFile.Add(p); //pdfFile.Add(p); //pdfFile.Add(nameSurname); //pdfFile.Add(p); //pdfFile.Add(signature); pdfFile.Close(); #endregion #endregion } #endregion }
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(); } } }
/* * Requiere: N/A * Modifica: Exporta el grid de vista previa a un PDF y abre una nueva pestaña en el browser que la previsualiza. Si el usuario lo desea puede descargar el documento desde ahi. * Retorna: N/A. */ protected void exportarToPdf() { string nombreReporte = "Reporte Doroteos.pdf"; iTextSharp.text.Document doc = new iTextSharp.text.Document(iTextSharp.text.PageSize.LETTER); if (preGrid.Rows[0].Cells.Count > 4) doc.SetPageSize(iTextSharp.text.PageSize.LETTER.Rotate()); var output = new System.IO.FileStream(Server.MapPath(nombreReporte), System.IO.FileMode.Create); var writer = PdfWriter.GetInstance(doc, output); doc.Open(); iTextSharp.text.Rectangle page = doc.PageSize; PdfPTable head = new PdfPTable(1); head.TotalWidth = page.Width; Phrase phrase = new Phrase("Reporte generado el: " + DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss") + " GMT", new iTextSharp.text.Font(iTextSharp.text.Font.COURIER, 8)); PdfPCell c = new PdfPCell(phrase); c.Border = iTextSharp.text.Rectangle.NO_BORDER; c.VerticalAlignment = Element.ALIGN_TOP; c.HorizontalAlignment = Element.ALIGN_CENTER; head.AddCell(c); doc.Add(head); doc.AddCreationDate(); iTextSharp.text.Font boldFont = new iTextSharp.text.Font(iTextSharp.text.Font.TIMES_ROMAN, 24, iTextSharp.text.Font.BOLD); iTextSharp.text.Font boldFontHeader = new iTextSharp.text.Font(iTextSharp.text.Font.TIMES_ROMAN, 14, iTextSharp.text.Font.BOLD); doc.Add(new iTextSharp.text.Paragraph("Reporte de proyectos", boldFont)); doc.Add(new iTextSharp.text.Paragraph(" ", boldFont)); BaseFont fieldFontRoman = BaseFont.CreateFont(@"C:\Windows\Fonts\arial.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED); iTextSharp.text.Font normalCell = new iTextSharp.text.Font(fieldFontRoman, 11, iTextSharp.text.Font.NORMAL); iTextSharp.text.Font ff = new iTextSharp.text.Font(fieldFontRoman, 13, iTextSharp.text.Font.BOLD); /*Se agregan datos de proyecto, en caso de ser seleccionado*/ PdfPTable table = new PdfPTable(preGrid.Rows[0].Cells.Count); for (int i = 0; i < preGrid.Rows[0].Cells.Count; i++) { Phrase p = new Phrase(HttpUtility.HtmlDecode(preGrid.HeaderRow.Cells[i].Text), ff); PdfPCell cell = new PdfPCell(p); float level = 0.80F; GrayColor gray = new GrayColor(level); cell.BackgroundColor = gray; bool tiene = cell.HasMinimumHeight(); //Phrase p = new Phrase(quitarTildes(preGrid.HeaderRow.Cells[i].Text), ff); table.AddCell(cell); } foreach (GridViewRow row in preGrid.Rows) { for (int i = 0; i < preGrid.Rows[0].Cells.Count; i++) { Phrase p = new Phrase(HttpUtility.HtmlDecode(row.Cells[i].Text), normalCell); //Phrase p = new Phrase(quitarTildes(row.Cells[i].Text), normalCell); PdfPCell cell = new PdfPCell(p); cell.PaddingBottom = 7.0F; cell.PaddingTop = 7.0F; table.AddCell(cell); } } doc.Add(table); //Se cierra documento doc.Close(); Page.ClientScript.RegisterStartupScript(this.GetType(), "OpenWindow", "window.open('" + nombreReporte + "','_newtab');", true); }
private void ExportToPDF(DataTable dt) { var attachment = "attachment; filename=" + _propertyName + " Budget " + _year + ".pdf"; var pdfDoc = new Document(PageSize.A4.Rotate()); var pdfStream = new MemoryStream(); var pdfWriter = PdfWriter.GetInstance(pdfDoc, pdfStream); pdfDoc.Open();//Open Document to write pdfDoc.AddSubject(_year); pdfDoc.AddTitle(_propertyName); pdfDoc.AddCreationDate(); pdfDoc.NewPage(); var fontH = FontFactory.GetFont("ARIAL", 9, Font.BOLD); var fontT = FontFactory.GetFont("ARIAL", 12, Font.BOLD); var font8 = FontFactory.GetFont("ARIAL", 8); var font8B = FontFactory.GetFont("ARIAL", 8, Font. BOLD); var preface = new Paragraph(); var prefacedate = new Paragraph(); // Lets write a big header preface.Add(new Paragraph("[" + _currency + "] " + _propertyName + " Budget " + _year, fontT)); prefacedate.Add(new Paragraph("Print Date: [" + DateTime.Now + "] ", font8B)); var pdfTable = new PdfPTable(dt.Columns.Count); pdfTable.HorizontalAlignment = 0; pdfTable.TotalWidth = 781f; pdfTable.LockedWidth = true; PdfPCell pdfPCell = null; //Add Header of the pdf table for (var column = 0; column < dt.Columns.Count; column++) { pdfPCell = new PdfPCell(new Phrase(new Chunk(dt.Columns[column].Caption, fontH))); pdfTable.AddCell(pdfPCell); } //How add the data from datatable to pdf table for (var rows = 0; rows < dt.Rows.Count; rows++) { for (var column = 0; column < dt.Columns.Count; column++) { if (rows == dt.Rows.Count - 1) { pdfPCell = new PdfPCell(new Phrase(new Chunk(dt.Rows[rows][column].ToString(), font8B))); } else { pdfPCell = new PdfPCell(new Phrase(new Chunk(dt.Rows[rows][column].ToString(), font8))); } if (column != 0) pdfPCell.HorizontalAlignment = Element.ALIGN_RIGHT; pdfTable.AddCell(pdfPCell); } } var widths = new float[] { 55, 75f, 75f, 72f, 72f, 72f, 72f }; pdfTable.SetWidths(widths); pdfTable.SpacingBefore = 15f; // Give some space after the text or it may overlap the table pdfDoc.SetMargins(5.0f, 5.0f, 40.0f, 0f); pdfDoc.Add(preface); pdfDoc.Add(pdfTable); // add pdf table to the document pdfDoc.Add(prefacedate); pdfDoc.Close(); pdfWriter.Close(); Response.ClearContent(); Response.ClearHeaders(); Response.ContentType = "application/pdf"; Response.AppendHeader("Content-Disposition", attachment); Response.BinaryWrite(pdfStream.ToArray()); 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(); StringBuilder sbConfigFactParms = new StringBuilder(); StringBuilder sbConfigFact = new StringBuilder(); StringBuilder sbDataEmisor = new StringBuilder(); StringBuilder sbOpcionalEncabezado = new StringBuilder(); DataTable dtConfigFact = new DataTable(); DataTable dtDataEmisor = new DataTable(); DataTable dtOpcEncabezado = new DataTable(); _ci.NumberFormat.CurrencyDecimalDigits = 4; _c2.NumberFormat.CurrencyDecimalDigits = 2; electronicDocument = (ElectronicDocument)htFacturaxion["electronicDocument"]; objTimbre = (Data)htFacturaxion["objTimbre"]; timbrar = Convert.ToBoolean(htFacturaxion["timbrar"]); //pathPdf = htFacturaxion["rutaDocumentoPdf"].ToString(); Int64 idCfdi = Convert.ToInt64(htFacturaxion["idCfdi"]); #region "Extraemos los datos del CFDI" 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:I:").Append(Convert.ToInt64(htFacturaxion["idEmisor"])); sbConfigFact. Append("DECLARE @idEmpresa AS INT; SET @idEmpresa = 0; "). Append("SELECT rutaTemplateHeader, CF.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 = -1 AND CF.idTipoComp = @1 AND idCFDProcedencia = 1 AND objDesc NOT LIKE 'nuevoLbl%' "); sbDataEmisor. Append("SELECT nombreSucursal FROM sucursales WHERE idSucursal = @0 "); sbOpcionalEncabezado. Append("SELECT campo1 AS observaciones "). //Append("campo2 AS observaciones2"). //Append("campo3 AS observaciones3"). Append("FROM opcionalEncabezado WHERE idCFDI = @0 and ST = 1"); dtConfigFact = dal.QueryDT("DS_FE", sbConfigFact.ToString(), sbConfigFactParms.ToString(), hc); dtDataEmisor = dal.QueryDT("DS_FE", sbDataEmisor.ToString(), "F:I:" + htFacturaxion["idSucursalEmisor"].ToString(), hc); dtOpcEncabezado = dal.QueryDT("DS_FE", sbOpcionalEncabezado.ToString(), "F:I:" + idCfdi, hc); Hashtable htDatosCfdi = new Hashtable(); #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 " + 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("fechaFactura", electronicDocument.Data.Fecha.Value); htDatosCfdi.Add("UUID", objTimbre.Uuid.Value.ToUpper()); 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()); #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(); //pdfPageEventHandlerProbell pageEventHandler = new pdfPageEventHandlerProbell(); PdfWriter writer = PdfWriter.GetInstance(document, fs); writer.SetFullCompression(); writer.ViewerPreferences = PdfWriter.PageModeUseNone; //writer.PageEvent = pageEventHandler; PdfPageEventHandlerSoliplas sol = new PdfPageEventHandlerSoliplas(); writer.PageEvent = sol; writer.SetPdfVersion(PdfWriter.PDF_VERSION_1_7); azul = new Color(22, 111, 168); azul1 = new Color(43, 145, 175); blanco = new Color(255, 255, 255); Link = new Color(7, 73, 208); gris = new Color(236, 236, 236); grisOX = new Color(220, 215, 220); rojo = new Color(230, 7, 7); lbAzul = new Color(43, 145, 175); EM = BaseFont.CreateFont(@"C:\Windows\Fonts\VERDANA.TTF", BaseFont.WINANSI, BaseFont.NOT_EMBEDDED); f5 = new Font(EM, 5); f5B = new Font(EM, 5, Font.BOLD); f5BBI = new Font(EM, 5, Font.BOLDITALIC); f6 = new Font(EM, 6); f6B = new Font(EM, 6, Font.BOLD); 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); PdfPCell cell; Paragraph par; Cell cel; dSaltoLinea = new Chunk("\n\n "); #endregion PdfPTable encabezado = new PdfPTable(3); encabezado.WidthPercentage = 100; encabezado.TotalWidth = document.PageSize.Width - document.LeftMargin - document.RightMargin; encabezado.SetWidths(new int[3] { 30, 10, 60 }); encabezado.DefaultCell.Border = 0; encabezado.LockedWidth = true; pathIMGLOGO = @"C:\Inetpub\repositorioFacturaxion\imagesFacturaEspecial\SOLIPLAS\logoSoliplas.png"; pathIMGFX = @"C:\Inetpub\repositorioFacturaxion\imagesFacturaEspecial\SOLIPLAS\cfdifx.png"; Image imgLogo = Image.GetInstance(pathIMGLOGO); imgLogo.ScalePercent(48f); Image imgFx = Image.GetInstance(pathIMGFX); imgFx.ScalePercent(25f); #region "Construimos el encabezado y Detalles del documento" //Encabezado Folio Fiscal Table encabezadoFolio = new Table(3); float[] headerEncabezadoFolio = { 60, 10, 30 }; encabezadoFolio.Widths = headerEncabezadoFolio; encabezadoFolio.WidthPercentage = 100F; encabezadoFolio.Padding = 1; encabezadoFolio.Spacing = 1; encabezadoFolio.BorderWidth = 0; encabezadoFolio.DefaultCellBorder = 0; encabezadoFolio.BorderColor = gris; cel = new Cell(imgFx); cel.HorizontalAlignment = Element.ALIGN_LEFT; cel.BorderWidthTop = 0; cel.BorderWidthLeft = 0; cel.BorderWidthRight = 0; cel.BorderWidthBottom = 0; encabezadoFolio.AddCell(cel); cel = new Cell(new Phrase("Folio Fiscal", titulo)); cel.HorizontalAlignment = Element.ALIGN_CENTER; cel.BorderColor = gris; cel.BackgroundColor = azul; encabezadoFolio.AddCell(cel); cel = new Cell(new Phrase(htDatosCfdi["folioFiscal"].ToString().ToUpper(), f6)); cel.VerticalAlignment = Element.ALIGN_MIDDLE; cel.HorizontalAlignment = Element.ALIGN_CENTER; cel.BorderWidthTop = 1; cel.BorderWidthLeft = 1; cel.BorderWidthRight = 1; cel.BorderWidthBottom = 1; cel.BorderColor = azul; encabezadoFolio.AddCell(cel); //Encabezado Comprobante Table encabezadoComprobante = new Table(6); float[] headerEncabezadoComprobante = { 30,40,5,5,10,10 }; encabezadoComprobante.Widths = headerEncabezadoComprobante; encabezadoComprobante.WidthPercentage = 100F; encabezadoComprobante.Padding = 1; encabezadoComprobante.Spacing = 1; encabezadoComprobante.BorderWidth = 0; encabezadoComprobante.DefaultCellBorder = 0; encabezadoComprobante.BorderColor = gris; //LOGO DELA EMPRESA cel = new Cell(imgLogo); cel.HorizontalAlignment = Element.ALIGN_CENTER; cel.BorderWidthTop = 0; cel.BorderWidthLeft = 0; cel.BorderWidthRight = 0; cel.BorderWidthBottom = 0; cel.Rowspan = 4; //cel.Colspan = 2; encabezadoComprobante.AddCell(cel); //EMISOR StringBuilder emisor = new StringBuilder(); emisor. Append("RFC: "). Append(htDatosCfdi["rfcEmisor"].ToString().ToUpper()).Append("\n"). Append(htDatosCfdi["nombreEmisor"]).Append("\n"). Append(htDatosCfdi["direccionEmisor1"].ToString().ToUpper()).Append("\n"). Append(htDatosCfdi["direccionEmisor2"].ToString().ToUpper()).Append("\n"). Append(htDatosCfdi["direccionEmisor3"].ToString().ToUpper()).Append("\n"); cel = new Cell(new Phrase(emisor.ToString(), f6)); cel.VerticalAlignment = Element.ALIGN_RIGHT; cel.BorderColor = gris; cel.BorderWidthTop = 0; cel.BorderWidthLeft = 0; cel.BorderWidthRight = (float).5; cel.BorderWidthBottom = 0; cel.Rowspan = 4; cel.Colspan = 3; encabezadoComprobante.AddCell(cel); // Serie cel = new Cell(new Phrase("Serie", titulo)); cel.VerticalAlignment = Element.ALIGN_MIDDLE; cel.HorizontalAlignment = Element.ALIGN_CENTER; cel.BackgroundColor = azul; cel.BorderWidthTop = 0; cel.BorderWidthLeft = 0; cel.BorderWidthRight = 0; cel.BorderWidthBottom = 0; cel.BorderColor = gris; //cel.Colspan = 3; encabezadoComprobante.AddCell(cel); // Folio cel = new Cell(new Phrase("Folio", titulo)); cel.VerticalAlignment = Element.ALIGN_MIDDLE; cel.HorizontalAlignment = Element.ALIGN_CENTER; cel.BackgroundColor = azul; cel.BorderWidthTop = 0; cel.BorderWidthLeft = 0; cel.BorderWidthRight = 0; cel.BorderWidthBottom = 0; cel.BorderColor = gris; encabezadoComprobante.AddCell(cel); cel = new Cell(new Phrase(htDatosCfdi["serie"].ToString(), f6)); cel.VerticalAlignment = Element.ALIGN_MIDDLE; cel.HorizontalAlignment = Element.ALIGN_CENTER; cel.BorderWidthTop = 0; cel.BorderWidthLeft = 0; cel.BorderWidthRight = (float).5; cel.BorderWidthBottom = (float).5; cel.BorderColor = gris; encabezadoComprobante.AddCell(cel); cel = new Cell(new Phrase(htDatosCfdi["folio"].ToString(), f6)); cel.VerticalAlignment = Element.ALIGN_MIDDLE; cel.HorizontalAlignment = Element.ALIGN_CENTER; cel.BorderWidthTop = 0; cel.BorderWidthLeft = 0; cel.BorderWidthRight = (float).5; cel.BorderWidthBottom = (float).5; cel.BorderColor = gris; encabezadoComprobante.AddCell(cel); // Fecha de emisión del comprobante cel = new Cell(new Phrase("Fecha", titulo)); cel.VerticalAlignment = Element.ALIGN_MIDDLE; cel.HorizontalAlignment = Element.ALIGN_CENTER; cel.BackgroundColor = azul; cel.BorderWidthTop = 0; cel.BorderWidthLeft = 0; cel.BorderWidthRight = (float).5; cel.BorderWidthBottom = (float).5; cel.BorderColor = gris; cel.Colspan = 2; encabezadoComprobante.AddCell(cel); cel = new Cell(new Phrase(htDatosCfdi["fechaFactura"].ToString(), f6)); cel.VerticalAlignment = Element.ALIGN_MIDDLE; cel.HorizontalAlignment = Element.ALIGN_CENTER; cel.BorderWidthTop = 0; cel.BorderWidthLeft = 0; cel.BorderWidthRight = (float).5; cel.BorderWidthBottom = (float).5; cel.BorderColor = gris; cel.Colspan = 2; encabezadoComprobante.AddCell(cel); Table encabezadoComprobante1 = new Table(2); float[] headerEncabezadoComprobante1 = { 50, 50 }; encabezadoComprobante1.Widths = headerEncabezadoComprobante1; encabezadoComprobante1.WidthPercentage = 100F; encabezadoComprobante1.Padding = 1; encabezadoComprobante1.Spacing = 1; encabezadoComprobante1.BorderWidth = 0; encabezadoComprobante1.DefaultCellBorder = 0; encabezadoComprobante1.BorderColor = gris; //Datos discales del cliente cel = new Cell(new Phrase("Datos Fiscales del Cliente", titulo)); cel.HorizontalAlignment = Element.ALIGN_CENTER; cel.BorderColor = gris; cel.BackgroundColor = azul; encabezadoComprobante1.AddCell(cel); //Expedido en: cel = new Cell(new Phrase("Expedido en:", titulo)); cel.HorizontalAlignment = Element.ALIGN_CENTER; cel.BorderColor = gris; cel.BackgroundColor = azul; encabezadoComprobante1.AddCell(cel); //Receptor StringBuilder cliente = new StringBuilder(); cliente. Append("\nRFC: "). Append(htDatosCfdi["rfcCliente"].ToString().ToUpper()).Append("\n"). Append(htDatosCfdi["cliente"]).Append("\n"). Append(htDatosCfdi["direccionCliente1"].ToString().ToUpper()).Append("\n"). Append(htDatosCfdi["direccionCliente2"].ToString().ToUpper()).Append("\n"). Append(htDatosCfdi["direccionCliente3"].ToString().ToUpper()).Append("\n"). Append("\n"); cel = new Cell(new Phrase(cliente.ToString(), f6)); cel.VerticalAlignment = Element.ALIGN_MIDDLE; cel.BorderColor = gris; cel.BorderWidthTop = 0; cel.BorderWidthLeft = 0; cel.BorderWidthRight = (float).5; cel.BorderWidthBottom = 0; cel.Rowspan = 5; encabezadoComprobante1.AddCell(cel); //Expedido en: StringBuilder expedido = new StringBuilder(); expedido. //Append(htDatosCfdi["sucursal"]).Append("\n"). Append(htDatosCfdi["direccionExpedido1"].ToString().ToUpper()).Append("\n"). Append(htDatosCfdi["direccionExpedido2"].ToString().ToUpper()).Append("\n"). Append(htDatosCfdi["direccionExpedido3"].ToString().ToUpper()).Append("\n"). Append("\n"); cel = new Cell(new Phrase(expedido.ToString(), f6)); cel.VerticalAlignment = Element.ALIGN_MIDDLE; cel.UseBorderPadding = true; cel.BorderColor = gris; cel.BorderWidthTop = 0; cel.BorderWidthLeft = 0; cel.BorderWidthRight = (float).5; cel.BorderWidthBottom = 0; cel.Rowspan = 5; encabezadoComprobante1.AddCell(cel); #endregion sol.encabezado = encabezado; sol.dSaltoLinea = dSaltoLinea; #region "Tabla Detalle" Table encabezadoDetalle = new Table(6); float[] headerEncabezadoDetalle = { 7, 8, 11, 52, 13, 13 }; encabezadoDetalle.Widths = headerEncabezadoDetalle; encabezadoDetalle.WidthPercentage = 100F; encabezadoDetalle.Padding = 1; encabezadoDetalle.Spacing = 1; encabezadoDetalle.BorderWidth = 0; encabezadoDetalle.DefaultCellBorder = 0; encabezadoDetalle.BorderColor = gris; // Número cel = new Cell(new Phrase("Cantidad", titulo)); cel.HorizontalAlignment = Element.ALIGN_RIGHT; cel.BorderColor = gris; cel.BackgroundColor = azul; encabezadoDetalle.AddCell(cel); // Còdigo de Barras cel = new Cell(new Phrase("Unidad", titulo)); cel.HorizontalAlignment = Element.ALIGN_RIGHT; cel.BorderColor = gris; cel.BackgroundColor = azul; encabezadoDetalle.AddCell(cel); // Código cel = new Cell(new Phrase("Código", titulo)); cel.HorizontalAlignment = Element.ALIGN_CENTER; cel.BorderColor = gris; cel.BackgroundColor = azul; encabezadoDetalle.AddCell(cel); // Descripción cel = new Cell(new Phrase("Descripción", titulo)); cel.HorizontalAlignment = Element.ALIGN_CENTER; cel.BorderColor = gris; cel.BackgroundColor = azul; encabezadoDetalle.AddCell(cel); // Precio Unitario cel = new Cell(new Phrase("Precio Unitario", titulo)); cel.HorizontalAlignment = Element.ALIGN_CENTER; cel.BorderColor = gris; cel.BackgroundColor = azul; encabezadoDetalle.AddCell(cel); // Importe cel = new Cell(new Phrase("Importe", titulo)); cel.HorizontalAlignment = Element.ALIGN_CENTER; cel.BorderColor = gris; cel.BackgroundColor = azul; encabezadoDetalle.AddCell(cel); // Creamos la tabla para insertar los conceptos de detalle de la factura PdfPTable tableConceptos = new PdfPTable(6); int[] colWithsConceptos = new int[6]; //String[] arrColWidthConceptos = dtConfigFact.Rows[0]["conceptosColWidth"].ToString().Split(new Char[] { ',' }); String[] arrColWidthConceptos = { "12", "8", "15", "51", "13", "17" }; for (int i = 0; i < arrColWidthConceptos.Length; i++) { colWithsConceptos.SetValue(Convert.ToInt32(arrColWidthConceptos[i]), i); } tableConceptos.SetWidths(colWithsConceptos); tableConceptos.WidthPercentage = 100F; 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].NumeroIdentificacion.Value, new Font(Font.HELVETICA, 7, Font.NORMAL))); cellConceptos.Border = 0; cellConceptos.HorizontalAlignment = PdfPCell.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, 7, Font.NORMAL))); cellMontos.Border = 0; cellMontos.HorizontalAlignment = PdfCell.ALIGN_RIGHT; tableConceptos.AddCell(cellMontos); } dSaltoLinea = new Chunk("\n\n "); #endregion #region "Construimos el Comentarios" Table comentarios = new Table(7); float[] headerwidthsComentarios = { 18, 18, 28, 28, 7, 5, 5 }; comentarios.Widths = headerwidthsComentarios; comentarios.WidthPercentage = 100; comentarios.Padding = 1; comentarios.Spacing = 1; comentarios.BorderWidth = 0; comentarios.DefaultCellBorder = 0; comentarios.BorderColor = gris; cel = new Cell(new Phrase("Observaciones:", f5B)); cel.VerticalAlignment = Element.ALIGN_MIDDLE; cel.BorderWidthTop = 0; cel.BorderWidthLeft = (float).5; cel.BorderWidthRight = 0; cel.BorderWidthBottom = 0; cel.BorderColor = gris; cel.Colspan = 2; comentarios.AddCell(cel); cel = new Cell(new Phrase("Cantidad:", f5B)); cel.VerticalAlignment = Element.ALIGN_MIDDLE; cel.BorderWidthTop = 0; cel.BorderWidthLeft = 0; cel.BorderWidthRight = 0; cel.BorderWidthBottom = 0; cel.BorderColor = gris; cel.Colspan = 2; comentarios.AddCell(cel); cel = new Cell(new Phrase("Sub Total", f5B)); cel.VerticalAlignment = Element.ALIGN_MIDDLE; cel.HorizontalAlignment = Element.ALIGN_RIGHT; cel.BorderWidthTop = 0; cel.BorderWidthLeft = 0; cel.BorderWidthRight = 0; cel.BorderWidthBottom = 0; cel.BorderColor = gris; comentarios.AddCell(cel); cel = new Cell(new Phrase(electronicDocument.Data.SubTotal.Value.ToString("C", _c2), f5)); cel.VerticalAlignment = Element.ALIGN_MIDDLE; cel.HorizontalAlignment = Element.ALIGN_RIGHT; cel.BorderWidthTop = 0; cel.BorderWidthLeft = 0; cel.BorderWidthRight = (float).5; cel.BorderWidthBottom = 0; cel.BorderColor = gris; cel.Colspan = 2; comentarios.AddCell(cel); cel = new Cell(new Phrase(dtOpcEncabezado.Rows[0]["observaciones"].ToString(), f5)); cel.BorderWidthTop = 0; cel.BorderWidthLeft = (float).5; cel.BorderWidthRight = 0; cel.BorderWidthBottom = (float).5; cel.BorderColor = gris; cel.Colspan = 2; cel.Rowspan = 3; comentarios.AddCell(cel); cel = new Cell(new Phrase(dtConfigFact.Rows[0]["cantidadLetra"].ToString(), f5));//CE26 cel.BorderWidthTop = 0; cel.BorderWidthLeft = 0; cel.BorderWidthRight = 0; cel.BorderWidthBottom = (float).5; cel.BorderColor = gris; cel.Colspan = 2; cel.Rowspan = 3; comentarios.AddCell(cel); cel = new Cell(new Phrase("Descuento",f5B)); cel.VerticalAlignment = Element.ALIGN_MIDDLE; cel.HorizontalAlignment = Element.ALIGN_RIGHT; cel.BorderWidthTop = 0; cel.BorderWidthLeft = 0; cel.BorderWidthRight = 0; cel.BorderWidthBottom = 0; cel.BorderColor = gris; comentarios.AddCell(cel); cel = new Cell(new Phrase(electronicDocument.Data.Descuento.Value.ToString("C", _c2), f5)); cel.VerticalAlignment = Element.ALIGN_MIDDLE; cel.HorizontalAlignment = Element.ALIGN_RIGHT; cel.BorderWidthTop = 0; cel.BorderWidthLeft = 0; cel.BorderWidthRight = (float).5; cel.BorderWidthBottom = 0; cel.BorderColor = gris; cel.Colspan = 2; comentarios.AddCell(cel); double importe = 0; double tasa = 0; for (int i = 0; i < electronicDocument.Data.Impuestos.Traslados.Count; i++) { if (electronicDocument.Data.Impuestos.Traslados[i].Tipo.Value == "IVA") { importe = electronicDocument.Data.Impuestos.Traslados[i].Importe.Value; tasa = electronicDocument.Data.Impuestos.Traslados[i].Tasa.Value; break; } } cel = new Cell(new Phrase("IVA " + tasa.ToString() + " %", f5B)); cel.VerticalAlignment = Element.ALIGN_MIDDLE; cel.HorizontalAlignment = Element.ALIGN_RIGHT; cel.BorderWidthTop = 0; cel.BorderWidthLeft = 0; cel.BorderWidthRight = 0; cel.BorderWidthBottom = 0; comentarios.AddCell(cel); cel = new Cell(new Phrase(electronicDocument.Data.Impuestos.TotalTraslados.Value.ToString("C", _c2), f5)); cel.VerticalAlignment = Element.ALIGN_MIDDLE; cel.HorizontalAlignment = Element.ALIGN_RIGHT; cel.BorderWidthTop = 0; cel.BorderWidthLeft = 0; cel.BorderWidthRight = (float).5; cel.BorderWidthBottom = (float).5; cel.BorderColor = gris; cel.Colspan = 2; comentarios.AddCell(cel); cel = new Cell(new Phrase("Total", f5B)); cel.VerticalAlignment = Element.ALIGN_MIDDLE; cel.HorizontalAlignment = Element.ALIGN_RIGHT; cel.BorderWidthTop = 0; cel.BorderWidthLeft = 0; cel.BorderWidthRight = 0; cel.BorderWidthBottom = (float).5; cel.BorderColor = gris; comentarios.AddCell(cel); cel = new Cell(new Phrase(electronicDocument.Data.Total.Value.ToString("C", _c2), f5)); cel.VerticalAlignment = Element.ALIGN_MIDDLE; cel.HorizontalAlignment = Element.ALIGN_RIGHT; cel.BorderWidthTop = 0; cel.BorderWidthLeft = 0; cel.BorderWidthRight = (float).5; cel.BorderWidthBottom = (float).5; cel.BorderColor = gris; cel.Colspan = 2; comentarios.AddCell(cel); #endregion #region "Construimos Tabla Datos CFDi" DefaultSplitCharacter split = new DefaultSplitCharacter(); Table adicional = new Table(3); float[] headerwidthsAdicional = { 20, 25, 55 }; adicional.Widths = headerwidthsAdicional; adicional.WidthPercentage = 100; adicional.Padding = 1; adicional.Spacing = 1; adicional.BorderWidth = (float).5; adicional.DefaultCellBorder = 1; adicional.BorderColor = gris; if (timbrar) { #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 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; cel = new Cell(imageQRCode); cel.VerticalAlignment = Element.ALIGN_MIDDLE; cel.HorizontalAlignment = Element.ALIGN_CENTER; cel.BorderColor = gris; cel.BorderWidthTop = 0; cel.BorderWidthRight = (float).5; cel.BorderWidthLeft = 0; cel.BorderWidthBottom = 0; cel.Rowspan = 6; adicional.AddCell(cel); par = new Paragraph(); par.SetLeading(7f, 0f); par.Add(new Chunk("SELLO DIGITAL DEL EMISOR\n", f5L)); par.Add(new Chunk(electronicDocument.Data.Sello.Value, f5).SetSplitCharacter(split)); cel = new Cell(par); cel.BorderColor = gris; cel.BorderWidthTop = 0; cel.BorderWidthRight = 0; cel.BorderWidthLeft = 0; cel.BorderWidthBottom = (float).5; cel.Colspan = 2; adicional.AddCell(cel); cel = new Cell(new Phrase("FOLIO FISCAL:", f5L)); cel.BorderColor = gris; cel.BorderWidthTop = 0; cel.BorderWidthRight = 0; cel.BorderWidthLeft = 0; cel.BorderWidthBottom = 0; adicional.AddCell(cel); cel = new Cell(new Phrase(objTimbre.Uuid.Value.ToUpper(), f5)); cel.BorderColor = gris; cel.BorderWidthTop = 0; cel.BorderWidthRight = 0; cel.BorderWidthLeft = (float).5; cel.BorderWidthBottom = 0; adicional.AddCell(cel); cel = new Cell(new Phrase("FECHA Y HORA DE CERTIFICACION:", f5L)); cel.BorderColor = gris; cel.BorderWidthTop = (float).5; cel.BorderWidthRight = 0; cel.BorderWidthLeft = 0; cel.BorderWidthBottom = 0; adicional.AddCell(cel); string[] fechaTimbrado = Convert.ToDateTime(objTimbre.FechaTimbrado.Value).GetDateTimeFormats('s'); cel = new Cell(new Phrase(fechaTimbrado[0], f5)); cel.BorderColor = gris; cel.BorderWidthTop = (float).5; cel.BorderWidthRight = 0; cel.BorderWidthLeft = (float).5; cel.BorderWidthBottom = 0; adicional.AddCell(cel); cel = new Cell(new Phrase("No. DE SERIE DEL CERTIFICADO DEL SAT:", f5L)); cel.BorderColor = gris; cel.BorderWidthTop = (float).5; cel.BorderWidthRight = 0; cel.BorderWidthLeft = 0; cel.BorderWidthBottom = 0; adicional.AddCell(cel); cel = new Cell(new Phrase(objTimbre.NumeroCertificadoSat.Value, f5)); cel.BorderColor = gris; cel.BorderWidthTop = (float).5; cel.BorderWidthRight = 0; cel.BorderWidthLeft = (float).5; cel.BorderWidthBottom = 0; adicional.AddCell(cel); cel = new Cell(new Phrase("No. DE SERIE DEL CERTIFICADO DEL EMISOR:", f5L)); cel.BorderColor = gris; cel.BorderWidthTop = (float).5; cel.BorderWidthRight = 0; cel.BorderWidthLeft = 0; cel.BorderWidthBottom = (float).5; adicional.AddCell(cel); cel = new Cell(new Phrase(electronicDocument.Data.NumeroCertificado.Value, f5)); cel.BorderColor = gris; cel.BorderWidthTop = (float).5; cel.BorderWidthRight = 0; cel.BorderWidthLeft = (float).5; cel.BorderWidthBottom = (float).5; adicional.AddCell(cel); par = new Paragraph(); par.SetLeading(7f, 0f); par.Add(new Chunk("TIPO DE COMPROBANTE: ", f5L)); par.Add(new Chunk(electronicDocument.Data.TipoComprobante.Value + " | ", f5)); par.Add(new Chunk("Moneda: ", f5L)); par.Add(new Chunk(electronicDocument.Data.Moneda.Value + " | ", f5)); par.Add(new Chunk("TASA DE CAMBIO: ", f5L)); string tasaCambio = electronicDocument.Data.TipoCambio.Value; string regimenes = ""; if (tasaCambio.Length > 0) { par.Add(new Chunk(Convert.ToDouble(tasaCambio).ToString("C", _ci) + " | ", f5)); } else { par.Add(new Chunk(" | ", f5)); } par.Add(new Chunk("FORMA DE PAGO: ", f5L)); par.Add(new Chunk(electronicDocument.Data.FormaPago.Value + " | ", f5)); par.Add(new Chunk("MÉTODO DE PAGO: ", f5L)); par.Add(new Chunk(electronicDocument.Data.MetodoPago.Value, f5)); if (electronicDocument.Data.Emisor.Regimenes.Count > 0) { for (int u = 0; u < electronicDocument.Data.Emisor.Regimenes.Count; u++) regimenes += electronicDocument.Data.Emisor.Regimenes[u].Regimen.Value.ToString() + ","; par.Add(new Chunk(" | ", f5)); par.Add(new Chunk("RÉGIMEN FISCAL: ", f5L)); par.Add(new Chunk(regimenes.Substring(0, regimenes.Length - 1).ToString(), f5)); par.Add(new Chunk(" | ", f5)); } if (electronicDocument.Data.CondicionesPago.Value.ToString().Length > 0) { par.Add(new Chunk(" | ", f5)); par.Add(new Chunk("CONDICIONES DE PAGO: ", f5L)); par.Add(new Chunk(electronicDocument.Data.CondicionesPago.Value.ToString(), f5)); par.Add(new Chunk(" | ", f5)); } if (electronicDocument.Data.NumeroCuentaPago.Value.ToString().Length > 0) { par.Add(new Chunk(" | ", f5)); par.Add(new Chunk("No. CUENTA: ", f5L)); par.Add(new Chunk(electronicDocument.Data.NumeroCuentaPago.Value, f5)); par.Add(new Chunk(" | ", f5)); } cel.BorderColor = gris; cel = new Cell(par); cel.BorderWidthTop = 0; cel.BorderWidthRight = 0; cel.BorderWidthLeft = 0; cel.BorderWidthBottom = 0; cel.Colspan = 2; cel.BorderColor = gris; adicional.AddCell(cel); if (electronicDocument.Data.LugarExpedicion.Value.Length > 0) { par = new Paragraph(); par.SetLeading(7f, 0f); par.Add(new Chunk("LUGAR EXPEDICIÓN: ", f5L)); par.Add(new Chunk(electronicDocument.Data.LugarExpedicion.Value, f5)); cel = new Cell(par); cel.BorderColor = gris; cel.BorderWidthTop = (float).5; cel.BorderWidthRight = 0; cel.BorderWidthLeft = 0; cel.BorderWidthBottom = 0; cel.Colspan = 3; adicional.AddCell(cel); } par = new Paragraph(); par.SetLeading(7f, 0f); par.Add(new Chunk("CADENA ORIGINAL DEL COMPLEMENTO DE CERTIFICACIÓN DIGITAL DEL SAT\n", f5L)); par.Add(new Chunk(electronicDocument.FingerPrintPac, f5).SetSplitCharacter(split)); cel = new Cell(par); cel.BorderColor = gris; cel.BorderWidthTop = (float).5; cel.BorderWidthRight = 0; cel.BorderWidthLeft = 0; cel.BorderWidthBottom = (float).5; cel.Colspan = 3; adicional.AddCell(cel); par = new Paragraph(); par.KeepTogether = true; par.SetLeading(7f, 0f); par.Add(new Chunk("SELLO DIGITAL DEL SAT\n", f5L)); par.Add(new Chunk(objTimbre.SelloSat.Value, f5).SetSplitCharacter(split)); cel = new Cell(par); cel.BorderColor = gris; cel.BorderWidthTop = 0; cel.BorderWidthRight = 0; cel.BorderWidthLeft = 0; cel.BorderWidthBottom = 0; cel.Colspan = 3; adicional.AddCell(cel); } #endregion #region "Construimos Tabla del Footer" PdfPTable footer = new PdfPTable(1); footer.WidthPercentage = 100; footer.TotalWidth = document.PageSize.Width - document.LeftMargin - document.RightMargin; cell = new PdfPCell(new Phrase("", f5)); cell.BorderWidthTop = 0; cell.BorderWidthLeft = 0; cell.BorderWidthRight = 0; cell.BorderWidthBottom = 0; footer.AddCell(cell); cell = new PdfPCell(new Phrase("ESTE DOCUMENTO ES UNA REPRESENTACIÓN IMPRESA DE UN CFDI", titulo)); cell.VerticalAlignment = Element.ALIGN_MIDDLE; cell.HorizontalAlignment = Element.ALIGN_CENTER; cell.BackgroundColor = azul; cell.BorderWidthTop = 0; cell.BorderWidthLeft = 0; cell.BorderWidthRight = 0; cell.BorderWidthBottom = 0; footer.AddCell(cell); #endregion sol.encFolioFiscal = encabezadoFolio; sol.encComprobante = encabezadoComprobante; sol.encComprobante1 = encabezadoComprobante1; sol.encTitulos = encabezadoDetalle; sol.adicional = adicional; sol.footer = footer; document.Open(); document.Add(tableConceptos); document.Add(comentarios); document.Add(adicional); string filePdfExt = pathPdf.Replace(_rutaDocs, _rutaDocsExt); string urlPathFilePdf = filePdfExt.Replace(@"\", "/"); document.Close(); writer.Close(); fs.Close(); //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; } }
/// <summary> /// 将datagirdview中的数据导出到pdf文件中 /// </summary> /// <returns></returns> private bool ExportDataToPDFTable() { bool rt = true; Document doc = new Document(iTextSharp.text.PageSize.A4, 25, 25, 25, 25); string path = System.Environment.CurrentDirectory; if(!Directory.Exists(string.Format("{0}/Report",path))) { Directory.CreateDirectory(string.Format("{0}/Report",path)); } string pdfFilePath = string.Format("{0}/Report/{1}.pdf", System.Environment.CurrentDirectory, DateTime.Now.ToString("yyyyMMddHHmmss")); PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(pdfFilePath, FileMode.Create)); doc.AddCreationDate(); doc.Open(); BaseFont bfSon = BaseFont.CreateFont(@"D:\CodeRepo\STBY-H\QTP.ClientShell\font\simsun.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); Font font8 = new Font(bfSon, 8); Paragraph paragraph = new Paragraph("CASCO STBY-H 综合测试", font8); Paragraph pTotalTest = new Paragraph(string.Format("总测试次数:{0}", txb_testcount.Text.ToString()), font8); Paragraph pHaveTest = new Paragraph(string.Format("已测试次数:{0}", txb_testedcount.Text.ToString()), font8); DataTable dt = GetDgvToTable(dataGridViewX1); try { if (dt != null) { int numColumns = dt.Columns.Count; PdfPTable pdfTable = new PdfPTable(numColumns); PdfPCell pdfPCell = null; pdfPCell = new PdfPCell(new Phrase(new Chunk("序号", font8))); pdfTable.AddCell(pdfPCell); pdfPCell = new PdfPCell(new Phrase(new Chunk("测试项", font8))); pdfTable.AddCell(pdfPCell); pdfPCell = new PdfPCell(new Phrase(new Chunk("单项测试次数", font8))); pdfTable.AddCell(pdfPCell); pdfPCell = new PdfPCell(new Phrase(new Chunk("测试次数", font8))); pdfTable.AddCell(pdfPCell); pdfPCell = new PdfPCell(new Phrase(new Chunk("测试结果", font8))); pdfTable.AddCell(pdfPCell); pdfPCell = new PdfPCell(new Phrase(new Chunk("备注", font8))); pdfTable.AddCell(pdfPCell); for (int rows = 0; rows < dt.Rows.Count; rows++) { for (int column = 0; column < dt.Columns.Count; column++) { pdfPCell = new PdfPCell(new Phrase(new Chunk(dt.Rows[rows][column].ToString(), font8))); pdfTable.AddCell(pdfPCell); } } pdfTable.SpacingBefore = 15f; doc.Add(paragraph); doc.Add(pTotalTest); doc.Add(pHaveTest); doc.Add(pdfTable); } } catch (System.Exception ex) { rt = false; } finally { doc.Close(); } return rt; }
protected override Stream Read() { Document doc = new Document(PageSize.A4, 50, 50, 50, 50); doc.AddTitle(Title); doc.AddCreationDate(); doc.AddCreator("iTextSharp"); doc.AddAuthor("文化中国"); doc.AddSubject(w.Excerpt); doc.AddKeywords(w.Tags); using (MemoryStream stream = new MemoryStream()) { PdfWriter writer = PdfWriter.GetInstance(doc, stream); writer.SetEncryption(true, null, null, 0); writer.PageEvent = new HeaderFooterPdfPageEventHelper(); doc.Open(); Paragraph p = new Paragraph(Title, font); p.Alignment = 1; doc.Add(p); MatchCollection matches = regex.Matches(w.Script.Text); foreach (Match m in matches) { Chunk chunk = new Chunk(m.Groups["cont"].Value); switch (m.Groups["tag"].Value.ToLower()) { case "h1": font.Color = BaseColor.WHITE; chunk.SetBackground(BaseColor.DARK_GRAY); break; case "p": font.Color = BaseColor.BLACK; break; } chunk.Font = font; p = new Paragraph(chunk); p.SetLeading(0.0f, 2.0f); p.FirstLineIndent = 20f; p.Alignment = 0; doc.Add(p); } doc.Close(); return new MemoryStream(stream.GetBuffer()); } }
protected override Stream Read() { Document doc = new Document(PageSize.A4, 50, 50, 50, 50); doc.AddTitle(Title); doc.AddCreationDate(); doc.AddCreator("iTextSharp"); doc.AddAuthor("文化中国"); doc.AddSubject(f.Brief); using (MemoryStream stream = new MemoryStream()) { PdfWriter writer = PdfWriter.GetInstance(doc, stream); writer.SetEncryption(true, null, null, PdfWriter.ALLOW_PRINTING); writer.ViewerPreferences = PdfWriter.PageModeUseOutlines; writer.PageEvent = new HeaderFooterPdfPageEventHelper(); doc.Open(); foreach (var w in f.Webcasts.Where(w => w.Script != null).OrderBy(w => w.Aired)) { Paragraph p = new Paragraph(w.Title, font); p.Alignment = 1; Chapter chapter = new Chapter(p, 1); chapter.NumberDepth = 0; chapter.BookmarkTitle = w.Title; chapter.TriggerNewPage = true; doc.Add(chapter); MatchCollection matches = regex.Matches(w.Script.Text); foreach (Match m in matches) { Chunk chunk = new Chunk(m.Groups["cont"].Value); switch (m.Groups["tag"].Value.ToLower()) { case "h1": font.Color = BaseColor.WHITE; chunk.SetBackground(BaseColor.DARK_GRAY); break; case "p": font.Color = BaseColor.BLACK; break; } chunk.Font = font; p = new Paragraph(chunk); p.SetLeading(0.0f, 2.0f); p.FirstLineIndent = 20f; p.Alignment = 0; doc.Add(p); } } doc.Close(); return new MemoryStream(stream.GetBuffer()); } }
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 void bill(string siparisNo, string Kullaniciid) { this.siparisNo = siparisNo; this.Kullaniciid = Kullaniciid; iTextSharp.text.pdf.BaseFont STF_Helvetica_Turkish = iTextSharp.text.pdf.BaseFont.CreateFont("Helvetica", "CP1254", iTextSharp.text.pdf.BaseFont.NOT_EMBEDDED); iTextSharp.text.Font fontTitle = new iTextSharp.text.Font(STF_Helvetica_Turkish, 11, iTextSharp.text.Font.NORMAL); SqlCommand cdname = new SqlCommand("select *from Tbl_Kullanici where KullaniciId=@p1", conn.connection()); cdname.Parameters.AddWithValue("@p1", Kullaniciid); SqlDataReader drname = cdname.ExecuteReader(); while (drname.Read()) { name = drname[1].ToString() + " " + drname[2].ToString(); e_mail = drname[3].ToString(); } conn.connection().Close(); iTextSharp.text.Document pdf = new iTextSharp.text.Document(); filePath = HttpContext.Current.Server.MapPath("~/Bills/" + siparisNo + "_Fatura.Pdf"); PdfWriter.GetInstance(pdf, new FileStream(filePath, FileMode.Create)); pdf.AddAuthor("BookSite"); pdf.AddCreator("BookSite"); pdf.AddCreationDate(); pdf.AddSubject("Fatura"); PdfPTable table = new PdfPTable(4); PdfPCell cell = new PdfPCell(new Phrase(name + " FATURA - " + siparisNo, fontTitle)); cell.Colspan = 4; cell.HorizontalAlignment = 1; table.AddCell(cell); table.AddCell(new Phrase("Kitap Adı", fontTitle)); table.AddCell(new Phrase("Miktar", fontTitle)); table.AddCell(new Phrase("Birim Fiyat", fontTitle)); table.AddCell(new Phrase("Toplam Fiyat", fontTitle)); SqlCommand cd = new SqlCommand("select *from Tbl_Sepet where SiparisNo=@p1", conn.connection()); cd.Parameters.AddWithValue("@p1", siparisNo); SqlDataReader dr = cd.ExecuteReader(); while (dr.Read()) { table.AddCell(new Phrase(dr[7].ToString(), fontTitle)); table.AddCell(new Phrase(dr[2].ToString(), fontTitle)); table.AddCell(new Phrase(dr[6].ToString(), fontTitle)); table.AddCell(new Phrase(dr[3].ToString(), fontTitle)); } conn.connection().Close(); if (pdf.IsOpen() == false) { pdf.Open(); } pdf.Add(table); pdf.Close(); }
//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); }
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(); StringBuilder sbConfigFactParms = new StringBuilder(); _ci.NumberFormat.CurrencyDecimalDigits = 2; ElectronicDocument electronicDocument = (ElectronicDocument)htFacturaxion["electronicDocument"]; Data objTimbre = (Data)htFacturaxion["objTimbre"]; timbrar = Convert.ToBoolean(htFacturaxion["timbrar"]); Int64 idCfdi = Convert.ToInt64(htFacturaxion["idCfdi"]); #region "Extraemos Datos Adicionales" DataTable dtOpcionalDetalle = new DataTable(); StringBuilder sbOpcionalDetalle = new StringBuilder(); sbOpcionalDetalle. Append("SELECT "). Append("COALESCE(campo1, '0') AS noIdent "). Append("FROM opcionalDetalle "). Append("WHERE idCFDI = @0 "); dtOpcionalDetalle = dal.QueryDT("DS_FE", sbOpcionalDetalle.ToString(), "F:I:" + idCfdi, hc); if (dtOpcionalDetalle.Rows.Count == 0) { for (int i = 1; i <= electronicDocument.Data.Conceptos.Count; i++) { dtOpcionalDetalle.Rows.Add("0"); } } #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("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("C.P. ").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("C.P. ").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("C.P. ").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, 20, 20, 20, 40); document.AddAuthor("Facturaxion"); document.AddCreator("r3Take"); document.AddCreationDate(); //FileStream fs = new FileStream(pathPdf, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite); pdfPageEventHandlerCED110324NN4 pageEventHandler = new pdfPageEventHandlerCED110324NN4(); 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; azul = new Color(22, 111, 168); blanco = new Color(255, 255, 255); Link = new Color(7, 73, 208); gris = new Color(236, 236, 236); grisOX = new Color(220, 215, 220); rojo = new Color(230, 7, 7); lbAzul = new Color(43, 145, 175); EM = BaseFont.CreateFont(@"C:\Windows\Fonts\VERDANA.TTF", BaseFont.WINANSI, BaseFont.NOT_EMBEDDED); f5 = new Font(EM, 5); f5B = new Font(EM, 5, Font.BOLD); f5BBI = new Font(EM, 5, Font.BOLDITALIC); f6 = new Font(EM, 6); f6B = new Font(EM, 6, Font.BOLD); f7B = new Font(EM, 7, Font.BOLD); f6L = new Font(EM, 6, Font.BOLD, Link); f5L = new Font(EM, 5, Font.BOLD, lbAzul); f8B = new Font(EM, 8, Font.BOLD); f8L = new Font(EM, 8); f8LA = new Font(EM, 8, 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" formatoCED110324NN4(document, electronicDocument, objTimbre, pageEventHandler, idCfdi, dtOpcionalDetalle, htDatosCfdi, HTC); #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; } }
private void To_pdf() { Document doc = new Document(PageSize.A4.Rotate(), 10, 10, 10, 10); SaveFileDialog saveFileDialog1 = new SaveFileDialog(); saveFileDialog1.InitialDirectory = @"C:"; saveFileDialog1.Title = "Guardar Reporte"; saveFileDialog1.DefaultExt = "pdf"; saveFileDialog1.Filter = "pdf Files (*.pdf)|*.pdf| All Files (*.*)|*.*"; saveFileDialog1.FilterIndex = 2; saveFileDialog1.RestoreDirectory = true; string filename = ""; if (saveFileDialog1.ShowDialog() == DialogResult.OK) { filename = saveFileDialog1.FileName; } if (filename.Trim() != "") { FileStream file = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite); PdfWriter.GetInstance(doc, file); doc.Open(); string remito = "Autorizo: OSVALDO SANTIAGO ESTRADA"; string envio = "Fecha:" + DateTime.Now.ToString(); Chunk chunk = new Chunk("Reporte de General Usuarios", FontFactory.GetFont("ARIAL", 20, iTextSharp.text.Font.BOLD)); doc.Add(new Paragraph(chunk)); doc.Add(new Paragraph(" ")); doc.Add(new Paragraph(" ")); doc.Add(new Paragraph("------------------------------------------------------------------------------------------")); doc.Add(new Paragraph("Lagos de moreno Jalisco")); doc.Add(new Paragraph(remito)); doc.Add(new Paragraph(envio)); doc.Add(new Paragraph("------------------------------------------------------------------------------------------")); doc.Add(new Paragraph(" ")); doc.Add(new Paragraph(" ")); doc.Add(new Paragraph(" ")); GenerarDocumento(doc); doc.AddCreationDate(); doc.Add(new Paragraph("______________________________________________", FontFactory.GetFont("ARIAL", 20, iTextSharp.text.Font.BOLD))); doc.Add(new Paragraph("Firma", FontFactory.GetFont("ARIAL", 20, iTextSharp.text.Font.BOLD))); doc.Close(); Process.Start(filename);//Esta parte se puede omitir, si solo se desea guardar el archivo, y que este no se ejecute al instante } }
//create a new pdf document private void btn_Prepare_Click(object sender, EventArgs e) { //if all of these null if ((textboxAuthor.Text == "" || textboxCreator.Text == "" || textboxSubject.Text == "" || textboxKeyword.Text == "" || rtextboxParagraph.Text == "") || checkTextboxValues()) { MessageBox.Show("PLEASE FILL IN THE TEXTBOXES", "Message Box", MessageBoxButtons.OKCancel, MessageBoxIcon.Information); } else { //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(textboxAuthor.Text); //Creation Date, need for create a new pdf document report.AddCreationDate(); //Creator, need for create a new pdf document report.AddCreator(textboxCreator.Text); //Subject, need for create a new pdf document report.AddSubject(textboxSubject.Text); //Keywords, need for create a new pdf document report.AddKeywords(textboxKeyword.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(rtextboxParagraph.Text)); //open the connection db.openConnection(); //a command line for add a new document SqlCommand query = new SqlCommand("INSERT INTO Table_DOCUMENT(file_Name,file_Path,file_CreationDate,u_ID) VALUES(@fn, @fp, @cd,@uid)", db.getConnection()); //add the value in the textbox to @fn query.Parameters.AddWithValue("@fn", textboxFileName.Text); //add the value in the textbox to @fp query.Parameters.AddWithValue("@fp", textboxFilePath.Text + @"\" + textboxFileName.Text); //add the value in the combobox to @uid query.Parameters.AddWithValue("@uid", comboboxUserID.Text); //add the value in the textbox to @cd query.Parameters.AddWithValue("@cd", textboxFileDate.Text); if (textboxFileDate.Text == "" || textboxFileName.Text == "" || comboboxUserID.Text == "") { MessageBox.Show("PLEASE ENTER THE NAME OF THE FILE: FILE NAME, CREATION DATE, OR USER ID", "Message Box", MessageBoxButtons.OKCancel, MessageBoxIcon.Error); } else if (checkFileName()) { MessageBox.Show("This File Name Already Exist, Select A Different One", "Message Box", MessageBoxButtons.OKCancel, MessageBoxIcon.Error); textboxFileName.Text = ""; } else { //execute the query if (query.ExecuteNonQuery() == 1) { //the record is successfully MessageBox.Show("DATA WERE RECORDED", "Message Box", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation); //return the default values and colors dateTimePicker1.ResetText(); textboxFileID.Text = "file ID"; textboxFileID.ForeColor = Color.DimGray; textboxFileName.Text = "filename.pdf"; textboxFileName.ForeColor = Color.DimGray; comboboxUserID.Text = "user id"; comboboxUserID.ForeColor = Color.DimGray; textboxFilePath.Text = "file path"; textboxFilePath.ForeColor = Color.DimGray; dateTimePicker1.ResetText(); textboxFileDate.Text = "DD.MM.YYYY"; textboxFileDate.ForeColor = Color.DimGray; textboxSubject.Text = ""; rtextboxParagraph.Text = ""; dateTimePicker1.Text = ""; textboxAuthor.Text = ""; textboxCreator.Text = ""; textboxKeyword.Text = ""; } else { MessageBox.Show("ERROR", "Message Box", MessageBoxButtons.OKCancel, MessageBoxIcon.Error); } } //close the report report.Close(); //close the connection db.closeConnection(); } }
/// <inheritdoc /> public override async Task <ExportedRoleplay> ExportAsync(Roleplay roleplay) { // Create our document var pdfDoc = new Document(); var filePath = Path.GetTempFileName(); using (var of = File.Create(filePath)) { var writer = PdfWriter.GetInstance(pdfDoc, of); writer.Open(); pdfDoc.Open(); var owner = await this.Guild.GetUserAsync((ulong)roleplay.Owner.DiscordID); pdfDoc.AddAuthor(owner.Nickname); pdfDoc.AddCreationDate(); pdfDoc.AddCreator("DIGOS Ambassador"); pdfDoc.AddTitle(roleplay.Name); var joinedUsers = await Task.WhenAll ( roleplay.JoinedUsers.Select ( async p => { var guildUser = await this.Guild.GetUserAsync((ulong)p.User.DiscordID); if (guildUser is null) { var messageByUser = roleplay.Messages.FirstOrDefault ( m => m.AuthorDiscordID == p.User.DiscordID ); if (messageByUser is null) { return($"Unknown user ({p.User.DiscordID})"); } return(messageByUser.AuthorNickname); } return(guildUser.Username); } ) ); pdfDoc.Add(CreateTitle(roleplay.Name)); pdfDoc.Add(CreateParticipantList(joinedUsers)); pdfDoc.NewPage(); var messages = roleplay.Messages.OrderBy(m => m.Timestamp).DistinctBy(m => m.Contents); foreach (var message in messages) { pdfDoc.Add(CreateMessage(message.AuthorNickname, message.Contents)); } pdfDoc.Close(); writer.Flush(); writer.Close(); } var resultFile = File.OpenRead(filePath); var exported = new ExportedRoleplay(roleplay.Name, ExportFormat.PDF, resultFile); return(exported); }
private void Speichern(string filename) { try { Document document = new Document(); PdfWriter.GetInstance(document, new FileStream(filename, FileMode.Create)); document.AddTitle("Portscanner Report"); document.AddCreationDate(); document.Open(); document.Add(new Paragraph("Portscanner: IP/Port list", FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 16, iTextSharp.text.Font.UNDERLINE))); document.Add(new Paragraph(" ")); foreach (ListViewItem item in lv_Port.Items) { document.Add(new Paragraph("IP: " + item.SubItems[0].Text + item.SubItems[1].Text)); document.Add(new Paragraph("Port: " + item.SubItems[1].Text)); document.Add(new Paragraph("Status: " + item.SubItems[4].Text)); document.Add(new Paragraph(" ")); } document.Close(); } catch (IOException) { MessageBox.Show("The file is in use. Please close all applications accessing this file and try again.", "Access not possible", MessageBoxButtons.OK); } catch (Exception ex) { Console.WriteLine("Fehler beim Speichern" + ex); } }
public void GerarRelatorio(Lancamento lancamentoGerar) { iTextSharp.text.Document doc = new iTextSharp.text.Document(PageSize.A4, 40, 40, 40, 80); doc.AddCreationDate(); Directory.CreateDirectory(System.AppDomain.CurrentDomain.BaseDirectory + @"\Relatorios"); string nomeRelatorio = "relatorio_" + lancamentoGerar.Id + "_" + lancamentoGerar.Id + DateTime.Now.Millisecond + ".pdf"; string caminho = System.AppDomain.CurrentDomain.BaseDirectory + @"\Relatorios\" + nomeRelatorio; // exception interna porém é possível continuar PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(doc, new FileStream(caminho, FileMode.OpenOrCreate)); doc.Open(); // Título inicial Paragraph paragrafo = new Paragraph("", new Font(Font.NORMAL, 12)) { Alignment = Element.ALIGN_LEFT, Font = new Font(Font.FontFamily.TIMES_ROMAN, 13, 1) }; paragrafo.Add("Relatório de Decisão"); doc.Add(paragrafo); paragrafo.Clear(); // Data paragrafo.Font = new Font(Font.FontFamily.TIMES_ROMAN, 11, 1) { Color = new BaseColor(128, 128, 128) }; paragrafo.Add("Data : " + DateTime.Now.ToString()); doc.Add(paragrafo); paragrafo.Clear(); doc.Add(new Paragraph(" ")); LineSeparator line = new LineSeparator(1f, 100f, new BaseColor(0, 0, 0), Element.ALIGN_LEFT, 1); doc.Add(line); // Dados lançamento paragrafo.Font = new Font(Font.FontFamily.TIMES_ROMAN, 12, 1); // nome var firstFont = new Font(Font.FontFamily.TIMES_ROMAN, 12, 1); var secondFont = FontFactory.GetFont("Times New Roman", 12, new BaseColor(128, 128, 128)); Chunk title; Chunk description; Phrase phrase; title = new Chunk("Nome da decisão : ", firstFont); description = new Chunk(lancamentoGerar.Nome, secondFont); phrase = new Phrase(title) { description }; phrase.Add("\n"); doc.Add(phrase); // descrição title = new Chunk("Descrição da decisão : ", firstFont); description = new Chunk(lancamentoGerar.Descricao, secondFont); phrase = new Phrase(title) { description }; phrase.Add("\n"); doc.Add(phrase); // data title = new Chunk("Data da decisão : ", firstFont); description = new Chunk(lancamentoGerar.Data, secondFont); phrase = new Phrase(title) { description }; phrase.Add("\n"); doc.Add(phrase); // modelo title = new Chunk("Modelo utilizado : ", firstFont); description = new Chunk(lancamentoGerar.Modelo.Nome, secondFont); phrase = new Phrase(title) { description }; phrase.Add("\n"); doc.Add(phrase); doc.Add(new Paragraph(" ")); doc.Add(line); // Tabela 1 paragrafo.Font = new Font(Font.FontFamily.TIMES_ROMAN, 12, 1); paragrafo.Alignment = Element.ALIGN_CENTER; paragrafo.Add("Tabela 1 - Informações sobre os elementos"); doc.Add(paragrafo); doc.Add(new Paragraph(" ")); PdfPTable table = new PdfPTable(1 + lancamentoGerar.Modelo.Criterios.Count); table.AddCell(new Phrase(new Chunk("Nome", new Font(Font.FontFamily.TIMES_ROMAN, 12, 1)))); foreach (var criterio in lancamentoGerar.Modelo.Criterios) { table.AddCell(new Phrase(new Chunk(criterio.Nome, new Font(Font.FontFamily.TIMES_ROMAN, 12, 1)))); } foreach (var element in lancamentoGerar.Elementos) { table.AddCell(element.Nome); foreach (var criterio in element.Criterios) { table.AddCell(Convert.ToString(criterio.Importancia)); } } doc.Add(table); doc.Add(new Paragraph(" ")); doc.Add(line); paragrafo.Clear(); // Tabela 2 paragrafo.Font = new Font(Font.FontFamily.TIMES_ROMAN, 12, 1); paragrafo.Alignment = Element.ALIGN_CENTER; paragrafo.Add("Tabela 2 - Dados da tomada de decisão"); doc.Add(paragrafo); doc.Add(new Paragraph(" ")); table = new PdfPTable(2); table.AddCell(new Phrase(new Chunk("Nome", new Font(Font.FontFamily.TIMES_ROMAN, 12, 1)))); table.AddCell(new Phrase(new Chunk("Peso", new Font(Font.FontFamily.TIMES_ROMAN, 12, 1)))); foreach (var element in lancamentoGerar.ItensDecisao.OrderByDescending(entry => entry.Peso)) { table.AddCell(element.Nome); table.AddCell(Convert.ToString(element.Peso)); } doc.Add(table); doc.Close(); System.Diagnostics.Process.Start(caminho); }
public static byte[] FromHtml(string html) { using (MemoryStream memoryStream = new MemoryStream()) { Document document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4); //PdfAWriter writer = PdfAWriter.GetInstance(document, ms, PdfAConformanceLevel.PDF_A_1B); PdfWriter writer = PdfWriter.GetInstance(document, memoryStream); writer.PdfVersion = PdfWriter.VERSION_1_7; writer.SetTagged(); writer.ViewerPreferences = PdfWriter.DisplayDocTitle; writer.CloseStream = false; writer.InitialLeading = 12.5f; writer.CompressionLevel = PdfStream.BEST_COMPRESSION; //writer.SetFullCompression(); //Causa erro no padrão PDF_A_1* try { document.AddLanguage("pt-BR"); document.AddCreationDate(); writer.CreateXmpMetadata(); document.Open(); //FontFactory.RegisteredFonts.Add(""); FontFactory.RegisterDirectories(); ICC_Profile icc = ICC_Profile.GetInstance((byte[])Properties.Resources.ResourceManager.GetObject("icc_profile")); writer.SetOutputIntents("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", icc); //MemoryStream cssStream = new MemoryStream(Encoding.UTF8.GetBytes("html, html * { font-family: Arial, Arial, Arial!important; color: black!important; }")); MemoryStream cssStream = new MemoryStream(Encoding.UTF8.GetBytes("body { font-family: \"Courier New\", Courier, monospace!important; color: black!important; }")); MemoryStream htmlStream = new MemoryStream(Encoding.UTF8.GetBytes(html)); XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, htmlStream, cssStream); document.Close(); writer.Close(); } catch (Exception ex) { throw ex; } return memoryStream.ToArray(); } }
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 }
//pdf /// <summary> /// creates a PDF at path for the given files, for each file callback(success, file, message, Image) will be called /// </summary> public void CreatePdfFromFiles(string path, IEnumerable<string> files, Action<bool, string, string, Image> callback = null) { //if no callback use an empty one callback = callback ?? ((b,s1,s2,i) => { }); //create document and open Document doc = new Document(); doc.SetMargins(0, 0, 0, 0); PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read)); //writer.SetPdfVersion(PdfWriter.VERSION_1_7); writer.SetFullCompression(); doc.Open(); //set some metadata doc.AddTitle(Path.GetFileName(path).RemoveFromEnd(".pdf")); doc.AddCreationDate(); doc.AddCreator("created by " + appname + " @ " + homepage); //calculate page size if desired KSize psize = new KSize(); if (ensmallen || embiggen) { var e = files.Select(file => { var i = Image.GetInstance(new Uri(file)); return new KSize((int) i.Width, (int) i.Height); }); psize = embiggen ? e.MaxBy(s => s.area) : e.MinBy(s => s.area); } //process files foreach (string file in files) { Image i; try { i = Image.GetInstance(new Uri(file)); } catch (Exception ex) { callback(false, file, ex.Message, null); continue; } //set page size and add a new page (technically don't have to do this every time if psize isn't empty) doc.SetPageSize(psize.empty ? new Rectangle(i.Width, i.Height) : new Rectangle(psize.w, psize.h)); doc.NewPage(); //scale and add image if (psize.empty) { i.ScaleToFit(doc.PageSize.Width, doc.PageSize.Height); } else { // see https://stackoverflow.com/questions/6565703/math-algorithm-fit-image-to-screen-retain-aspect-ratio float rp = (float)psize.w / (float)psize.h; float ri = i.Width / i.Height; float iw = rp > ri ? i.Width * psize.h / i.Height : psize.w; float ih = rp > ri ? psize.h : i.Height * psize.w / i.Width; i.ScaleToFit(doc.PageSize.Width, doc.PageSize.Height); i.SetAbsolutePosition((psize.w - iw)/2, (psize.h - ih)/2); } i.Alt = Path.GetFileName(file); doc.Add(i); callback(true, file, null, i); } doc.Close(); }
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(); } }
public AsistenciaPersonal(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}/AsistenciaPersonal.pdf", empresa.Descripcion, departamento.Descripcion); // Vamos a buscar los datos que nos permitirtán armar elreporte IEnumerable<sp_LibroAsistenciaResult> resultado = 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> libroAsistencia = Mapper.Map<IEnumerable<sp_LibroAsistenciaResult>, IEnumerable<LibroAsistenciaDTO>>(resultado); if (libroAsistencia.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 libroAsistencia.Where(x => x.Rut != null).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 Asistencia Personal"); Paragraph parrafo = new Paragraph(); parrafo.Add(new Paragraph("Asistencia Personal", Titulo) { Alignment = Element.ALIGN_CENTER }); doc.Add(parrafo); // Texto PdfPTable tablaEncabezado = new PdfPTable(new float[] { 1, 5, 1, 5 }); tablaEncabezado.AddCell(new PdfPCell(new Phrase("Nombre:", Chico)) { Border = Rectangle.NO_BORDER }); tablaEncabezado.AddCell(new PdfPCell(new Phrase(empleado.NombreCompleto, Normal)) { Border = Rectangle.NO_BORDER, Colspan=3 }); tablaEncabezado.AddCell(new PdfPCell(new Phrase("Empresa:", Chico)) { Border = Rectangle.NO_BORDER }); tablaEncabezado.AddCell(new PdfPCell(new Phrase(empresa != null ? empresa.Descripcion.Trim() : String.Empty, Normal)) { Border = Rectangle.NO_BORDER }); tablaEncabezado.AddCell(new PdfPCell(new Phrase("Rut:", Chico)) { Border = Rectangle.NO_BORDER }); tablaEncabezado.AddCell(new PdfPCell(new Phrase(empleado.RutAufen, Normal)) { Border = Rectangle.NO_BORDER }); tablaEncabezado.AddCell(new PdfPCell(new Phrase("Sucursal o Planta:", Chico)) { Border = Rectangle.NO_BORDER }); tablaEncabezado.AddCell(new PdfPCell(new Phrase(empleado.SucursalPlanta, Normal)) { Border = Rectangle.NO_BORDER }); tablaEncabezado.AddCell(new PdfPCell(new Phrase("Cargo:", Chico)) { Border = Rectangle.NO_BORDER }); //tablaEncabezado.AddCell(new PdfPCell(new Phrase(empleado.Cargo, Normal)) { Border = Rectangle.NO_BORDER }); tablaEncabezado.AddCell(new PdfPCell(new Phrase(String.Empty, Normal)) { Border = Rectangle.NO_BORDER }); tablaEncabezado.AddCell(new PdfPCell(new Phrase("Centro de Costo:", Chico)) { Border = Rectangle.NO_BORDER }); tablaEncabezado.AddCell(new PdfPCell(new Phrase(String.Empty, Normal)) { Border = Rectangle.NO_BORDER }); tablaEncabezado.AddCell(new PdfPCell(new Phrase(String.Empty, Normal)) { Border = Rectangle.NO_BORDER }); tablaEncabezado.AddCell(new PdfPCell(new Phrase(String.Empty, Normal)) { Border = Rectangle.NO_BORDER }); tablaEncabezado.AddCell(new PdfPCell(new Phrase(String.Format("PERIODO: {0} a {1}", FechaDesde.ToShortDateString(), FechaHasta.ToShortDateString()), Normal)) { Colspan = 4, Border = Rectangle.NO_BORDER }); doc.Add(new Paragraph(" ")); tablaEncabezado.AddCell(new PdfPCell(GetNomenclatura()) { Colspan = 4 }); doc.Add(tablaEncabezado); doc.Add(new Phrase()); doc.Add(new Phrase()); // tabla PdfPTable tabla = new PdfPTable(new float[] { 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 4 }); // Primera lìnea cabecera tabla.AddCell(new PdfPCell(new Phrase("Fecha", Chico))); tabla.AddCell(new PdfPCell(new Phrase("HI", Chico)) { }); tabla.AddCell(new PdfPCell(new Phrase("HS", Chico))); tabla.AddCell(new PdfPCell(new Phrase("HCol", Chico))); tabla.AddCell(new PdfPCell(new Phrase("MI", Chico))); tabla.AddCell(new PdfPCell(new Phrase("MS", Chico))); tabla.AddCell(new PdfPCell(new Phrase("HTH", Chico))); tabla.AddCell(new PdfPCell(new Phrase("HTN", Chico))); tabla.AddCell(new PdfPCell(new Phrase("HE", Chico))); tabla.AddCell(new PdfPCell(new Phrase("ATR", Chico))); tabla.AddCell(new PdfPCell(new Phrase("ADL", Chico))); tabla.AddCell(new PdfPCell(new Phrase("Col.", Chico))); tabla.AddCell(new PdfPCell(new Phrase("S.Ent", Chico))); tabla.AddCell(new PdfPCell(new Phrase("Permisos", Chico))); foreach (var atraso in reporte) { //Fecha tabla.AddCell(new PdfPCell(new Phrase(atraso.Fecha.Value.ToString("ddd dd/MM"), Chico))); //Hora Ingreso tabla.AddCell(new PdfPCell(new Phrase(atraso.EntradaTeorica.HasValue ? atraso.EntradaTeorica.Value.ToShortTimeString() : null, Chico))); // Hora Salida tabla.AddCell(new PdfPCell(new Phrase(atraso.SalidaTeorica.HasValue ? atraso.SalidaTeorica.Value.ToShortTimeString() : null, Chico))); // Colaciòn por turno tabla.AddCell(new PdfPCell(new Phrase((int)atraso.TiempoColacion.Value.TotalHours + atraso.TiempoColacion.Value.ToString(@"\:mm"), Chico))); // Marca de entrada tabla.AddCell(new PdfPCell(new Phrase(atraso.Entrada.HasValue ? atraso.Entrada.Value.ToShortTimeString() : null, Chico))); // Marca de salida tabla.AddCell(new PdfPCell(new Phrase(atraso.Salida.HasValue ? atraso.Salida.Value.ToShortTimeString() : null, Chico))); //Horas pactadas po hombre tabla.AddCell(new PdfPCell(new Phrase(atraso.printHorasPactadas, Chico))); //Horas realizadas tabla.AddCell(new PdfPCell(new Phrase(atraso.printHorasReales.ToString(), Chico))); //Horas extra tabla.AddCell(new PdfPCell(new Phrase(atraso.printHorasExtra, Chico))); // Atraso tabla.AddCell(new PdfPCell(new Phrase(atraso.printAtraso, Chico))); // Salida adelantada tabla.AddCell(new PdfPCell(new Phrase(atraso.printSalidaAdelantada, Chico))); // Colación tabla.AddCell(new PdfPCell(new Phrase(atraso.printTiempoColacionReal, Chico))); // S.Ent tabla.AddCell(new PdfPCell(new Phrase(atraso.printSobreEntrada, Chico))); // Permisos tabla.AddCell(new PdfPCell(new Phrase(atraso.Observacion, Chico))); } //Subtotal tabla.AddCell(new PdfPCell(new Phrase("Sub Total", Chico)) { Colspan = 6 }); //Horas pactadas po hombre tabla.AddCell(new PdfPCell(new Phrase(LibroAsistenciaDTOHelpers.CalculaJornada(reporte), Chico))); //Horas realizadas tabla.AddCell(new PdfPCell(new Phrase(LibroAsistenciaDTOHelpers.CalculaAsistencia(reporte), Chico))); //Horas extra tabla.AddCell(new PdfPCell(new Phrase(LibroAsistenciaDTOHelpers.CalculaHorasExtra(reporte), Chico))); // Atraso tabla.AddCell(new PdfPCell(new Phrase(LibroAsistenciaDTOHelpers.CalculaAtrasoEntrada(reporte), Chico))); // Salida adelantada tabla.AddCell(new PdfPCell(new Phrase(LibroAsistenciaDTOHelpers.CalculaSalidaAdelantada(reporte), Chico))); // Colacón tabla.AddCell(new PdfPCell(new Phrase(LibroAsistenciaDTOHelpers.CalculaColacion(reporte), Chico))); // S.Ent tabla.AddCell(new PdfPCell(new Phrase(LibroAsistenciaDTOHelpers.CalculaSobreEntrada(reporte), Chico))); // Permisos tabla.AddCell(new PdfPCell(new Phrase("", Chico))); doc.Add(tabla); doc.Add(new Phrase()); // Resumen PdfPTable resumen = new PdfPTable(new float[] { 2, 1, 2, 1, 2, 1, 2, 1 }); //Días Trabajados resumen.AddCell(new PdfPCell(new Phrase("Días Trabajados", Chico)) { Border = Rectangle.NO_BORDER }); resumen.AddCell(new PdfPCell(new Phrase(LibroAsistenciaDTOHelpers.CalculaDiasTrabajdos(reporte), Chico)) { Border = Rectangle.NO_BORDER }); // resumen.AddCell(new PdfPCell(new Phrase("Horas Pactadas", Chico)) { Border = Rectangle.NO_BORDER }); resumen.AddCell(new PdfPCell(new Phrase(LibroAsistenciaDTOHelpers.CalculaAsistencia(reporte), Chico)) { Border = Rectangle.NO_BORDER }); // resumen.AddCell(new PdfPCell(new Phrase("Horas extras", Chico)) { Border = Rectangle.NO_BORDER }); resumen.AddCell(new PdfPCell(new Phrase(LibroAsistenciaDTOHelpers.CalculaHorasExtra(reporte), Chico)) { Border = Rectangle.NO_BORDER }); // resumen.AddCell(new PdfPCell(new Phrase("Errores de marca", Chico)) { Border = Rectangle.NO_BORDER }); resumen.AddCell(new PdfPCell(new Phrase(LibroAsistenciaDTOHelpers.CalculaErroresMarcaje(reporte), Chico)) { Border = Rectangle.NO_BORDER }); // resumen.AddCell(new PdfPCell(new Phrase("Días ausentes", Chico)) { Border = Rectangle.NO_BORDER }); resumen.AddCell(new PdfPCell(new Phrase(LibroAsistenciaDTOHelpers.CalculaDiasInasistencias(reporte), Chico)) { Border = Rectangle.NO_BORDER }); // resumen.AddCell(new PdfPCell(new Phrase("Horas Trabajadas", Chico)) { Border = Rectangle.NO_BORDER }); resumen.AddCell(new PdfPCell(new Phrase(LibroAsistenciaDTOHelpers.CalculaAsistencia(reporte), Chico)) { Border = Rectangle.NO_BORDER }); // resumen.AddCell(new PdfPCell(new Phrase("Vacaciones", Chico)) { Border = Rectangle.NO_BORDER }); resumen.AddCell(new PdfPCell(new Phrase("", Chico)) { Border = Rectangle.NO_BORDER }); // Aquí va una tabla con el espacio para la firma resumen.AddCell(new PdfPCell(new Phrase("", Chico)) { VerticalAlignment = Rectangle.ALIGN_BOTTOM, HorizontalAlignment = Rectangle.ALIGN_CENTER, Colspan = 2, Rowspan = 3, Border = Rectangle.NO_BORDER }); // resumen.AddCell(new PdfPCell(new Phrase("Días Atraso", Chico)) { Border = Rectangle.NO_BORDER }); resumen.AddCell(new PdfPCell(new Phrase(LibroAsistenciaDTOHelpers.CalculaDiasAtraso(reporte), Chico)) { Border = Rectangle.NO_BORDER }); // resumen.AddCell(new PdfPCell(new Phrase("Total Atraso", Chico)) { Border = Rectangle.NO_BORDER }); resumen.AddCell(new PdfPCell(new Phrase(LibroAsistenciaDTOHelpers.CalculaAtrasoEntrada(reporte), Chico)) { Border = Rectangle.NO_BORDER }); // resumen.AddCell(new PdfPCell(new Phrase("Licencias Médicas", Chico)) { Border = Rectangle.NO_BORDER }); resumen.AddCell(new PdfPCell(new Phrase("", Chico)) { Border = Rectangle.NO_BORDER }); // resumen.AddCell(new PdfPCell(new Phrase("Salidas", Chico)) { Border = Rectangle.NO_BORDER }); resumen.AddCell(new PdfPCell(new Phrase(LibroAsistenciaDTOHelpers.CalculaDiasSalidaAdelantada(reporte), Chico)) { Border = Rectangle.NO_BORDER }); // resumen.AddCell(new PdfPCell(new Phrase("Total Salidas", Chico)) { Border = Rectangle.NO_BORDER }); resumen.AddCell(new PdfPCell(new Phrase(LibroAsistenciaDTOHelpers.CalculaSalidaAdelantada(reporte), Chico)) { Border = Rectangle.NO_BORDER }); resumen.AddCell(new PdfPCell(new Phrase("", Chico)) { Border = Rectangle.NO_BORDER }); resumen.AddCell(new PdfPCell(new Phrase("", Chico)) { Border = Rectangle.NO_BORDER }); resumen.AddCell(new PdfPCell(new Phrase(" ", Chico)) { Border = Rectangle.NO_BORDER, Colspan = 8, Rowspan = 5 }); resumen.AddCell(new PdfPCell(new Phrase(" ", Chico)) { Border = Rectangle.NO_BORDER, Colspan = 8 }); resumen.AddCell(new PdfPCell(new Phrase("", Chico)) { Border = Rectangle.NO_BORDER, Colspan = 6 }); resumen.AddCell(new PdfPCell(new Phrase("______________________ Firma Empleado", Chico)) { VerticalAlignment = Rectangle.ALIGN_BOTTOM, HorizontalAlignment = Rectangle.ALIGN_CENTER, Colspan = 2, Border = Rectangle.NO_BORDER }); doc.Add(resumen); //PdfPTable firma = new PdfPTable(new float[] { 2, 1, 2, 1, 2, 1, 2, 1 }); //firma.AddCell(new PdfPCell(new Phrase(" ", Chico)) { Border = Rectangle.NO_BORDER, Colspan = 8, Rowspan = 2 }); ////firma.AddCell(new PdfPCell(new Phrase(" ", Chico)) { Border = Rectangle.NO_BORDER, Colspan = 8 }); //firma.AddCell(new PdfPCell(new Phrase("", Chico)) { Border = Rectangle.NO_BORDER, Colspan = 6 }); //firma.AddCell(new PdfPCell(new Phrase("______________________ Firma Empleado", Chico)) { VerticalAlignment = Rectangle.ALIGN_BOTTOM, HorizontalAlignment = Rectangle.ALIGN_CENTER, Colspan = 2, Border = Rectangle.NO_BORDER, FixedHeight = 1.7f }); //doc.Add(new Phrase()); //doc.Add(new Phrase()); //doc.Add(new Phrase()); //doc.Add(new Phrase()); //doc.Add(firma); doc.NewPage(); } doc.Close(); _Archivo = ms.ToArray(); } } }
private void SaveAsPDFA(ref string tempPDF, string pdfPath, MetaData md) { string tempdir = Path.Combine(Path.GetTempPath(), "GhostScriptWrapper"); if (!Directory.Exists(tempdir)) { Directory.CreateDirectory(tempdir); } tempPDF = Path.Combine(tempdir, string.Format("{0}_tmp.pdf", Guid.NewGuid())); File.Copy(pdfPath, tempPDF); GhostScriptWrapper.CallAPI(GetArgs(tempPDF, pdfPath)); var document = new it.Document(); using (var fs = new FileStream(tempPDF, FileMode.Create)) { // step 2: we create a writer that listens to the document //PdfCopy writer = new PdfCopy(document, fs); var pdfaWriter = ip.PdfAWriter.GetInstance(document, fs, ip.PdfAConformanceLevel.PDF_A_1B); pdfaWriter.SetTagged(); pdfaWriter.CreateXmpMetadata(); // step 3: we open the document document.Open(); document.AddAuthor(md.Author); document.AddCreator(md.Creator); document.AddLanguage(md.Language); document.AddProducer(); document.AddTitle(Path.GetFileNameWithoutExtension(pdfPath)); // we create a reader for a certain document var reader = new ip.PdfReader(pdfPath); reader.ConsolidateNamedDestinations(); document.NewPage(); var icc = ip.ICC_Profile.GetInstance(Environment.GetEnvironmentVariable("SystemRoot") + @"\System32\spool\drivers\color\sRGB Color Space Profile.icm"); pdfaWriter.SetOutputIntents("sRGB", null, "http://www.color.org", "sRGB IEC61966-2.1", icc.Data); // step 4: we add content for (var i = 1; i <= reader.NumberOfPages; i++) { var page = pdfaWriter.GetImportedPage(reader, i); pdfaWriter.DirectContentUnder.AddTemplate(page, 0, 0); document.NewPage(); } // step 5: we close the document and writer document.AddCreationDate(); pdfaWriter.Flush(); try { pdfaWriter.Close(); } catch (Exception ex) { Console.WriteLine(ex.Message); } reader.Close(); try { document.Close(); } catch { } } ManipulatePdf(tempPDF, pdfPath, md); }
public Document NewDocument(string path) { var document = new Document(PageSize.A6.Rotate()); var pdf = new FileStream(path, FileMode.OpenOrCreate); PdfWriter writer = PdfWriter.GetInstance(document, pdf); writer.PageEvent = new WaterMark(_school.Name); document.AddCreationDate(); document.AddAuthor("lilvonz"); document.AddTitle("School Receipt"); document.SetMargins(20f, 20f, 20f, 20f); return document; }
private void btnAraToplam_Click(object sender, EventArgs e) //PDF DOSYASI OLARAK KAYDETME ORTAMI BURASI. { try { if (listView1.Items.Count > 0) { DialogResult cevap = MessageBox.Show("Fiş istiyor musunuz?", "HESAP", MessageBoxButtons.YesNo); if (cevap == DialogResult.Yes) { string fileName = "", tarih = "", kuver = "", fiyat = "", urunAdi = ""; int fisID = 0; int temp = int.Parse(MainForm.Masa), fiyatUrun = 0; using (var cafeContext = new CafeContext()) { var result = from receipts in cafeContext.Receipts join orders in cafeContext.Orders on receipts.TableNumber equals orders.TableNumber where receipts.TableNumber == temp && orders.isAlive == true select new { orders, receipts }; foreach (var gez in result) { fileName = gez.receipts.ReceiptID.ToString(); tarih = gez.receipts.Date; fisID = gez.receipts.ReceiptID; kuver = gez.receipts.Cover.ToString(); fiyat = gez.receipts.TotalPrice.ToString(); } var resultProduct = from orders in cafeContext.Orders join product in cafeContext.Products on orders.Product.ProductID equals product.ProductID where orders.isAlive == true & orders.TableNumber == temp select new { orders, product }; iTextSharp.text.Document raporum = new iTextSharp.text.Document(); PdfWriter.GetInstance(raporum, new FileStream("C:" + fileName + ".pdf", FileMode.Create)); raporum.AddAuthor("Cafelania"); raporum.AddCreationDate(); raporum.AddSubject("FIŞ BILGILERI"); raporum.AddKeywords("fis"); if (raporum.IsOpen() == false) { raporum.Open(); } raporum.Add(new Paragraph(" CAFELANIA " + tarih)); raporum.Add(new Paragraph(" ")); raporum.Add(new Paragraph("Fis Numarasi:" + fisID.ToString() + " Kuver Sayisi:" + kuver + " Masa Numarasi:" + temp.ToString())); raporum.Add(new Paragraph(" ")); foreach (var gez in resultProduct) { urunAdi = gez.product.ProductName; fiyatUrun = int.Parse(gez.product.Amount.ToString()) * int.Parse(gez.orders.ProductCount.ToString()); raporum.Add(new Paragraph("Adet: " + gez.orders.ProductCount.ToString() + " " + urunAdi + " " + fiyatUrun.ToString() + "TL")); raporum.Add(new Paragraph(" ")); } raporum.Add(new Paragraph(" TOPLAM TUTAR:" + lblfiyat.Text)); MessageBox.Show("Toplam hesap: " + lblfiyat.Text + "\nFiş Numarası: " + fisID.ToString()); raporum.Close(); } } } else { MessageBox.Show("Fiş oluşturmak için lütfen sipariş giriniz.", "Uyarı", MessageBoxButtons.OK, MessageBoxIcon.Error); } } catch { } }
public Ausencia(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}/PersonalAusente.pdf", empresa.Descripcion, departamento.Descripcion); // Vamos a buscar los datos que nos permitirtán armar elreporte IEnumerable<sp_LibroInasistenciaResult> resultado = db.sp_LibroInasistencia( FechaDesde.ToString("yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture) , FechaHasta.ToString("yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture) , int.Parse(empresa.Codigo).ToString() , departamento.Codigo , rut).OrderBy(x => x.Fecha).ToList(); IEnumerable<LibroInasistenciaDTO> inasistencias = Mapper.Map<IEnumerable<sp_LibroInasistenciaResult>, IEnumerable<LibroInasistenciaDTO>>(resultado); if (inasistencias.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 inasistencias.Where(x=>x.Rut!=null).GroupBy(x => new { x.Rut, x.IdDepartamento, x.IdEmpresa }).Take(3)) { doc.AddAuthor("Aufen"); doc.AddCreationDate(); doc.AddCreator("Aufen"); doc.AddTitle("Informe de Personal Ausente (sin marcas)"); Paragraph parrafo = new Paragraph(); parrafo.Add(new Paragraph("Informe de Personal Ausente (sin marcas)", Titulo) { Alignment = Element.ALIGN_CENTER }); parrafo.Add(new Paragraph(String.Format("Período: {0} a {1}", FechaDesde.ToShortDateString(), FechaHasta.ToShortDateString()), Normal) { Alignment = Element.ALIGN_CENTER }); parrafo.Add(new Paragraph("Centro de Costos:", Normal)); doc.Add(parrafo); doc.Add(new Phrase()); PdfPTable tabla = new PdfPTable(new float[] {2, 2, 2, 2, 1, 1, 4 }); // Encabezado tabla.AddCell(new PdfPCell(new Phrase("Empleado", Normal)) { Colspan = 4}); tabla.AddCell(new PdfPCell(new Phrase("Horario", Normal)) { Colspan = 2 }); tabla.AddCell(new PdfPCell(new Phrase("Autorizaciones", Normal))); // 2 encabezado tabla.AddCell(new PdfPCell(new Phrase("Fecha", Chico))); 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("Autorizaciones", Chico))); var empleado = db.vw_Empleados.FirstOrDefault(x => x.IdEmpresa == empresa.Codigo && x.IdUbicacion == reporte.Key.IdDepartamento && x.Codigo == reporte.Key.Rut); foreach(var ausencia in reporte) { //Fecha tabla.AddCell(new PdfPCell(new Phrase(ausencia.Fecha.HasValue ? ausencia.Fecha.Value.ToString("ddd dd/MM") : String.Empty, Chico))); //Código tabla.AddCell(new PdfPCell(new Phrase(empleado.RutAufen, Chico))); //Apellidos tabla.AddCell(new PdfPCell(new Phrase((ausencia.Apellidos ?? string.Empty).Trim(), Chico))); //Nombres tabla.AddCell(new PdfPCell(new Phrase((ausencia.Nombres ?? string.Empty).Trim(), Chico))); //Ing. tabla.AddCell(new PdfPCell(new Phrase(ausencia.EntradaTeorica.HasValue ? ausencia.EntradaTeorica.Value.ToString("HH:mm") : String.Empty, Chico))); //Sal. tabla.AddCell(new PdfPCell(new Phrase(ausencia.SalidaTeorica.HasValue ? ausencia.SalidaTeorica.Value.ToString("HH:mm") : String.Empty, Chico))); //Autorizaciones tabla.AddCell(new PdfPCell(new Phrase(ausencia.Observacion, Chico))); } doc.Add(tabla); doc.NewPage(); } doc.Close(); _Archivo = ms.ToArray(); } } }
public void ExportToPdf(System.Data.DataTable dt) { Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog(); dlg.FileName = "Izvjestaj"; // Default file name dlg.DefaultExt = ".pdf"; // Default file extension dlg.Filter = "PDF documents (.pdf)|*.pdf"; // Filter files by extension // save file dialog box Nullable <bool> result = dlg.ShowDialog(); try { if (result == true) { // Save document string filename = dlg.FileName; iTextSharp.text.Document document = new iTextSharp.text.Document(); PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(filename, FileMode.Create)); document.AddTitle("Izvjestaj"); document.AddCreationDate(); document.Open(); iTextSharp.text.Font font5 = iTextSharp.text.FontFactory.GetFont(FontFactory.HELVETICA, 7); PdfPTable table = new PdfPTable(dt.Columns.Count); if (pom == "_Arhiva") { float[] widths = new float[] { 1f, 3f, 3f, 3f, 4f, 3f, 3f, 4f }; table.SetWidths(widths); table.WidthPercentage = 100; PdfPCell cell = new PdfPCell(new Phrase("Elementi")); cell.Colspan = dt.Columns.Count; foreach (DataColumn c in dt.Columns) { table.AddCell(new Phrase(c.ColumnName, font5)); } foreach (DataRow r in dt.Rows) { if (dt.Rows.Count > 0) { table.AddCell(new Phrase(r[0].ToString(), font5)); table.AddCell(new Phrase(r[1].ToString(), font5)); table.AddCell(new Phrase(r[2].ToString(), font5)); table.AddCell(new Phrase(r[3].ToString(), font5)); table.AddCell(new Phrase(r[4].ToString(), font5)); table.AddCell(new Phrase(r[5].ToString(), font5)); table.AddCell(new Phrase(r[6].ToString(), font5)); table.AddCell(new Phrase(r[7].ToString(), font5)); } } } else { float[] widths = new float[] { 1f, 3f, 3f, 3f, 4f, 3f, 3f, 4f, 4f }; table.SetWidths(widths); table.WidthPercentage = 100; // int iCol = 0; // string colname = ""; PdfPCell cell = new PdfPCell(new Phrase("Elementi")); cell.Colspan = dt.Columns.Count; foreach (DataColumn c in dt.Columns) { table.AddCell(new Phrase(c.ColumnName, font5)); } foreach (DataRow r in dt.Rows) { if (dt.Rows.Count > 0) { table.AddCell(new Phrase(r[0].ToString(), font5)); table.AddCell(new Phrase(r[1].ToString(), font5)); table.AddCell(new Phrase(r[2].ToString(), font5)); table.AddCell(new Phrase(r[3].ToString(), font5)); table.AddCell(new Phrase(r[4].ToString(), font5)); table.AddCell(new Phrase(r[5].ToString(), font5)); table.AddCell(new Phrase(r[6].ToString(), font5)); table.AddCell(new Phrase(r[7].ToString(), font5)); table.AddCell(new Phrase(r[8].ToString(), font5)); } } } //dodavanje naslova iTextSharp.text.Font titleFont = FontFactory.GetFont("Arial", 32); iTextSharp.text.Font regularFont = FontFactory.GetFont("Arial", 12); iTextSharp.text.Paragraph title; iTextSharp.text.Paragraph text; title = new iTextSharp.text.Paragraph("Izvještaj", titleFont); title.Alignment = Element.ALIGN_CENTER; document.Add(title); text = new iTextSharp.text.Paragraph("Datum:_____________", regularFont); text.Alignment = Element.ALIGN_RIGHT; document.Add(text); document.Add(new iTextSharp.text.Paragraph(" ")); document.Add(new iTextSharp.text.Paragraph(" ")); document.Add(table); document.Close(); this.Close(); } } catch (Exception error) { MessageBox.Show("Error: " + error.Message); } }
protected void Prepare_Print() { String[] weekDays = new String[] { " ","Sun", "Mon", "Tue", "Wed", "Thu" }; int[] sessions = new int[] {0,1,2,3,4,5,6,7,8,9}; PdfPTable tblSchedule = new PdfPTable(10); PdfPRow[] tempRow = new PdfPRow[6]; PdfPCell[][] tempCell = new PdfPCell[6][]; int rowIndex = 0; int cellIndex = 0; Paragraph subject = new Paragraph(); Paragraph teacher = new Paragraph(); Paragraph lunch = new Paragraph(); Paragraph dayPara = new Paragraph(); Paragraph sessionPara = new Paragraph(); Paragraph teacherPara = new Paragraph(); Font lunch_font = new Font(); Font day_session_para = new Font(); Font session_font = new Font(); Font teacher_font = new Font(); session_font.Size = 10; teacher_font.SetStyle("Italics"); teacher_font.Size = 7; lunch_font.SetColor(153, 153, 255); lunch_font.SetStyle("italics"); lunch = new Paragraph("Lunch", lunch_font); day_session_para.SetColor(0, 0, 153); foreach (String weekDay in weekDays) { tempCell[rowIndex] = new PdfPCell[10]; tempRow[rowIndex] = new PdfPRow(tempCell[rowIndex]); foreach (int session in sessions) { if (session == 0 || session == 6) { if (session == 0) { dayPara = new Paragraph(weekDays[rowIndex],day_session_para); tempCell[rowIndex][cellIndex] = new PdfPCell(dayPara); } else if (weekDay != " ") { tempCell[rowIndex][cellIndex] = new PdfPCell(lunch); } else { //tempCell[rowIndex][cellIndex] = new PdfPCell(new Phrase(Convert.ToString(sessions[cellIndex]))); dayPara = new Paragraph(Convert.ToString(sessions[cellIndex]), day_session_para); tempCell[rowIndex][cellIndex] = new PdfPCell(dayPara); } } else { if (weekDay == " ") { dayPara = new Paragraph(Convert.ToString(sessions[cellIndex]), day_session_para); tempCell[rowIndex][cellIndex] = new PdfPCell(dayPara); //tempCell[rowIndex][cellIndex] = new PdfPCell(new Phrase(Convert.ToString(sessions[cellIndex]))); } else { string query = "select B.CourseTitle,A.TeacherID from tblStudentCourseMap as A,tblCourses as B where A.ComCod = B.ComCod and A.DaySession = '" + weekDay + session + "' and A.StudentID = '" + Current_User_ID + "'"; myCon.ConOpen(); SqlDataReader sessionDet = myCon.ExecuteReader(query); if (sessionDet.Read()) if (!sessionDet.IsDBNull(0)) { sessionPara = new Paragraph(sessionDet.GetString(0), session_font); //tempCell[rowIndex][cellIndex] = new PdfPCell(sessionPara); teacherPara = new Paragraph(sessionDet.GetString(1), teacher_font); tempCell[rowIndex][cellIndex] = new PdfPCell(new Phrase(sessionPara)); tempCell[rowIndex][cellIndex].Phrase.Add(new Phrase("\n")); tempCell[rowIndex][cellIndex].Phrase.Add(teacherPara); //tempCell[rowIndex][cellIndex] = new PdfPCell(new Phrase(sessionDet.GetString(0) + "\n" + sessionDet.GetString(1))); } else { tempCell[rowIndex][cellIndex] = new PdfPCell(new Phrase("")); //tempCell[rowIndex][cellIndex } else tempCell[rowIndex][cellIndex] = new PdfPCell(new Phrase("")); myCon.ConClose(); tempCell[rowIndex][cellIndex].FixedHeight = 75; } } //tempCell[rowIndex][cellIndex].Width = 50; cellIndex++; //tempRow[rowIndex].Cells.Add(tempCell[cellIndex++, rowIndex]); } cellIndex = 0; //rowIndex++; tblSchedule.Rows.Add(tempRow[rowIndex++]); } Font HeaderFont = new Font(); Font HeadingFont = new Font(); HeaderFont.Size = 20; HeaderFont.SetStyle(Font.UNDERLINE); HeadingFont.Size = 15; HeadingFont.SetStyle(Font.UNDERLINE); Paragraph HeaderPara = new Paragraph("BITS PILANI, DUBAI OFFCAMPUS - TIMETABLE", HeaderFont); Paragraph HeadingPara = new Paragraph("Time Table allotment for " + Current_User_ID + ".",HeadingFont); HeaderPara.Alignment = HeadingPara.Alignment = 1; Document rptTimetable = new Document(PageSize.A4_LANDSCAPE.Rotate()); PdfWriter.GetInstance(rptTimetable, new FileStream(Request.PhysicalApplicationPath + "\\" + Current_User_ID + "_timetable.pdf", FileMode.Create)); rptTimetable.Open(); rptTimetable.AddCreationDate(); rptTimetable.AddHeader("BITS PILANI, DUBAI OFFCAMPUS", "TIMETABLE"); rptTimetable.Add(new Paragraph("\n")); rptTimetable.AddTitle("BITS PILANI, DUBAI OFFCAMPUS - TIMETABLE"); rptTimetable.Add(HeaderPara); rptTimetable.Add(HeadingPara); rptTimetable.Add(new Paragraph("\n\n")); if (rptTimetable != null && tblSchedule != null) { rptTimetable.Add(tblSchedule); } rptTimetable.Close(); Response.Redirect("~\\" + Current_User_ID + "_timetable.pdf"); }
/// <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 button1_Click(object sender, EventArgs e) { //creamos el documento //...ahora configuramos para que el tamaño de hoja sea A4 Document document = new Document(iTextSharp.text.PageSize.A4); //document.PageSize.BackgroundColor = new iTextSharp.text.BaseColor(255, 255, 255); document.PageSize.Rotate(); //...definimos el autor del documento. document.AddAuthor("Arbis Percy Reyes Paredes"); //...el creador, que será el mismo eh! document.AddCreator("Arbis Percy Reyes Paredes"); //hacemos que se inserte la fecha de creación para el documento document.AddCreationDate(); //...título document.AddTitle("Generación de un pdf con itextSharp"); //... el asunto document.AddSubject("Este es un paso muy important"); //... palabras claves document.AddKeywords("pdf, PdfWriter; Documento; iTextSharp"); //creamos un instancia del objeto escritor de documento PdfWriter writer = PdfWriter.GetInstance(document, new System.IO.FileStream ("Code.pdf", System.IO.FileMode.Create)); //encriptamos el pdf, dándole como clave de usuario "key" y la clave del dueño será "owner" //si quitas los comentarios (en writer.SetEncryption...), entonces el documento generado //no mostrarà tanto la información de autor, titulo, fecha de creacion... //que habiamos establecio más arriba. y sólo podrás abrirlo con una clave //writer.SetEncryption(PdfWriter.STRENGTH40BITS,"key","owner", PdfWriter.CenterWindow); //definimos la manera de inicialización de abierto del documento. //esto, hará que veamos al inicio, todas la páginas del documento //en la parte izquierda writer.ViewerPreferences = PdfWriter.PageModeUseThumbs; //con esto conseguiremos que el documento sea presentada de dos en dos writer.ViewerPreferences = PdfWriter.PageLayoutTwoColumnLeft; //con esto podemos oculta las barras de herramienta y de menú respectivamente. //(quite las dos barras de comentario de la siguiente línea para ver los efectos) //PdfWriter.HideToolbar | PdfWriter.HideMenubar //abrimos el documento para agregarle contenido document.Open(); //este stream es para jalar el código string TemPath = Application.StartupPath.ToString(); TemPath = TemPath.Substring(0, TemPath.Length - 10); string pathFileForm1cs = TemPath + @"\Form1.cs"; System.IO.StreamReader reader = new System.IO.StreamReader(pathFileForm1cs); //leemos primera línea string linea = reader.ReadLine(); //creamos la fuente iTextSharp.text.Font myfont = new iTextSharp.text.Font( FontFactory.GetFont(FontFactory.COURIER, 10, iTextSharp.text.Font.ITALIC)); //creamos un objeto párrafo, donde insertamos cada una de las líneas que //se vaya leyendo mediante el reader Paragraph myParagraph = new Paragraph("Código fuente en Visual C# \n\n", myfont); do { //leyendo linea de texto linea = reader.ReadLine(); //concatenando cada parrafo que estará formado por una línea myParagraph.Add(new Paragraph(linea, myfont)); } while (linea != null); //mientras no llegue al final de documento, sigue leyendo //agregar todo el paquete de texto document.Add(myParagraph); //esto es importante, pues si no cerramos el document entonces no se creara el pdf. document.Close(); //esto es para abrir el documento y verlo inmediatamente después de su creación System.Diagnostics.Process.Start("C:\\Program Files (x86)\\Foxit PhantomPDF\\FoxitPhantomPDF.exe", "Code.pdf"); }
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 void SendToPDF(string filename, clsFont jfont) { int countOfPages = _unicodeCharList.CharCodes.Count() / LINES_PER_PAGE; //fifty lines per page. //New document, 8.5"x11" in landscape orientation. iTextSharp.text.Document doc = new iTextSharp.text.Document(PageSize.LETTER); //add metadata doc.AddTitle("Unicode Character Set 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); //Create our base font string FontPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "ARIALUNI.TTF"); BaseFont baseFont = BaseFont.CreateFont(FontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED); iTextSharp.text.Font x = FontFactory.GetFont(jfont.SelectedFontName()); for (int currentPage = 0; currentPage < countOfPages; currentPage++) { PdfPTable table = new PdfPTable(5); table.AddCell("Char"); table.AddCell("Dec"); table.AddCell("Hex"); table.AddCell("Desc"); table.AddCell("AltDesc"); //convert image to a pdf image for inclusion in the doc for (int curChar = currentPage * LINES_PER_PAGE; curChar < (currentPage * LINES_PER_PAGE + LINES_PER_PAGE); curChar++) { UnicodeCharList.CharEntry oneEntry = _unicodeCharList.CharCodes[curChar]; string charString = char.ConvertFromUtf32(Convert.ToInt32(oneEntry.CodeDec)).ToString(); Phrase codedChar = new Phrase(charString, x); table.AddCell(codedChar); table.AddCell(oneEntry.CodeDec); table.AddCell(oneEntry.CodeHex); table.AddCell(oneEntry.Desc); table.AddCell(oneEntry.AltDesc); } doc.Add(table); doc.NewPage(); } doc.Close(); }