public void Save(System.Drawing.Bitmap bm, string filename, System.Drawing.RotateFlipType rotate) { Bitmap image = bm; if (rotate != RotateFlipType.RotateNoneFlipNone) { image.RotateFlip(rotate); } using (FileStream stream = new FileStream(filename, FileMode.Create)) { using (iTextSharp.text.Document pdfDocument = new iTextSharp.text.Document(PageSize.LETTER, PAGE_LEFT_MARGIN, PAGE_RIGHT_MARGIN, PAGE_TOP_MARGIN, PAGE_BOTTOM_MARGIN)) { iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDocument, stream); pdfDocument.Open(); MemoryStream ms = new MemoryStream(); image.Save(ms, System.Drawing.Imaging.ImageFormat.Tiff); iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(ms); img.ScaleToFit(PageSize.LETTER.Width - (PAGE_LEFT_MARGIN + PAGE_RIGHT_MARGIN), PageSize.LETTER.Height - (PAGE_TOP_MARGIN + PAGE_BOTTOM_MARGIN)); pdfDocument.Add(img); pdfDocument.Close(); writer.Close(); } } }
public PdfDocument(Models.Document documentTemplate, string outputFile) { // Create Colors foreach (Models.Typography.Color bColor in documentTemplate.Colors) { Color itextColor = new Color(bColor); Colors.Add(itextColor); } // Create Fonts foreach (Models.Typography.Font bFont in documentTemplate.Fonts) { foreach (Models.Typography.FontStyle bFontStyle in bFont.Styles) { FontStyle itextFontStyle = new FontStyle(bFontStyle); Fonts.Add(itextFontStyle); } } try { CreatePages(documentTemplate, outputFile); SetDocumentProperties(documentTemplate); _itextDocument.Close(); _itextPDFWriter.Close(); } catch (IOException iox) { throw; } }
public void FinishWriting() { document.Close(); document.Dispose(); writer.Close(); writer.Dispose(); _document = null; _writer = null; }
public FileResult PdfConverter() { string htmlText = string.Empty; string filename = string.Empty; filename = "Test"; htmlText += "<div></div>"; string filePath = Request.PhysicalApplicationPath + "/Upload/Test/" + filename.Replace(" ", "") + ".pdf"; using (FileStream docFile = new FileStream(filePath, FileMode.Create)) { string url = "http://" + Request.Url.Authority + "/account/Login"; Dictionary <string, object> attr = new Dictionary <string, object>(); attr.Add("logo", new TemplateHelper().getlogo()); attr.Add("Insuredname", "Praveen Kumar"); attr.Add("EmailId", "*****@*****.**"); attr.Add("InsuredDoB", "11-05-2016"); attr.Add("InsuredAge", "40"); attr.Add("MobileNo", "9866078078"); attr.Add("SpouseDoB", "11-05-2016"); attr.Add("SpouseAge", "15"); attr.Add("DoughterDoB", "11-05-2016"); attr.Add("DoughterAge", "10"); attr.Add("SonDoB", "11-05-2016"); attr.Add("SonAge", "8"); attr.Add("NoofAdults", "2"); attr.Add("NoofChildren", "2"); attr.Add("Smoker", "Yes"); attr.Add("Preexistingdiseases", "No"); attr.Add("MaternityCover", "Yes"); attr.Add("RestorationBenefits", "Yes"); htmlText = new TemplateHelper().GetTemplateBody(attr, "~/App_Data/test.html"); iTextSharp.text.Document document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 30, 30, 10, 30); iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, docFile); document.Open(); iTextSharp.text.html.simpleparser.StyleSheet styles = new iTextSharp.text.html.simpleparser.StyleSheet(); iTextSharp.text.html.simpleparser.HTMLWorker hw = new iTextSharp.text.html.simpleparser.HTMLWorker(document); hw.Parse(new StringReader(htmlText)); document.Close(); writer.Close(); } return(File(filePath, "application/pdf", filename.Replace(" ", "") + ".pdf")); }
public void Close() { if (pdfDocument != null) { pdfDocument.Close(); pdfDocument.Dispose(); writer.Close(); writer.Dispose(); stream.Close(); stream.Dispose(); pdfDocument = null; writer = null; pdfDocument = null; } if (reader != null) { reader.Close(); } }
public static void ExportStagesToPDF(IList <StageViewModelBase> stages, string simulacionFileName) { //logger.Info("Inicio Exportar a PDF"); Document doc = null; iTextSharp.text.pdf.PdfWriter writer = null; try { doc = new Document(iTextSharp.text.PageSize.LETTER); writer = iTextSharp.text.pdf.PdfWriter.GetInstance(doc, new FileStream(simulacionFileName, FileMode.Create)); doc.AddTitle("Simulación"); doc.AddCreator("JALUPEGUI Sistemas"); doc.Open(); iTextSharp.text.Font _standardFont = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 8, iTextSharp.text.Font.NORMAL, BaseColor.BLACK); doc.Add(new Paragraph("Resultados Simulación")); doc.Add(Chunk.NEWLINE); foreach (StageViewModel s in stages) { doc.Add(new Paragraph(s.Name)); doc.Add(Chunk.NEWLINE); PdfPTable tblDatos = new PdfPTable(3); tblDatos.WidthPercentage = 100; #region Look and Feel PdfPCell clVariable = new PdfPCell(new Phrase("Variable", _standardFont)); clVariable.BorderWidth = 0; clVariable.BorderWidthBottom = 0.75f; PdfPCell clValorInicial = new PdfPCell(new Phrase("Valor Inicial", _standardFont)); clValorInicial.BorderWidth = 0; clValorInicial.BorderWidthBottom = 0.75f; PdfPCell clValorSimulacion = new PdfPCell(new Phrase("Valor Simulación", _standardFont)); clValorSimulacion.BorderWidth = 0; clValorSimulacion.BorderWidthBottom = 0.75f; tblDatos.AddCell(clVariable); tblDatos.AddCell(clValorInicial); tblDatos.AddCell(clValorSimulacion); #endregion Look and Feel foreach (ModelWPF.Variable v in s.Variables) { clVariable = new PdfPCell(new Phrase(v.Name, _standardFont)); clVariable.BorderWidth = 0; clValorInicial = new PdfPCell(new Phrase(v.InitialValue.ToString(), _standardFont)); clValorInicial.BorderWidth = 0; clValorSimulacion = new PdfPCell(new Phrase(v.ActualValue.ToString(), _standardFont)); clValorSimulacion.BorderWidth = 0; tblDatos.AddCell(clVariable); tblDatos.AddCell(clValorInicial); tblDatos.AddCell(clValorSimulacion); } doc.Add(tblDatos); foreach (ChartViewModel c in s.Charts) { MemoryStream memStream = new MemoryStream(); ((ChartViewModel)c).ExportChart(memStream, 800, 600); var img = Bitmap.FromStream(memStream); iTextSharp.text.Image imagen = iTextSharp.text.Image.GetInstance(img, BaseColor.WHITE); imagen.BorderWidth = 0; imagen.Alignment = iTextSharp.text.Element.ALIGN_CENTER; imagen.ScalePercent(50); doc.Add(imagen); memStream.Flush(); memStream.Close(); } doc.NewPage(); //logger.Info("Fin Exportar a PDF"); } } catch (Exception e) { //logger.Error("Error Exportar a PDF:" + e.Message); throw e; } finally { doc.Close(); writer.Close(); } }
private Boolean AñadirDatos() { Document doc = new Document(PageSize.LETTER); PdfWriter writer = null; // Indicamos donde vamos a guardar el documento int numero = 0; for (int i = 0; i <= numero; i++) { if (System.IO.File.Exists("C:/Users/vichg/OneDrive/Escritorio/ControlAlumnos" + numero + ".pdf")) { numero++; } else { writer = PdfWriter.GetInstance(doc, new FileStream(@"C:\Users\vichg\OneDrive\Escritorio\ControlAlumnos" + numero + ".pdf", FileMode.Create)); } } // Le colocamos el título y el autor // **Nota: Esto no será visible en el documento doc.AddTitle("Lista de Alumnos "); doc.AddCreator("Luis Enrique García Rodríguez y Victor Hugo Gonzales Arreola"); // Abrimos el archivo doc.Open(); iTextSharp.text.Font _standardFont = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 8, iTextSharp.text.Font.NORMAL, BaseColor.BLACK); // Escribimos el encabezamiento en el documento doc.Add(new Paragraph(" Lista de ALumnos 2019 Clase Desarrollo Asp.NET")); doc.Add(Chunk.NEWLINE); // Creamos una tabla que contendrá el nombre, apellido y país // de nuestros visitante. PdfPTable tblPrueba = new PdfPTable(5); tblPrueba.WidthPercentage = 100; // Configuramos el título de las columnas de la tabla PdfPCell clControl = new PdfPCell(new Phrase("Numero Control", _standardFont)); clControl.BorderWidth = 0; clControl.BorderWidthBottom = 0.50f; PdfPCell clNombre = new PdfPCell(new Phrase("Nombre Alumno", _standardFont)); clNombre.BorderWidth = 0; clNombre.BorderWidthBottom = 0.50f; PdfPCell clCarrera = new PdfPCell(new Phrase("Carrera", _standardFont)); clCarrera.BorderWidth = 0; clCarrera.BorderWidthBottom = 0.50f; PdfPCell clSemestre = new PdfPCell(new Phrase("Semestre", _standardFont)); clSemestre.BorderWidth = 0; clSemestre.BorderWidthBottom = 0.50f; PdfPCell clCorreo = new PdfPCell(new Phrase("Correo", _standardFont)); clCorreo.BorderWidth = 0; clCorreo.BorderWidthBottom = 0.50f; // Añadimos las celdas a la tabla tblPrueba.AddCell(clControl); tblPrueba.AddCell(clNombre); tblPrueba.AddCell(clCarrera); tblPrueba.AddCell(clSemestre); tblPrueba.AddCell(clCorreo); int iPosicion = 0; foreach (GridViewRow row in GrdAlumnos.Rows) { doc.Add(Chunk.NEWLINE); iPosicion++; // Llenamos la tabla con información clControl = new PdfPCell(new Phrase(row.Cells[0].Text, _standardFont)); clControl.BorderWidth = 0; clNombre = new PdfPCell(new Phrase(row.Cells[1].Text, _standardFont)); clNombre.BorderWidth = 0; clCarrera = new PdfPCell(new Phrase(row.Cells[2].Text, _standardFont)); clCarrera.BorderWidth = 0; clSemestre = new PdfPCell(new Phrase(row.Cells[3].Text, _standardFont)); clSemestre.BorderWidth = 0; clCorreo = new PdfPCell(new Phrase(row.Cells[4].Text, _standardFont)); clCorreo.BorderWidth = 0; // Añadimos las celdas a la tabla tblPrueba.AddCell(clControl); tblPrueba.AddCell(clNombre); tblPrueba.AddCell(clCarrera); tblPrueba.AddCell(clSemestre); tblPrueba.AddCell(clCorreo); } doc.Add(tblPrueba); doc.Close(); writer.Close(); return(true); }
private void GenerarPDF(CabezalRecibo recibo) { try { gridViewDocumentos.AllowPaging = false; Document doc = new Document(PageSize.LETTER); // Indicamos donde vamos a guardar el documento System.IO.MemoryStream ms = new System.IO.MemoryStream(); //PdfWriter writer = PdfWriter.GetInstance(doc,new FileStream(@"C:\recibo.pdf", FileMode.Create)); doc.AddTitle("Recibo Pago"); doc.AddCreator("E&E Integra"); iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(doc, ms); doc.Open(); // Creamos el tipo de Font que vamos utilizar iTextSharp.text.Font _tituloFont = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 14, iTextSharp.text.Font.BOLD, BaseColor.BLACK); iTextSharp.text.Font _tituloFont2 = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 14, iTextSharp.text.Font.NORMAL, BaseColor.BLACK); iTextSharp.text.Font texto = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12, iTextSharp.text.Font.NORMAL, BaseColor.BLACK); iTextSharp.text.Font cuota_font = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 9, iTextSharp.text.Font.NORMAL, BaseColor.BLACK); string imageURL = Server.MapPath("~//Imagenes") + "\\logo.png"; iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(imageURL); jpg.Alignment = iTextSharp.text.Image.TEXTWRAP | iTextSharp.text.Image.ALIGN_LEFT; jpg.ScaleAbsolute(177f, 100f); doc.Add(jpg); // Escribimos el encabezamiento en el documento Paragraph paragraph1 = new Paragraph(@" RUT: " + Session["rut"].ToString(), _tituloFont); paragraph1.Alignment = Element.ALIGN_JUSTIFIED; doc.Add(paragraph1); Paragraph paragraph2 = new Paragraph(@" Recibo Oficial", _tituloFont); paragraph2.Alignment = Element.ALIGN_JUSTIFIED; doc.Add(paragraph2); Paragraph paragraph3 = new Paragraph(@" Nro. Recibo: " + recibo.Numero.ToString(), _tituloFont2); paragraph3.Alignment = Element.ALIGN_JUSTIFIED; doc.Add(paragraph3); Paragraph paragraph4 = new Paragraph(@" Moneda: " + recibo.Moneda, _tituloFont2); paragraph4.Alignment = Element.ALIGN_JUSTIFIED; doc.Add(paragraph4); Paragraph paragraph5 = new Paragraph(@" Importe " + recibo.Importe, _tituloFont); paragraph5.Alignment = Element.ALIGN_JUSTIFIED; doc.Add(paragraph5); doc.Add(Chunk.NEWLINE); doc.Add(Chunk.NEWLINE); doc.Add(Chunk.NEWLINE); String nom = recibo.cliente.Nombre; Paragraph paragraph6 = new Paragraph(@"Recibimos de " + nom + " la cantidad de " + recibo.Importe + " por concepto de pago de deuda"); paragraph6.Alignment = Element.ALIGN_LEFT; doc.Add(paragraph6); doc.Add(Chunk.NEWLINE); Paragraph paragraph7 = new Paragraph(@"Observaciones:", _tituloFont); paragraph7.Alignment = Element.ALIGN_LEFT; doc.Add(paragraph7); String resultString = ""; if (!String.IsNullOrEmpty(recibo.Observaciones)) { resultString = Regex.Replace(recibo.Observaciones, @"^\s+$[\r\n]*", "", RegexOptions.Multiline); } Paragraph paragraph8 = new Paragraph(@resultString, cuota_font); paragraph8.Alignment = Element.ALIGN_LEFT; doc.Add(paragraph8); if (!String.IsNullOrEmpty(recibo.MotivoAnulacion)) { Paragraph paragraph9 = new Paragraph(@"Motivo Anulación:", _tituloFont); paragraph9.Alignment = Element.ALIGN_LEFT; doc.Add(paragraph9); String anulacionString = Regex.Replace(recibo.MotivoAnulacion, @"^\s+$[\r\n]*", "", RegexOptions.Multiline); Paragraph paragraph10 = new Paragraph(@anulacionString, cuota_font); paragraph10.Alignment = Element.ALIGN_LEFT; doc.Add(paragraph10); } doc.Add(Chunk.NEWLINE); Paragraph paragraph11 = new Paragraph(@"Paysandú, " + recibo.Fecha.Day + " de " + MonthName(recibo.Fecha.Month) + " de " + recibo.Fecha.Year); paragraph11.Alignment = Element.ALIGN_RIGHT; doc.Add(paragraph11); float antes = writer.GetVerticalPosition(true); float diff = antes - 353; for (int i = 0; i < diff / 20; i++) { doc.Add(Chunk.NEWLINE); } doc.Add(jpg); doc.Add(Chunk.NEWLINE); doc.Add(paragraph1); doc.Add(paragraph2); doc.Add(paragraph3); doc.Add(paragraph4); doc.Add(paragraph5); doc.Add(Chunk.NEWLINE); doc.Add(Chunk.NEWLINE); doc.Add(Chunk.NEWLINE); doc.Add(paragraph6); doc.Add(Chunk.NEWLINE); doc.Add(paragraph7); doc.Add(paragraph8); if (!String.IsNullOrEmpty(recibo.MotivoAnulacion)) { Paragraph paragraph9 = new Paragraph(@"Motivo Anulación:", _tituloFont); paragraph9.Alignment = Element.ALIGN_LEFT; doc.Add(paragraph9); String anulacionString = Regex.Replace(recibo.MotivoAnulacion, @"^\s+$[\r\n]*", "", RegexOptions.Multiline); Paragraph paragraph10 = new Paragraph(@anulacionString, cuota_font); paragraph10.Alignment = Element.ALIGN_LEFT; doc.Add(paragraph10); } doc.Add(Chunk.NEWLINE); doc.Add(paragraph11); doc.Close(); byte[] Result = ms.ToArray(); writer.Close(); Sistema.GetInstancia().PDFActual = Result; Sistema.GetInstancia().AumentarNroRecibo(Session["rut"].ToString()); // Session["pdf"] = Result; gridViewDocumentos.AllowPaging = true; if (Sistema.GetInstancia().PDFActual != null) { //Response.Redirect("VisorPDFReportes.aspx"); Response.Write("<script>"); Response.Write("window.open('VisorPDFReportes.aspx', '_blank');"); Response.Write("</script>"); } } catch { } }
public IActionResult Pdf() { byte[] userId; int id = 0; if (HttpContext.Session.TryGetValue("userID", out userId)) { Int32.TryParse(System.Text.Encoding.UTF8.GetString(userId), out id); } List <BillViewModel> listaFacturas = db.getFacturasPDF(id); string sWebRootFolder = _hostingEnvironment.WebRootPath; string sFileName = @"demo.pdf"; string URL = string.Format("{0}://{1}/{2}", Request.Scheme, Request.Host, sFileName); FileInfo file = new FileInfo(Path.Combine(sWebRootFolder, sFileName)); if (file.Exists) { file.Delete(); file = new FileInfo(Path.Combine(sWebRootFolder, sFileName)); } // Creamos el documento con el tamaño de página tradicional Document doc = new Document(PageSize.LETTER); // Indicamos donde vamos a guardar el documento iTextSharp.text.pdf.PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(sWebRootFolder + "/" + sFileName, FileMode.Create)); // Abrimos el archivo doc.Open(); // Creamos el tipo de Font que vamos utilizar iTextSharp.text.Font _standardFont = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10, iTextSharp.text.Font.NORMAL, BaseColor.BLACK); // Escribimos el encabezamiento en el documento doc.Add(new Paragraph("Detalles de su facturación")); doc.Add(Chunk.NEWLINE); // Creamos una tabla que contendrá el nombre, apellido y zona // de nuestros visitante. foreach (BillViewModel factura in listaFacturas) { PdfPTable tblPrueba = new PdfPTable(2); tblPrueba.WidthPercentage = 100; // Configuramos el título de las columnas de la tabla PdfPCell idFactura = new PdfPCell(new Phrase("Id Factura", _standardFont)); idFactura.BorderWidth = 0; idFactura.BorderWidthBottom = 0.75f; PdfPCell fecha = new PdfPCell(new Phrase("Fecha", _standardFont)); fecha.BorderWidth = 0; fecha.BorderWidthBottom = 0.75f; // Añadimos las celdas a la tabla tblPrueba.AddCell(idFactura); tblPrueba.AddCell(fecha); // Cambiamos el tipo de Font para el listado _standardFont = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10, iTextSharp.text.Font.NORMAL, BaseColor.BLUE); // Llenamos la tabla con el primer resultado idFactura = new PdfPCell(new Phrase(factura.IdBD.ToString(), _standardFont)); idFactura.BorderWidth = 0; fecha = new PdfPCell(new Phrase(factura.Fecha.ToString(), _standardFont)); fecha.BorderWidth = 0; // Añadimos las celdas a la tabla tblPrueba.AddCell(idFactura); tblPrueba.AddCell(fecha); // Finalmente, añadimos la tabla al documento PDF doc.Add(tblPrueba); foreach (BillDetailViewModel linea in factura.LineasFactura) { PdfPTable tblPrueba2 = new PdfPTable(3); tblPrueba2.WidthPercentage = 100; // Configuramos el título de las columnas de la tabla PdfPCell nomProducto = new PdfPCell(new Phrase("Producto", _standardFont)); nomProducto.BorderWidth = 0; nomProducto.BorderWidthBottom = 0.75f; PdfPCell cantidad = new PdfPCell(new Phrase("Cantidad", _standardFont)); cantidad.BorderWidth = 0; cantidad.BorderWidthBottom = 0.75f; PdfPCell subtotal = new PdfPCell(new Phrase("Subtotal", _standardFont)); subtotal.BorderWidth = 0; subtotal.BorderWidthBottom = 0.75f; // Añadimos las celdas a la tabla tblPrueba2.AddCell(nomProducto); tblPrueba2.AddCell(cantidad); tblPrueba2.AddCell(subtotal); // Cambiamos el tipo de Font para el listado _standardFont = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10, iTextSharp.text.Font.NORMAL, BaseColor.BLUE); // Llenamos la tabla con el primer resultado nomProducto = new PdfPCell(new Phrase(linea.nomProducto, _standardFont)); nomProducto.BorderWidth = 0; cantidad = new PdfPCell(new Phrase(linea.Cantidad.ToString(), _standardFont)); cantidad.BorderWidth = 0; subtotal = new PdfPCell(new Phrase(linea.SubtotalBD.ToString(), _standardFont)); subtotal.BorderWidth = 0; // Añadimos las celdas a la tabla tblPrueba2.AddCell(nomProducto); tblPrueba2.AddCell(cantidad); tblPrueba2.AddCell(subtotal); // Finalmente, añadimos la tabla al documento PDF doc.Add(tblPrueba2); } //foreach 2 } //foreach 1 doc.Close(); writer.Close(); ViewBag.URL = URL; return(View("../Users/Bajar")); }