public void Add(Athlete athete) { var data = new IT.Phrase(athete.Id.ToString() , IT.FontFactory.GetFont(IT.FontFactory.HELVETICA, SIZE_ROW, IT.Font.NORMAL)); var cell = new IT.pdf.PdfPCell(data); cell.HorizontalAlignment = IT.Element.ALIGN_LEFT; cell.PaddingBottom = PAD_BOTTOM; table.AddCell(cell); data = new IT.Phrase(athete.Surname + " " + athete.Name, IT.FontFactory.GetFont(IT.FontFactory.HELVETICA, SIZE_ROW, IT.Font.NORMAL)); cell = new IT.pdf.PdfPCell(data); cell.HorizontalAlignment = IT.Element.ALIGN_LEFT; cell.PaddingBottom = PAD_BOTTOM; table.AddCell(cell); data = new IT.Phrase(" ", IT.FontFactory.GetFont(IT.FontFactory.HELVETICA, SIZE_TITLE, IT.Font.NORMAL)); cell = new IT.pdf.PdfPCell(data); cell.HorizontalAlignment = IT.Element.ALIGN_LEFT; cell.PaddingBottom = PAD_BOTTOM; table.AddCell(cell); }
protected iTextSharp.text.pdf.PdfPCell ImageCell(string path, float scale, int align, int rowSpan, int colSpan) { iTextSharp.text.pdf.PdfPCell cellImg = null; try { if (path != null) { iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(GetImagePath(path));//HttpContext.Current.Server.MapPath(path) image.ScalePercent(scale); cellImg = new iTextSharp.text.pdf.PdfPCell(image); cellImg.VerticalAlignment = iTextSharp.text.pdf.PdfPCell.ALIGN_TOP; // cellImg.BorderColor = iTextSharp.text.Color.WHITE; cellImg.HorizontalAlignment = iTextSharp.text.pdf.PdfPCell.ALIGN_CENTER; cellImg.FixedHeight = 40f; cellImg.PaddingBottom = 0f; cellImg.PaddingTop = 1f; // cellImg.Top = 2f; if (rowSpan > 0) { cellImg.Rowspan = rowSpan; } if (colSpan > 0) { cellImg.Colspan = colSpan; } } } catch (Exception ex) { } return(cellImg); }
protected iTextSharp.text.pdf.PdfPCell ImageCell(string path, float scale, float height, int hAlign, int vAlign = iTextSharp.text.pdf.PdfPCell.ALIGN_TOP, float p_left = 0f, float p_right = 0f, float p_top = 0f, float p_btm = 0f, string borderPattren = "T,R,B") { iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(GetImagePath(path));//HttpContext.Current.Server.MapPath(path) image.ScalePercent(scale); iTextSharp.text.pdf.PdfPCell cell = new iTextSharp.text.pdf.PdfPCell(image); cell.BorderColor = iTextSharp.text.Color.BLACK; cell.VerticalAlignment = iTextSharp.text.pdf.PdfPCell.ALIGN_TOP; cell.HorizontalAlignment = hAlign; //cell.PaddingBottom = 0f; //cell.PaddingTop = 0f; cell.Border = GetBorderSides(borderPattren); if (p_btm >= 0f) { cell.PaddingBottom = p_btm; } if (p_top >= 0f) { cell.PaddingTop = p_top; } if (p_left >= 0f) { cell.PaddingLeft = p_left; } if (p_right >= 0f) { cell.PaddingRight = p_right; } return(cell); }
public static iTextSharp.text.pdf.PdfPTable GenerarTablaPDF(int AnchoPorcentaje, int Alineacion, System.Data.DataTable dt) { iTextSharp.text.pdf.PdfPTable tbl = new iTextSharp.text.pdf.PdfPTable(dt.Columns.Count); iTextSharp.text.pdf.PdfPCell[] celCol = new iTextSharp.text.pdf.PdfPCell[dt.Columns.Count]; for (int i = 0; i < celCol.Length; i++) { celCol[i] = new iTextSharp.text.pdf.PdfPCell( new iTextSharp.text.Paragraph( new iTextSharp.text.Chunk(dt.Columns[i].ColumnName, iTextSharp.text.FontFactory.GetFont("ARIAL", 10, iTextSharp.text.Font.BOLD)))); } tbl.WidthPercentage = AnchoPorcentaje; tbl.HorizontalAlignment = Alineacion; tbl.Rows.Add(new iTextSharp.text.pdf.PdfPRow(celCol)); for (int i = 0; i < dt.Rows.Count; i++) { var cell = new iTextSharp.text.pdf.PdfPCell[dt.Columns.Count]; for (int j = 0; j < dt.Columns.Count; j++) { cell[j] = new iTextSharp.text.pdf.PdfPCell( new iTextSharp.text.Paragraph( new iTextSharp.text.Chunk(dt.Rows[i][j].ToString(), iTextSharp.text.FontFactory.GetFont("ARIAL", 9, iTextSharp.text.Font.NORMAL)))); } tbl.Rows.Add(new iTextSharp.text.pdf.PdfPRow(cell)); } return(tbl); }
private static void GetInfoPDF(Jądro J, int i, iTextSharp.text.pdf.PdfPTable table, List <string> listawybranychinformacji) { foreach (var item in listawybranychinformacji) { if (item == "Numer Matrycy") { iTextSharp.text.pdf.PdfPCell cell = new iTextSharp.text.pdf.PdfPCell(); iTextSharp.text.Paragraph p = new iTextSharp.text.Paragraph(); p.Add(new iTextSharp.text.Phrase("Numer Matrycy")); p.Add(new iTextSharp.text.Phrase(Jądro.NAJLEPSZE.wypiszNRMatrycy(i))); p.Alignment = iTextSharp.text.Element.ALIGN_CENTER; if (Jądro.NAJLEPSZE.wypiszNRMatrycy(i) != "") { cell.AddElement(p); table.AddCell(cell); } } if (item == "ID") { iTextSharp.text.pdf.PdfPCell cell = new iTextSharp.text.pdf.PdfPCell(); iTextSharp.text.Paragraph p = new iTextSharp.text.Paragraph(); p.Add(new iTextSharp.text.Phrase("ID")); p.Add(new iTextSharp.text.Phrase(Jądro.NAJLEPSZE.wypiszID(i))); p.Alignment = iTextSharp.text.Element.ALIGN_CENTER; if (Jądro.NAJLEPSZE.wypiszNRMatrycy(i) != "") { cell.AddElement(p); table.AddCell(cell); } } if (item == "Punkt Zaczepienia") { iTextSharp.text.pdf.PdfPCell cell = new iTextSharp.text.pdf.PdfPCell(); iTextSharp.text.Paragraph p = new iTextSharp.text.Paragraph(); p.Add(new iTextSharp.text.Phrase("Punkt Zaczepienia")); p.Add(new iTextSharp.text.Phrase(Jądro.NAJLEPSZE.wypiszPunktZaczepienia(i))); p.Alignment = iTextSharp.text.Element.ALIGN_CENTER; if (Jądro.NAJLEPSZE.wypiszNRMatrycy(i) != "") { cell.AddElement(p); table.AddCell(cell); } } if (item == "Wymiary") { iTextSharp.text.pdf.PdfPCell cell = new iTextSharp.text.pdf.PdfPCell(); iTextSharp.text.Paragraph p = new iTextSharp.text.Paragraph(); p.Add(new iTextSharp.text.Phrase("Wymiary")); p.Add(new iTextSharp.text.Phrase(Jądro.NAJLEPSZE.wypiszWymiary(i))); p.Alignment = iTextSharp.text.Element.ALIGN_CENTER; if (Jądro.NAJLEPSZE.wypiszNRMatrycy(i) != "") { cell.AddElement(p); table.AddCell(cell); } } } }
/// <summary> /// Sets the cell properties. /// </summary> /// <param name="cell">The cell.</param> /// <param name="pdfCell">The PDF cell.</param> /// <returns>The PDF cell with converted odf cell properties.</returns> private iTextSharp.text.pdf.PdfPCell SetCellProperties(Cell cell, iTextSharp.text.pdf.PdfPCell pdfCell) { try { return(null); } catch (Exception) { throw; } }
private IT.pdf.PdfPTable GetTable(int year) { var ed = new IT.Phrase("Trofeo Luca De Gerone " + year.ToString() , IT.FontFactory.GetFont(IT.FontFactory.HELVETICA, SIZE_TITLE + 2, IT.Font.BOLD) ); //pett, nome , firma float[] widths = {1f,6f,6f, 4f}; IT.pdf.PdfPTable table = new IT.pdf.PdfPTable(widths); table.HeaderRows = 2; table.DefaultCell.Border = IT.Rectangle.NO_BORDER; // edizione var cell = new IT.pdf.PdfPCell(ed); cell.HorizontalAlignment = IT.Element.ALIGN_CENTER; cell.Colspan = COLUMNS; cell.PaddingBottom = PAD_BOTTOM; table.AddCell(cell); // riga vuota //table.AddCell(GetEmptyRow()); var data = new IT.Phrase("Pett.", IT.FontFactory.GetFont(IT.FontFactory.HELVETICA, SIZE_ROW, IT.Font.BOLD)); cell = new IT.pdf.PdfPCell(data); cell.HorizontalAlignment = IT.Element.ALIGN_LEFT; cell.PaddingBottom = PAD_BOTTOM; table.AddCell(cell); data = new IT.Phrase("Cognome", IT.FontFactory.GetFont(IT.FontFactory.HELVETICA, SIZE_ROW, IT.Font.BOLD)); cell = new IT.pdf.PdfPCell(data); cell.HorizontalAlignment = IT.Element.ALIGN_LEFT; cell.PaddingBottom = PAD_BOTTOM; table.AddCell(cell); data = new IT.Phrase("Nome", IT.FontFactory.GetFont(IT.FontFactory.HELVETICA, SIZE_ROW, IT.Font.BOLD)); cell = new IT.pdf.PdfPCell(data); cell.HorizontalAlignment = IT.Element.ALIGN_LEFT; cell.PaddingBottom = PAD_BOTTOM; table.AddCell(cell); data = new IT.Phrase("Firma di un genitore", IT.FontFactory.GetFont(IT.FontFactory.HELVETICA, SIZE_ROW, IT.Font.BOLD)); cell = new IT.pdf.PdfPCell(data); cell.HorizontalAlignment = IT.Element.ALIGN_RIGHT; cell.PaddingBottom = PAD_BOTTOM; table.AddCell(cell); return table; }
protected iTextSharp.text.pdf.PdfPCell ImageCell(byte[] path, float scale, int hAlign, int vAlign = iTextSharp.text.pdf.PdfPCell.ALIGN_TOP, iTextSharp.text.Color backColor = null) { iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(path); image.ScalePercent(scale); iTextSharp.text.pdf.PdfPCell cell = new iTextSharp.text.pdf.PdfPCell(image); cell.BorderColor = backColor == null ? iTextSharp.text.Color.WHITE : backColor; cell.VerticalAlignment = vAlign; cell.HorizontalAlignment = hAlign; cell.PaddingBottom = 0f; cell.PaddingTop = 0f; return(cell); }
/// <summary> /// Converts the specified table. /// </summary> /// <param name="table">The table.</param> /// <returns>The PDF table.</returns> public iTextSharp.text.pdf.PdfPTable Convert(Table table) { try { iTextSharp.text.pdf.PdfPTable pdfTable; TableLayoutInfo tableLayout = new TableLayoutInfo(); tableLayout.AnalyzeTableLayout(table); if (tableLayout.CellWidths != null) { pdfTable = new iTextSharp.text.pdf.PdfPTable(tableLayout.CellWidths); } else { pdfTable = new iTextSharp.text.pdf.PdfPTable(tableLayout.MaxCells); } if (table.Style != null && table.Style is TableStyle && ((TableStyle)table.Style).TableProperties != null) { //((TableStyle)table.Style).TableProperties.Width } foreach(Row row in table.Rows) { foreach(Cell cell in row.Cells) { iTextSharp.text.pdf.PdfPCell pdfCell = new iTextSharp.text.pdf.PdfPCell(); if (cell.ColumnRepeating != null && Int32.Parse(cell.ColumnRepeating) > 0) { pdfCell.Colspan = Int32.Parse(cell.ColumnRepeating); } foreach(iTextSharp.text.IElement pdfElement in MixedContentConverter.GetMixedPdfContent(cell.Content)) { pdfCell.AddElement(pdfElement); } pdfTable.AddCell(pdfCell); } } //pdfTable = this.SetProperties(table, pdfTable, maxCells); return pdfTable; } catch(Exception) { throw; } }
/// <summary> /// Converts the specified table. /// </summary> /// <param name="table">The table.</param> /// <returns>The PDF table.</returns> public iTextSharp.text.pdf.PdfPTable Convert(Table table) { try { iTextSharp.text.pdf.PdfPTable pdfTable; TableLayoutInfo tableLayout = new TableLayoutInfo(); tableLayout.AnalyzeTableLayout(table); if (tableLayout.CellWidths != null) { pdfTable = new iTextSharp.text.pdf.PdfPTable(tableLayout.CellWidths); } else { pdfTable = new iTextSharp.text.pdf.PdfPTable(tableLayout.MaxCells); } if (table.Style != null && table.Style is TableStyle && ((TableStyle)table.Style).TableProperties != null) { //((TableStyle)table.Style).TableProperties.Width } foreach (Row row in table.Rows) { foreach (Cell cell in row.Cells) { iTextSharp.text.pdf.PdfPCell pdfCell = new iTextSharp.text.pdf.PdfPCell(); if (cell.ColumnRepeating != null && Int32.Parse(cell.ColumnRepeating) > 0) { pdfCell.Colspan = Int32.Parse(cell.ColumnRepeating); } foreach (iTextSharp.text.IElement pdfElement in MixedContentConverter.GetMixedPdfContent(cell.Content)) { pdfCell.AddElement(pdfElement); } pdfTable.AddCell(pdfCell); } } //pdfTable = this.SetProperties(table, pdfTable, maxCells); return(pdfTable); } catch (Exception) { throw; } }
/// <summary> /// 创建pdf表格单元格 /// </summary> /// <param name="text"></param> /// <param name="pdfFont"></param> /// <returns></returns> private static iTextSharp.text.pdf.PdfPCell CreatePdfPCell(string text, iTextSharp.text.Font pdfFont) { iTextSharp.text.Phrase phrase = new iTextSharp.text.Phrase(text, pdfFont); iTextSharp.text.pdf.PdfPCell pdfPCell = new iTextSharp.text.pdf.PdfPCell(phrase); // TODO 单元格垂直居中显示 pdfPCell.HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER; pdfPCell.VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE; pdfPCell.MinimumHeight = 30; return(pdfPCell); }
protected iTextSharp.text.pdf.PdfPCell GetStringCell(string strValue, string fontFamilyName, float fontSize, int fontweight, iTextSharp.text.Color fontColor, int h_align, int v_align, float height, float p_left, float p_right, float p_top, float p_btm, string borderPattren, int rowspan, int colspan, iTextSharp.text.Color bgColor = null) { iTextSharp.text.pdf.PdfPCell pthCell = new iTextSharp.text.pdf.PdfPCell(new iTextSharp.text.Phrase(new iTextSharp.text.Chunk(strValue, GetFont(fontFamilyName, fontSize, fontweight, fontColor)))); try { pthCell.VerticalAlignment = v_align; pthCell.HorizontalAlignment = h_align; if (height > 0f) { pthCell.FixedHeight = height; } if (rowspan > 0) { pthCell.Rowspan = rowspan; } if (colspan > 0) { pthCell.Colspan = colspan; } pthCell.BackgroundColor = bgColor == null ? iTextSharp.text.Color.WHITE : bgColor; if (p_btm >= 0f) { pthCell.PaddingBottom = p_btm; } if (p_top >= 0f) { pthCell.PaddingTop = p_top; } if (p_left >= 0f) { pthCell.PaddingLeft = p_left; } if (p_right >= 0f) { pthCell.PaddingRight = p_right; } pthCell.Border = GetBorderSides(borderPattren); } catch (Exception ex) { } return(pthCell); }
protected iTextSharp.text.pdf.PdfPCell ImageCell(byte[] path, string SubHeading, string FontFamily, float fontSize = 10f, float scale = 50f, float Img_Height = 50f, float lbl_Height = 20f, int fontWeight = iTextSharp.text.Font.NORMAL, float totalWidth = 250f, float abWidth = 210, int rowSpan = 1, int colSpan = 1) { iTextSharp.text.pdf.PdfPTable tabSig = new iTextSharp.text.pdf.PdfPTable(1); iTextSharp.text.pdf.PdfPCell cell = null; try { tabSig.TotalWidth = totalWidth; tabSig.LockedWidth = true; tabSig.SetWidths(new float[] { 1.0f }); iTextSharp.text.pdf.PdfPCell cellSig = GetStringCell(SubHeading, FontFamily, fontSize, fontWeight, iTextSharp.text.Color.BLACK, iTextSharp.text.pdf.PdfCell.ALIGN_LEFT, iTextSharp.text.pdf.PdfCell.ALIGN_MIDDLE, lbl_Height, 5f, -1f, 4f, 4f, "", 1, 1); tabSig.AddCell(cellSig); if (path != null) { iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(path); //image.ScaleAbsolute(220.0f,50.0f); //image.ScalePercent(scale); image.ScaleAbsolute(abWidth, scale); // image.ScalePercent(scale); iTextSharp.text.pdf.PdfPCell cellImg = new iTextSharp.text.pdf.PdfPCell(image); cellImg.VerticalAlignment = iTextSharp.text.pdf.PdfPCell.ALIGN_TOP; cellImg.BorderColor = iTextSharp.text.Color.WHITE; cellImg.HorizontalAlignment = iTextSharp.text.pdf.PdfPCell.ALIGN_CENTER; cellImg.FixedHeight = Img_Height; cellImg.PaddingBottom = 0f; cellImg.PaddingTop = 1f; // cellImg.Top = 2f; tabSig.AddCell(cellImg); } cell = new iTextSharp.text.pdf.PdfPCell(tabSig); cell.BorderColor = iTextSharp.text.Color.BLACK; cell.HorizontalAlignment = iTextSharp.text.pdf.PdfPCell.ALIGN_LEFT; cell.VerticalAlignment = iTextSharp.text.pdf.PdfPCell.ALIGN_MIDDLE; cell.PaddingTop = 1f; cell.PaddingBottom = 1f; cell.Rowspan = rowSpan; cell.Colspan = colSpan; } catch (Exception ex) { } return(cell); }
public void Add(Athlete athete) { // posizione var ps = new IT.Phrase((++pos).ToString(), IT.FontFactory.GetFont(IT.FontFactory.HELVETICA, SIZE_ROW, IT.Font.BOLD) ); var cell = new IT.pdf.PdfPCell(ps); cell.HorizontalAlignment = IT.Element.ALIGN_LEFT; // evidenzia i primi 3 if (pos < 4) { cell.GrayFill = 0.90F; } cell.PaddingBottom = PAD_BOTTOM; table.AddCell(cell); var data = new IT.Phrase(athete.Id.ToString() , IT.FontFactory.GetFont(IT.FontFactory.HELVETICA, SIZE_ROW, IT.Font.NORMAL)); cell = new IT.pdf.PdfPCell(data); cell.HorizontalAlignment = IT.Element.ALIGN_LEFT; cell.PaddingBottom = PAD_BOTTOM; table.AddCell(cell); data = new IT.Phrase(athete.Surname + " " + athete.Name, IT.FontFactory.GetFont(IT.FontFactory.HELVETICA, SIZE_ROW, IT.Font.NORMAL)); cell = new IT.pdf.PdfPCell(data); cell.HorizontalAlignment = IT.Element.ALIGN_LEFT; cell.PaddingBottom = PAD_BOTTOM; table.AddCell(cell); data = new IT.Phrase(athete.Year.ToString(), IT.FontFactory.GetFont(IT.FontFactory.HELVETICA, SIZE_ROW, IT.Font.NORMAL)); cell = new IT.pdf.PdfPCell(data); cell.HorizontalAlignment = IT.Element.ALIGN_LEFT; cell.PaddingBottom = PAD_BOTTOM; table.AddCell(cell); string t = athete.Time == "99:99" ? "rit." : athete.Time; data = new IT.Phrase(t, IT.FontFactory.GetFont(IT.FontFactory.HELVETICA, SIZE_ROW, IT.Font.NORMAL)); cell = new IT.pdf.PdfPCell(data); cell.HorizontalAlignment = IT.Element.ALIGN_RIGHT; cell.PaddingBottom = PAD_BOTTOM; table.AddCell(cell); }
protected iTextSharp.text.pdf.PdfPCell PhraseCell(iTextSharp.text.pdf.PdfPTable table, int hAlign, int vAlign = iTextSharp.text.pdf.PdfPCell.ALIGN_TOP, iTextSharp.text.Color borderColor = null) { iTextSharp.text.pdf.PdfPCell cell = new iTextSharp.text.pdf.PdfPCell(table); try { cell.BorderColor = borderColor == null ? iTextSharp.text.Color.WHITE : borderColor; cell.HorizontalAlignment = hAlign; cell.VerticalAlignment = vAlign; cell.PaddingBottom = 2f; cell.PaddingTop = 0f; } catch (Exception ex) { } return(cell); }
public MemoryStream memoryStr2(DataTable dT) { //====================== using (MemoryStream ms = new MemoryStream()) using (Document document = new Document(PageSize.A4.Rotate(), 25, 25, 30, 30)) using (iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, ms)) { document.Open(); document.Add(new Paragraph(" ")); // tabela pierwsza // przetważanie tabeli if (dT.Rows.Count > 0) { int il_kolumn = dT.Columns.Count; iTextSharp.text.pdf.PdfPTable table = new iTextSharp.text.pdf.PdfPTable(il_kolumn); for (int ij = 0; ij < il_kolumn; ij++) { string dana = dT.Columns[ij].ColumnName.ToString(); iTextSharp.text.pdf.PdfPCell cell = new iTextSharp.text.pdf.PdfPCell(new Phrase(dana)); cell.BackgroundColor = iTextSharp.text.BaseColor.LIGHT_GRAY; table.AddCell(cell); }// end for foreach (DataRow dR in dT.Rows) { // loop po wierszach for (int j = 0; j < il_kolumn; j++) { // loop po kolumnach string dana = dR[j].ToString().Trim(); iTextSharp.text.pdf.PdfPCell cell = new iTextSharp.text.pdf.PdfPCell(new Phrase(dana)); table.AddCell(cell); } //end for } // end foreach document.Add(table); } // end of if document.Close(); document.Close(); writer.Close(); ms.Close(); //====================== return(ms); } }
protected iTextSharp.text.pdf.PdfPCell PhraseCell(iTextSharp.text.Phrase phrase, float height, int hAlign, int vAlign = iTextSharp.text.pdf.PdfPCell.ALIGN_TOP, iTextSharp.text.Color backColor = null, iTextSharp.text.Color borderColor = null) { iTextSharp.text.pdf.PdfPCell cell = new iTextSharp.text.pdf.PdfPCell(phrase); try { cell.BorderColor = iTextSharp.text.Color.WHITE; cell.BackgroundColor = backColor; cell.FixedHeight = height; cell.VerticalAlignment = vAlign; cell.HorizontalAlignment = hAlign; cell.PaddingBottom = 2f; cell.PaddingTop = 0f; } catch (Exception ex) { } return(cell); }
public void AddPage() { var table = GetTable(year); for (int i = 0; i < rowsPerPage; i++) { var data = new IT.Phrase((pageCounter * rowsPerPage + i + 1).ToString("000") , IT.FontFactory.GetFont(IT.FontFactory.HELVETICA, 12, IT.Font.NORMAL)); var cell = new IT.pdf.PdfPCell(data); cell.MinimumHeight = 60f; cell.HorizontalAlignment = IT.Element.ALIGN_LEFT; cell.PaddingBottom = PAD_BOTTOM; table.AddCell(cell); table.AddCell(new IT.pdf.PdfPCell()); table.AddCell(new IT.pdf.PdfPCell()); table.AddCell(new IT.pdf.PdfPCell()); } pageCounter++; document.Add(table); document.NewPage(); }
public static byte[] CreatePdfDataFromDataGridView(DataGridView grid, int startColumn, int endColumn, string title) { byte[] pdfData = null; PdfDocument document = null; MemoryStream ms = null; try { ms = new MemoryStream(); document = new PdfDocument(); PdfWriter writer = PdfWriter.GetInstance(document, ms); document.Open(); PdfContentByte cb = writer.DirectContent; cb.BeginText(); float fontSizeHeader = 14f; float topCursor = document.GetTop(10f); cb.SetFontAndSize(baseFontTimesBold, fontSizeHeader); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, title, document.GetLeft(10f), topCursor, 0); topCursor -= 20f; cb.EndText(); int nCols = endColumn - startColumn; PdfPTable table = new PdfPTable(nCols); table.TotalWidth = document.GetRight(10) - document.GetLeft(10); for (int i = startColumn; i < endColumn; i++) { PdfPCell cell = new PdfPCell(GetHeaderPhrase(grid.Columns[i].HeaderText)); cell.HorizontalAlignment = PdfPCell.ALIGN_LEFT; cell.VerticalAlignment = PdfPCell.ALIGN_LEFT; table.AddCell(cell); } for (int i = 0; i < grid.Rows.Count; i++) { for (int j = startColumn; j < endColumn; j++) { PdfPCell cell = new PdfPCell(GetCellPhrase(grid.Rows[i].Cells[j].FormattedValue.ToString())); cell.HorizontalAlignment = PdfPCell.ALIGN_LEFT; cell.VerticalAlignment = PdfPCell.ALIGN_LEFT; table.AddCell(cell); } } float currHeight = topCursor; int currRow = 0, pageRows = 0, nRows = grid.Rows.Count + 1; for (int i = 0; i < nRows; i++) { currHeight -= table.GetRowHeight(i); pageRows++; if (currHeight <= document.GetBottom(10f)) { table.WriteSelectedRows(currRow, currRow + pageRows, document.GetLeft(10), topCursor, cb); document.NewPage(); currRow += pageRows; currHeight = topCursor = document.GetTop(10f); pageRows = 0; } } if (pageRows > 0) { table.WriteSelectedRows(currRow, currRow + pageRows, document.GetLeft(10), topCursor, cb); document.NewPage(); } } finally { document?.Close(); if (ms != null) { pdfData = ms.GetBuffer(); } } return(pdfData); }
public static byte[] CreatePdfDataFromAssignment(SqlConnection conn, SqlTransaction trans, Assignment assignment) { byte[] pdfData = null; PdfDocument document = null; MemoryStream ms = null; try { ms = new MemoryStream(); document = new PdfDocument(); PdfWriter writer = PdfWriter.GetInstance(document, ms); document.Open(); PdfContentByte cb = writer.DirectContent; cb.BeginText(); float fontSize = 10, fontSizeHeader = 16; float margin = 50; float leftCursor = margin, topCursor = document.Top - 10f, lineSpace = 13; PdfImage labLogo = GetLaboratoryLogo(conn, trans, assignment.LaboratoryId); if (labLogo != null) { CropImageToHeight(labLogo, 64f); labLogo.SetAbsolutePosition(document.GetRight(10f) - labLogo.PlainWidth, document.GetTop(10f) - 40f); document.Add(labLogo); } cb.SetFontAndSize(baseFontTimesBold, fontSizeHeader); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "OPPDRAGSOVERSIKT", leftCursor, topCursor, 0); cb.SetFontAndSize(baseFontTimes, fontSize); topCursor -= lineSpace * 2; cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Oppdragsnummer: " + assignment.Name, leftCursor, topCursor, 0); topCursor -= lineSpace; cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Oppdrag opprettet: " + assignment.CreateDate.ToString(Utils.DateFormatNorwegian), leftCursor, topCursor, 0); topCursor -= lineSpace; cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Utskriftsdato: " + DateTime.Now.ToString(Utils.DateFormatNorwegian), leftCursor, topCursor, 0); topCursor -= lineSpace * 2; cb.SetFontAndSize(baseFontTimesBold, fontSize); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Oppdragsgiver, Firma/Avd.", leftCursor, topCursor, 0); cb.SetFontAndSize(baseFontTimes, fontSize); topCursor -= lineSpace; cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Navn: " + assignment.CustomerCompanyName, leftCursor, topCursor, 0); topCursor -= lineSpace; cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Addresse: " + assignment.CustomerCompanyAddress, leftCursor, topCursor, 0); topCursor -= lineSpace; cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Epost: " + assignment.CustomerCompanyEmail, leftCursor, topCursor, 0); topCursor -= lineSpace; cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Telefon: " + assignment.CustomerCompanyPhone, leftCursor, topCursor, 0); topCursor -= lineSpace * 2; cb.SetFontAndSize(baseFontTimesBold, fontSize); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Oppdragsgiver, Kontakt", leftCursor, topCursor, 0); cb.SetFontAndSize(baseFontTimes, fontSize); topCursor -= lineSpace; cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Navn: " + assignment.CustomerContactName, leftCursor, topCursor, 0); topCursor -= lineSpace; cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Addresse: " + assignment.CustomerContactAddress, leftCursor, topCursor, 0); topCursor -= lineSpace; cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Epost: " + assignment.CustomerContactEmail, leftCursor, topCursor, 0); topCursor -= lineSpace; cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Telefon: " + assignment.CustomerContactPhone, leftCursor, topCursor, 0); topCursor -= lineSpace * 2; cb.SetFontAndSize(baseFontTimesBold, fontSize); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Laboratorium", leftCursor, topCursor, 0); cb.SetFontAndSize(baseFontTimes, fontSize); topCursor -= lineSpace; cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Navn: " + assignment.LaboratoryName(conn, trans), leftCursor, topCursor, 0); topCursor -= lineSpace; cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Kontakt: " + assignment.ResponsibleName(conn, trans), leftCursor, topCursor, 0); topCursor -= lineSpace * 2; cb.SetFontAndSize(baseFontTimesBold, fontSize); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Måleresultater", leftCursor, topCursor, 0); cb.EndText(); topCursor -= lineSpace; PdfPTable table = new PdfPTable(13); table.TotalWidth = document.GetRight(margin) - document.GetLeft(margin); PdfPCell cell = new PdfPCell(GetHeaderPhrase("Analysis")); table.AddCell(cell); cell = new PdfPCell(GetHeaderPhrase("Sample Type")); table.AddCell(cell); cell = new PdfPCell(GetHeaderPhrase("P.Status")); table.AddCell(cell); cell = new PdfPCell(GetHeaderPhrase("A.Status")); table.AddCell(cell); cell = new PdfPCell(GetHeaderPhrase("Method")); table.AddCell(cell); cell = new PdfPCell(GetHeaderPhrase("Nuclide")); table.AddCell(cell); cell = new PdfPCell(GetHeaderPhrase("Activity")); table.AddCell(cell); cell = new PdfPCell(GetHeaderPhrase("Act.Unc.")); table.AddCell(cell); cell = new PdfPCell(GetHeaderPhrase("Act.Appr.")); table.AddCell(cell); cell = new PdfPCell(GetHeaderPhrase("MDA")); table.AddCell(cell); cell = new PdfPCell(GetHeaderPhrase("MDA Appr.")); table.AddCell(cell); cell = new PdfPCell(GetHeaderPhrase("Reportable")); table.AddCell(cell); cell = new PdfPCell(GetHeaderPhrase("Accredited")); table.AddCell(cell); string query = @" select s.number as 'sample', st.name as 'sample_type_name', sc.name as 'sample_component_name', p.number as 'preparation', pm.name_short as 'preparation_method', p.workflow_status_id as 'preparation_wfstatus', a.number as 'analysis', a.workflow_status_id as 'analysis_wfstatus', am.name_short as 'analysis_method', n.name as 'nuclide_name', ar.activity as 'act', ar.activity_uncertainty_abs as 'act.unc', ar.activity_approved as 'act.appr', ar.detection_limit as 'det.lim', ar.detection_limit_approved as 'det.lim.appr', ar.reportable, ar.accredited from sample s inner join sample_type st on st.id = s.sample_type_id left outer join sample_component sc on sc.id = s.sample_component_id inner join preparation p on p.sample_id = s.id and p.instance_status_id = 1 inner join preparation_method pm on pm.id = p.preparation_method_id inner join analysis a on a.preparation_id = p.id and a.instance_status_id = 1 and a.assignment_id = @assignment_id inner join analysis_result ar on ar.analysis_id = a.id and ar.instance_status_id = 1 and ar.reportable = 1 inner join analysis_method am on am.id = a.analysis_method_id inner join nuclide n on n.id = ar.nuclide_id order by s.number, p.number, a.number "; int nRows = 1; using (SqlDataReader reader = DB.GetDataReader(conn, trans, query, CommandType.Text, new[] { new SqlParameter("@assignment_id", assignment.Id) })) { while (reader.Read()) { int pwfstat = reader.GetInt32("preparation_wfstatus"); string spwfstat = "Unknown"; switch (pwfstat) { case WorkflowStatus.Construction: spwfstat = "Construction"; break; case WorkflowStatus.Complete: spwfstat = "Complete"; break; case WorkflowStatus.Rejected: spwfstat = "Rejected"; break; } int awfstat = reader.GetInt32("analysis_wfstatus"); string sawfstat = "Unknown"; switch (awfstat) { case WorkflowStatus.Construction: sawfstat = "Construction"; break; case WorkflowStatus.Complete: sawfstat = "Complete"; break; case WorkflowStatus.Rejected: sawfstat = "Rejected"; break; } string sact = ""; if (DB.IsValidField(reader["act"])) { sact = reader.GetDouble("act").ToString(Utils.ScientificFormat); } string sactunc = ""; if (DB.IsValidField(reader["act.unc"])) { sactunc = reader.GetDouble("act.unc").ToString(Utils.ScientificFormat); } string sdetlim = ""; if (DB.IsValidField(reader["det.lim"])) { sdetlim = reader.GetDouble("det.lim").ToString(Utils.ScientificFormat); } cell = new PdfPCell(GetCellPhrase(reader.GetString("sample") + " / " + reader.GetString("preparation") + " / " + reader.GetString("analysis"))); table.AddCell(cell); string sampleType = reader.GetString("sample_type_name"); if (DB.IsValidField(reader["sample_component_name"])) { sampleType += " / " + reader.GetString("sample_component_name"); } cell = new PdfPCell(GetCellPhrase(sampleType)); table.AddCell(cell); cell = new PdfPCell(GetCellPhrase(spwfstat)); table.AddCell(cell); cell = new PdfPCell(GetCellPhrase(sawfstat)); table.AddCell(cell); cell = new PdfPCell(GetCellPhrase(reader.GetString("preparation_method") + " / " + reader.GetString("analysis_method"))); table.AddCell(cell); cell = new PdfPCell(GetCellPhrase(reader.GetString("nuclide_name"))); table.AddCell(cell); cell = new PdfPCell(GetCellPhrase(sact)); table.AddCell(cell); cell = new PdfPCell(GetCellPhrase(sactunc)); table.AddCell(cell); cell = new PdfPCell(GetCellPhrase(reader.GetString("act.appr"))); table.AddCell(cell); cell = new PdfPCell(GetCellPhrase(sdetlim)); table.AddCell(cell); cell = new PdfPCell(GetCellPhrase(reader.GetString("det.lim.appr"))); table.AddCell(cell); cell = new PdfPCell(GetCellPhrase(reader.GetString("reportable"))); table.AddCell(cell); cell = new PdfPCell(GetCellPhrase(reader.GetString("accredited"))); table.AddCell(cell); nRows++; } } float currHeight = topCursor; int currRow = 0, pageRows = 0; for (int i = 0; i < nRows; i++) { currHeight -= table.GetRowHeight(i); pageRows++; if (currHeight <= document.GetBottom(10f)) { table.WriteSelectedRows(currRow, currRow + pageRows, document.GetLeft(10), topCursor, cb); document.NewPage(); currRow += pageRows; currHeight = topCursor = document.GetTop(10f); pageRows = 0; } } if (pageRows > 0) { table.WriteSelectedRows(currRow, currRow + pageRows, document.GetLeft(10), topCursor, cb); document.NewPage(); } } finally { document?.Close(); if (ms != null) { pdfData = ms.GetBuffer(); } } return(pdfData); }
/// <summary> /// Creates a table cell /// </summary> public iTextSharp.text.pdf.PdfPCell CreateTableCell(XmlAttributeCollection cellAttrs, System.Collections.IDictionary data) { int colspan = Moon.PDFDraw.Helper.GetIntAttributeValue("colspan", cellAttrs, 0); int horizontalalign = PDFDrawItextSharpHelper.Align( Moon.PDFDraw.Helper.GetAttributeValue("horizontalalign", cellAttrs, "Left")); int border = PDFDrawItextSharpHelper.Border( Moon.PDFDraw.Helper.GetStringArray(BorderAttributeConstant, cellAttrs)); iTextSharp.text.BaseColor borderColor = new iTextSharp.text.BaseColor( Moon.PDFDraw.Helper.GetAttributeColor("bordercolor", cellAttrs, "Black")); #if DEBUG //Console.WriteLine("PDFDrawItextSharp.CreateTableCell Border: " + border); #endif iTextSharp.text.pdf.PdfPCell cell = new iTextSharp.text.pdf.PdfPCell(); //iTextSharp.text.pdf.PdfPCell cell = new iTextSharp.text.pdf.PdfPCell(new iTextSharp.text.Phrase("xx")); if (colspan > 1) { cell.Colspan = colspan; } float borderWidth = Moon.PDFDraw.Helper.GetFloatAttributeValue("borderwidth", cellAttrs, -1); float borderWidthLeft = Moon.PDFDraw.Helper.GetFloatAttributeValue("borderwidthleft", cellAttrs, -1); float borderWidthTop = Moon.PDFDraw.Helper.GetFloatAttributeValue("borderwidthtop", cellAttrs, -1); float borderWidthRight = Moon.PDFDraw.Helper.GetFloatAttributeValue("borderwidthright", cellAttrs, -1); float borderWidthBottom = Moon.PDFDraw.Helper.GetFloatAttributeValue("borderwidthbottom", cellAttrs, -1); if (borderWidth != -1) cell.BorderWidth = borderWidth; if (borderWidthLeft != -1) cell.BorderWidthLeft = borderWidthLeft; if (borderWidthTop != -1) cell.BorderWidthTop = borderWidthTop; if (borderWidthRight != -1) cell.BorderWidthRight = borderWidthRight; if (borderWidthBottom != -1) cell.BorderWidthBottom = borderWidthBottom; cell.Border = iTextSharp.text.Rectangle.NO_BORDER; cell.EnableBorderSide(border); cell.HorizontalAlignment = horizontalalign; //cell.VerticalAlignment = iTextSharp.text.Element.ALIGN_TOP; cell.BorderColor = borderColor; //20130610 :: Add background color if( Moon.PDFDraw.Helper.GetAttributeValue(BackgroundColorAttributeConstant, cellAttrs, null) != null ){ cell.BackgroundColor = new BaseColor(Helper.GetAttributeColor(BackgroundColorAttributeConstant, cellAttrs, "White", data)); } //--- cell.UseAscender = true; cell.UseDescender = false; return cell; }
/// <summary> /// Creates a table cell /// </summary> /// <param name="colspan"></param> /// <param name="enableBroder_RECTANGLE_BORDER">iTextSharp.text.Rectangle.BOTTOM_BORDER /// | iTextSharp.text.Rectangle.RIGHT_BORDER /// | iTextSharp.text.Rectangle.LEFT_BORDER /// | iTextSharp.text.Rectangle.TOP_BORDER</param> /// <param name="horizontal_ELEMENT_ALIGN"></param> /// <param name="borderColor"></param> /// <param name="text"></param> /// <param name="font"></param> /// <returns></returns> public iTextSharp.text.pdf.PdfPCell CreateTableCell( int colspan, int enableBroder_RECTANGLE_BORDER, int horizontal_ELEMENT_ALIGN, iTextSharp.text.BaseColor borderColor, string text, iTextSharp.text.Font font) { iTextSharp.text.pdf.PdfPCell cell = new iTextSharp.text.pdf.PdfPCell(); if (colspan > 1) { cell.Colspan = colspan; } cell.Border = iTextSharp.text.Rectangle.NO_BORDER; cell.EnableBorderSide(enableBroder_RECTANGLE_BORDER); cell.HorizontalAlignment = horizontal_ELEMENT_ALIGN; cell.BorderColor = borderColor; cell.Phrase = new iTextSharp.text.Phrase(text, font); cell.UseAscender = true; cell.UseDescender = false; return cell; }
private void SetTable(string titleString, int year) { var ed = new IT.Phrase("Trofeo Luca De Gerone" + year.ToString() , IT.FontFactory.GetFont(IT.FontFactory.HELVETICA, SIZE_TITLE + 2, IT.Font.BOLD) ); var title = new IT.Phrase(titleString, IT.FontFactory.GetFont(IT.FontFactory.HELVETICA, SIZE_TITLE, IT.Font.BOLD) ); //pett, nome , tempo float[] widths = {1f,6f,4f}; table = new IT.pdf.PdfPTable(widths); table.HeaderRows = 2; table.DefaultCell.Border = IT.Rectangle.NO_BORDER; // edizione var cell = new IT.pdf.PdfPCell(ed); cell.HorizontalAlignment = IT.Element.ALIGN_CENTER; cell.Colspan = COLUMNS; cell.PaddingBottom = PAD_BOTTOM; table.AddCell(cell); // intesatazione cell = new IT.pdf.PdfPCell(title); cell.HorizontalAlignment = IT.Element.ALIGN_CENTER; cell.Colspan = COLUMNS; cell.PaddingBottom = PAD_BOTTOM; cell.GrayFill = 0.90F; table.AddCell(cell); // riga vuota //table.AddCell(GetEmptyRow()); var data = new IT.Phrase("Pett.", IT.FontFactory.GetFont(IT.FontFactory.HELVETICA, SIZE_ROW, IT.Font.BOLD)); cell = new IT.pdf.PdfPCell(data); cell.HorizontalAlignment = IT.Element.ALIGN_LEFT; cell.PaddingBottom = PAD_BOTTOM; table.AddCell(cell); data = new IT.Phrase("Nome", IT.FontFactory.GetFont(IT.FontFactory.HELVETICA, SIZE_ROW, IT.Font.BOLD)); cell = new IT.pdf.PdfPCell(data); cell.HorizontalAlignment = IT.Element.ALIGN_LEFT; cell.PaddingBottom = PAD_BOTTOM; table.AddCell(cell); data = new IT.Phrase("Tempo", IT.FontFactory.GetFont(IT.FontFactory.HELVETICA, SIZE_ROW, IT.Font.BOLD)); cell = new IT.pdf.PdfPCell(data); cell.HorizontalAlignment = IT.Element.ALIGN_RIGHT; cell.PaddingBottom = PAD_BOTTOM; table.AddCell(cell); }
public MemoryStream memoryStr(string sedzia, string tabela, string dzial, DateTime data1, DateTime data2, string aa, string bb) { //====================== using (MemoryStream ms = new MemoryStream()) using (Document document = new Document(PageSize.A4.Rotate(), 25, 25, 30, 30)) using (iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, ms)) { document.Open(); string id_sedziego = sedzia;//(string)Session["id_sedziego"]; string txt = cl.wyciagnij_sedziego(id_sedziego).ToString(); if (txt == "Object reference not set to an instance of an object.") { txt = ""; } document.Add(new Paragraph(txt)); document.Add(new Paragraph(" ")); // tabela pierwsza int i = 0; try { i = int.Parse(aa.Trim()) - 1; } catch (Exception) { } string cs = cl.podajConnectionString(int.Parse(dzial)); string kw = cl.podajKwerende(int.Parse(dzial), int.Parse(aa), int.Parse(bb), int.Parse(tabela)); DataTable dT = new DataTable(); try { DataSet dane = new DataSet(); dane.Tables.Clear(); if (tabela == "1") { dane = cl.pod_tabela(cs, kw, data1.ToShortDateString(), data2.ToShortDateString(), sedzia); } else { dane = cl.pod_tabela(cl.podajConnectionString(int.Parse(dzial)), cl.podajKwerende(int.Parse(dzial), 0, int.Parse(bb), int.Parse(tabela)), data1.ToShortDateString(), data2.ToShortDateString(), sedzia); } dT = dane.Tables[0]; } catch { } // przetważanie tabeli if (dT.Rows.Count > 0) { int il_kolumn = dT.Columns.Count; iTextSharp.text.pdf.PdfPTable table = new iTextSharp.text.pdf.PdfPTable(il_kolumn); for (int ij = 0; ij < il_kolumn; ij++) { string dana = dT.Columns[ij].ColumnName.ToString(); iTextSharp.text.pdf.PdfPCell cell = new iTextSharp.text.pdf.PdfPCell(new Phrase(dana)); cell.BackgroundColor = iTextSharp.text.BaseColor.LIGHT_GRAY; table.AddCell(cell); }// end for foreach (DataRow dR in dT.Rows) { // loop po wierszach for (int j = 0; j < il_kolumn; j++) { // loop po kolumnach string dana = dR[j].ToString().Trim(); iTextSharp.text.pdf.PdfPCell cell = new iTextSharp.text.pdf.PdfPCell(new Phrase(dana)); table.AddCell(cell); } //end for } // end foreach document.Add(table); } // end of if document.Close(); document.Close(); writer.Close(); ms.Close(); //====================== return(ms); } }
private IT.pdf.PdfPCell GetEmptyRow() { var cell = new IT.pdf.PdfPCell(); cell.Border = IT.Rectangle.NO_BORDER; cell.HorizontalAlignment = IT.Element.ALIGN_CENTER; cell.Colspan = COLUMNS; cell.PaddingBottom = 20F; return cell; }
public static byte[] CreatePdfDataFromAssignment(SqlConnection conn, SqlTransaction trans, Guid assignmentId) { string OrderName = "", LaboratoryName = "", ResponsibleName = "", CustomerName = "", CustomerCompany = "", CustomerAddress = ""; PdfImage labLogo = null; using (SqlDataReader reader = DB.GetDataReader(conn, trans, "csp_select_assignment_flat", CommandType.StoredProcedure, new SqlParameter("@id", assignmentId))) { if (reader.HasRows) { reader.Read(); OrderName = reader.GetString("name"); LaboratoryName = reader.GetString("laboratory_name"); ResponsibleName = reader.GetString("account_name"); CustomerName = reader.GetString("customer_contact_name"); CustomerCompany = reader.GetString("customer_company_name"); CustomerAddress = reader.GetString("customer_contact_address"); } } Guid labId = (Guid)DB.GetScalar(conn, trans, "select laboratory_id from assignment where id = @id", CommandType.Text, new SqlParameter("@id", assignmentId)); if (Utils.IsValidGuid(labId)) { using (SqlDataReader reader = DB.GetDataReader(conn, trans, "select laboratory_logo from laboratory where id = @id", CommandType.Text, new SqlParameter("@id", labId))) { if (reader.HasRows) { reader.Read(); if (DB.IsValidField(reader["laboratory_logo"])) { labLogo = PdfImage.GetInstance((byte[])reader["laboratory_logo"]); } } } } byte[] pdfData = null; PdfDocument document = null; MemoryStream ms = null; try { ms = new MemoryStream(); document = new PdfDocument(); PdfWriter writer = PdfWriter.GetInstance(document, ms); document.Open(); PdfContentByte cb = writer.DirectContent; cb.BeginText(); PdfBaseFont baseFont = PdfBaseFont.CreateFont(PdfBaseFont.TIMES_ROMAN, PdfBaseFont.CP1252, PdfBaseFont.NOT_EMBEDDED); PdfBaseFont baseFontBold = PdfBaseFont.CreateFont(PdfBaseFont.TIMES_BOLD, PdfBaseFont.CP1252, PdfBaseFont.NOT_EMBEDDED); PdfBaseFont baseFontItalic = PdfBaseFont.CreateFont(PdfBaseFont.TIMES_ITALIC, PdfBaseFont.CP1252, PdfBaseFont.NOT_EMBEDDED); float fontSize = 10, fontSizeHeader = 14; float margin = 50; float leftCursor = margin, topCursor = document.Top - margin, lineSpace = 13; bool hasLogos = false; if (labLogo != null) { CropImageToHeight(labLogo, 64f); labLogo.SetAbsolutePosition(leftCursor, topCursor); document.Add(labLogo); hasLogos = true; } if (hasLogos) { topCursor -= labLogo.ScaledHeight; } cb.SetFontAndSize(baseFontBold, fontSizeHeader); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "OPPDRAGSOVERSIKT", leftCursor, topCursor, 0); cb.SetFontAndSize(baseFont, fontSize); topCursor -= lineSpace * 2; cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Oppdrag: " + OrderName, leftCursor, topCursor, 0); topCursor -= lineSpace; string cust = CustomerName; if (!String.IsNullOrEmpty(CustomerCompany)) { cust += ", " + CustomerCompany; } cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Oppdragsgiver: " + cust, leftCursor, topCursor, 0); topCursor -= lineSpace; cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, CustomerAddress, leftCursor, topCursor, 0); topCursor -= lineSpace; cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Laboratorium/Kontaktperson: " + LaboratoryName + " / " + ResponsibleName, leftCursor, topCursor, 0); topCursor -= lineSpace * 4; cb.SetFontAndSize(baseFontBold, fontSizeHeader); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Måleresultater", leftCursor, topCursor, 0); cb.EndText(); topCursor -= lineSpace; PdfPTable table = new PdfPTable(13); table.TotalWidth = document.GetRight(margin) - document.GetLeft(margin); PdfPCell cell = new PdfPCell(GetHeaderPhrase("Analysis")); table.AddCell(cell); cell = new PdfPCell(GetHeaderPhrase("Sample Type")); table.AddCell(cell); cell = new PdfPCell(GetHeaderPhrase("P.Status")); table.AddCell(cell); cell = new PdfPCell(GetHeaderPhrase("A.Status")); table.AddCell(cell); cell = new PdfPCell(GetHeaderPhrase("Method")); table.AddCell(cell); cell = new PdfPCell(GetHeaderPhrase("Nuclide")); table.AddCell(cell); cell = new PdfPCell(GetHeaderPhrase("Activity")); table.AddCell(cell); cell = new PdfPCell(GetHeaderPhrase("Act.Unc.")); table.AddCell(cell); cell = new PdfPCell(GetHeaderPhrase("Act.Appr.")); table.AddCell(cell); cell = new PdfPCell(GetHeaderPhrase("MDA")); table.AddCell(cell); cell = new PdfPCell(GetHeaderPhrase("MDA Appr.")); table.AddCell(cell); cell = new PdfPCell(GetHeaderPhrase("Reportable")); table.AddCell(cell); cell = new PdfPCell(GetHeaderPhrase("Accredited")); table.AddCell(cell); string query = @" select s.number as 'sample', st.name as 'sample_type_name', sc.name as 'sample_component_name', p.number as 'preparation', pm.name_short as 'preparation_method', p.workflow_status_id as 'preparation_wfstatus', a.number as 'analysis', a.workflow_status_id as 'analysis_wfstatus', am.name_short as 'analysis_method', n.name as 'nuclide_name', ar.activity as 'act', ar.activity_uncertainty_abs as 'act.unc', ar.activity_approved as 'act.appr', ar.detection_limit as 'det.lim', ar.detection_limit_approved as 'det.lim.appr', ar.reportable, ar.accredited from sample s inner join sample_type st on st.id = s.sample_type_id left outer join sample_component sc on sc.id = s.sample_component_id inner join preparation p on p.sample_id = s.id and p.instance_status_id <= 1 inner join preparation_method pm on pm.id = p.preparation_method_id inner join analysis a on a.preparation_id = p.id and a.instance_status_id <= 1 and a.assignment_id = @assignment_id inner join analysis_result ar on ar.analysis_id = a.id inner join analysis_method am on am.id = a.analysis_method_id inner join nuclide n on n.id = ar.nuclide_id order by s.number, p.number, a.number "; int nRows = 1; using (SqlDataReader reader = DB.GetDataReader(conn, trans, query, CommandType.Text, new[] { new SqlParameter("@assignment_id", assignmentId) })) { while (reader.Read()) { int pwfstat = reader.GetInt32("preparation_wfstatus"); string spwfstat = "Unknown"; switch (pwfstat) { case WorkflowStatus.Construction: spwfstat = "Construction"; break; case WorkflowStatus.Complete: spwfstat = "Complete"; break; case WorkflowStatus.Rejected: spwfstat = "Rejected"; break; } int awfstat = reader.GetInt32("analysis_wfstatus"); string sawfstat = "Unknown"; switch (awfstat) { case WorkflowStatus.Construction: sawfstat = "Construction"; break; case WorkflowStatus.Complete: sawfstat = "Complete"; break; case WorkflowStatus.Rejected: sawfstat = "Rejected"; break; } string sact = ""; if (DB.IsValidField(reader["act"])) { sact = reader.GetDouble("act").ToString(Utils.ScientificFormat); } string sactunc = ""; if (DB.IsValidField(reader["act.unc"])) { sactunc = reader.GetDouble("act.unc").ToString(Utils.ScientificFormat); } string sdetlim = ""; if (DB.IsValidField(reader["det.lim"])) { sdetlim = reader.GetDouble("det.lim").ToString(Utils.ScientificFormat); } cell = new PdfPCell(GetCellPhrase(reader.GetString("sample") + "/" + reader.GetString("preparation") + "/" + reader.GetString("analysis"))); table.AddCell(cell); string sampleType = reader.GetString("sample_type_name"); if (DB.IsValidField(reader["sample_component_name"])) { sampleType += " / " + reader.GetString("sample_component_name"); } cell = new PdfPCell(GetCellPhrase(sampleType)); table.AddCell(cell); cell = new PdfPCell(GetCellPhrase(spwfstat)); table.AddCell(cell); cell = new PdfPCell(GetCellPhrase(sawfstat)); table.AddCell(cell); cell = new PdfPCell(GetCellPhrase(reader.GetString("preparation_method") + " / " + reader.GetString("analysis_method"))); table.AddCell(cell); cell = new PdfPCell(GetCellPhrase(reader.GetString("nuclide_name"))); table.AddCell(cell); cell = new PdfPCell(GetCellPhrase(sact)); table.AddCell(cell); cell = new PdfPCell(GetCellPhrase(sactunc)); table.AddCell(cell); cell = new PdfPCell(GetCellPhrase(reader.GetString("act.appr"))); table.AddCell(cell); cell = new PdfPCell(GetCellPhrase(sdetlim)); table.AddCell(cell); cell = new PdfPCell(GetCellPhrase(reader.GetString("det.lim.appr"))); table.AddCell(cell); cell = new PdfPCell(GetCellPhrase(reader.GetString("reportable"))); table.AddCell(cell); cell = new PdfPCell(GetCellPhrase(reader.GetString("accredited"))); table.AddCell(cell); nRows++; } } float currHeight = topCursor; int currRow = 0, pageRows = 0; for (int i = 0; i < nRows; i++) { currHeight -= table.GetRowHeight(i); pageRows++; if (currHeight <= document.GetBottom(10f)) { table.WriteSelectedRows(currRow, currRow + pageRows, document.GetLeft(10), topCursor, cb); document.NewPage(); currRow += pageRows; currHeight = topCursor = document.GetTop(10f); pageRows = 0; } } if (pageRows > 0) { table.WriteSelectedRows(currRow, currRow + pageRows, document.GetLeft(10), topCursor, cb); document.NewPage(); } } finally { document?.Close(); if (ms != null) { pdfData = ms.GetBuffer(); } } return(pdfData); }
private void CreateDocument_STAThread() { #region Prep System.Collections.ArrayList data = objData; //Create new document FixedDocument doc = new FixedDocument(); //Set page size doc.DocumentPaginator.PageSize = new Size(PAPER_SIZE_WIDTH_96, PAPER_SIZE_HEIGHT_96); //Number of records double count = (double)data.Count; #endregion if (count > 0) { #region Declare Variables AveryBarcodeLabel label; //Determine number of pages to generate double pageCount = Math.Ceiling(count / LABELS_PER_SHEET); int dataIndex = 0; int currentColumn = 0; int currentPDFColumn = 0; int currentRow = 0; iTextSharp.text.pdf.PdfPTable objPDFTable = null; #endregion #region Open PDF Document iTextSharp.text.Rectangle rectPaperSize = new iTextSharp.text.Rectangle((float)PAPER_SIZE_WIDTH_72, (float)PAPER_SIZE_HEIGHT_72); iTextSharp.text.Document objPDFDoc = CreatePagePDF(_strFilePathPDF, rectPaperSize, (float)SIDE_MARGIN_72, (float)SIDE_MARGIN_72, (float)(TOP_MARGIN_72), 0); //objPDFDoc. #endregion #region Define PDF Column Widths //Define PDF Column Widths float[] columnWidth = new float[5]; columnWidth[0] = (float)LABEL_WIDTH_72; columnWidth[1] = (float)HORIZONTAL_GAP_72; columnWidth[2] = (float)LABEL_WIDTH_72; columnWidth[3] = (float)HORIZONTAL_GAP_72; columnWidth[4] = (float)LABEL_WIDTH_72; #endregion for (int i = 0; i < pageCount; i++) { #region Prep XPS Page //Create page PageContent page = new PageContent(); FixedPage fixedPage = this.CreatePageXPS(); #endregion //Create labels for (int j = 0; j < 30; j++) { #region Set currentRow if (j % 10 == 0) { currentRow = 0; } else { currentRow++; } #endregion #region Set curentColumn (Vertically) if (j < 10) { currentColumn = 0; } else if (j > 19) { currentColumn = 2; } else { currentColumn = 1; } #endregion #region Set currentPDFColumn (Horizontally) if (j % 3 == 0) { currentPDFColumn = 0; } else if (j%3 == 1) { currentPDFColumn = 1; } else if (j % 3 == 2) { currentPDFColumn = 2; } #endregion if (dataIndex < count) { #region Start a New Page When Necessary if (dataIndex % 30 == 0 || dataIndex == 0) { if (objPDFTable != null) { objPDFDoc.Add(objPDFTable); objPDFDoc.NewPage(); } objPDFTable = new iTextSharp.text.pdf.PdfPTable(5); objPDFTable.SetTotalWidth(columnWidth); objPDFTable.LockedWidth = true; //objPDFTable.SplitLate = false; objPDFTable.SkipLastFooter = true; objPDFTable.KeepTogether = true; //objPDFTable.ExtendLastRow = true; } #endregion #region Get Data and Fill Lines label = new AveryBarcodeLabel(); if (data[dataIndex].GetType() == typeof(AveryBarcodeLabel)) { label = (AveryBarcodeLabel)data[dataIndex]; } else if (data[dataIndex].GetType() == typeof(AveryLabelDataModel)) { label = new AveryBarcodeLabel((AveryLabelDataModel)data[dataIndex]); } else if(data[dataIndex].GetType() == typeof(PostalAddress)) { PostalAddress objAddr = (PostalAddress)data[dataIndex]; label.Line1 = objAddr.Reference; label.Line2 = objAddr.Address1; if (!StringFunctions.IsNullOrWhiteSpace(objAddr.Address2)) label.Line2 += " " + objAddr.Address2; if (!StringFunctions.IsNullOrWhiteSpace(objAddr.Address3)) label.Line2 += " " + objAddr.Address3; label.Line3 = objAddr.ToLocationString() + " " + objAddr.PostalCode; } else if (data[dataIndex].GetType() == typeof(AddressBookEntry)) { AddressBookEntry objAddr = (AddressBookEntry)data[dataIndex]; label.Line1 = objAddr.FullName; label.Line2 = objAddr.Address1; if (!StringFunctions.IsNullOrWhiteSpace(objAddr.Address2)) label.Line2 += " " + objAddr.Address2; if (!StringFunctions.IsNullOrWhiteSpace(objAddr.Address3)) label.Line2 += " " + objAddr.Address3; label.Line3 = objAddr.ToLocationString() + " " + objAddr.PostalCode; label.Email = objAddr.Email; label.Phone = objAddr.Phone; } /* line1 = (string)data.Rows[dataIndex]["Name"]; line2 = (string)data.Rows[dataIndex]["Address"]; postalCode = (string)data.Rows[dataIndex]["PostalCode"]; line3 = (string)data.Rows[dataIndex]["City"] + " " + (string)data.Rows[dataIndex]["State"] + " " + postalCode; */ #endregion #region Draw Label Cell in PDF //Create individual label iTextSharp.text.pdf.PdfPTable tblCell; if ((label.Phone != null && label.Phone.Valid) || (label.Email != null && label.Email.Valid) || (label.Date != null && label.Date != DateTime.MinValue && label.Date != DateTime.MaxValue)) { #region Label With Phone/Email/Date Font objFont = new Font(); objFont.Size = Font.DEFAULTSIZE - 4; tblCell = new iTextSharp.text.pdf.PdfPTable(2); if (label.Date != null && label.Date != DateTime.MinValue && label.Date != DateTime.MaxValue) { iTextSharp.text.pdf.PdfPCell objLine1 = new iTextSharp.text.pdf.PdfPCell(new Phrase(label.Line1, objFont)); objLine1.Border = 0; tblCell.AddCell(objLine1); iTextSharp.text.pdf.PdfPCell objDate = new iTextSharp.text.pdf.PdfPCell(new Phrase("wd: " + label.Date.ToShortDateString(), objFont)); objDate.HorizontalAlignment = 2; //Right objDate.Border = 0; tblCell.AddCell(objDate); } else { iTextSharp.text.pdf.PdfPCell objLine1 = new iTextSharp.text.pdf.PdfPCell(new Phrase(label.Line1, objFont)); objLine1.Border = 0; objLine1.Colspan = 2; tblCell.AddCell(objLine1); } iTextSharp.text.pdf.PdfPCell objLine2 = new iTextSharp.text.pdf.PdfPCell(new Phrase(label.Line2, objFont)); objLine2.Border = 0; objLine2.Colspan = 2; tblCell.AddCell(objLine2); if (label.Phone != null && label.Phone.Valid) { iTextSharp.text.pdf.PdfPCell objLine3 = new iTextSharp.text.pdf.PdfPCell(new Phrase(label.Line3, objFont)); objLine3.Border = 0; objLine3.NoWrap = true; tblCell.AddCell(objLine3); iTextSharp.text.pdf.PdfPCell objPhone = new iTextSharp.text.pdf.PdfPCell(new Phrase(label.Phone.ToString(), objFont)); objPhone.HorizontalAlignment = 2; //Right objPhone.Border = 0; tblCell.AddCell(objPhone); } else { iTextSharp.text.pdf.PdfPCell objLine3 = new iTextSharp.text.pdf.PdfPCell(new Phrase(label.Line3, objFont)); objLine3.Border = 0; objLine3.Colspan = 2; tblCell.AddCell(objLine3); } if (label.Email != null && label.Email.Valid) { iTextSharp.text.pdf.PdfPCell objEmail = new iTextSharp.text.pdf.PdfPCell(new Phrase(label.Email.ToString(), objFont)); objEmail.HorizontalAlignment = 2; //Right objEmail.Border = 0; objEmail.Colspan = 2; tblCell.AddCell(objEmail); } #endregion } else { #region Standard Address Label tblCell = new iTextSharp.text.pdf.PdfPTable(1); Font objNameFont = new Font(); objNameFont.Size = Font.DEFAULTSIZE - 1; iTextSharp.text.pdf.PdfPCell objLine1 = new iTextSharp.text.pdf.PdfPCell(new Phrase(label.Line1, objNameFont)); objLine1.Border = 0; tblCell.AddCell(objLine1); Font objAddrFont = new Font(); objAddrFont.Size = Font.DEFAULTSIZE - 3; iTextSharp.text.pdf.PdfPCell objLine2 = new iTextSharp.text.pdf.PdfPCell(new Phrase(label.Line2, objAddrFont)); objLine2.Border = 0; tblCell.AddCell(objLine2); if (!StringFunctions.IsNullOrWhiteSpace(label.Line3)) { iTextSharp.text.pdf.PdfPCell objLine3 = new iTextSharp.text.pdf.PdfPCell(new Phrase(label.Line3, objAddrFont)); objLine3.Border = 0; tblCell.AddCell(objLine3); } #endregion } iTextSharp.text.pdf.PdfPCell pCell = new iTextSharp.text.pdf.PdfPCell(tblCell); pCell.FixedHeight = (float)(LABEL_HEIGHT_72); pCell.Padding = 5; pCell.Border = 0; objPDFTable.AddCell(pCell); #endregion #region Add Spacer Cell iTextSharp.text.pdf.PdfPCell objGap = new iTextSharp.text.pdf.PdfPCell(); objGap.Border = 0; if (currentPDFColumn == 0) { objPDFTable.AddCell(objGap); } else if (currentPDFColumn == 1) { objPDFTable.AddCell(objGap); } #endregion #region Set XPS Position and Add to Document //Set label location if (currentColumn == 0) { FixedPage.SetLeft(label, SIDE_MARGIN_96); } else if (currentColumn == 1) { FixedPage.SetLeft(label, SIDE_MARGIN_96 + LABEL_WIDTH_96 + HORIZONTAL_GAP_96); } else { FixedPage.SetLeft(label, SIDE_MARGIN_96 + LABEL_WIDTH_96 * 2 + HORIZONTAL_GAP_96 * 2); } FixedPage.SetTop(label, TOP_MARGIN_96 + currentRow * LABEL_HEIGHT_96); //Add label object to page fixedPage.Children.Add(label); #endregion #region Finish Last PDF Row By Adding Blanks if (dataIndex == count - 1) //If I'm on the last cell { if (currentPDFColumn != 3) { while (currentPDFColumn != 3) { currentPDFColumn++; objPDFTable.AddCell(objGap); } } } #endregion dataIndex++; } } #region Finalize XPS Page //Invoke Measure(), Arrange() and UpdateLayout() for drawing fixedPage.Measure(new Size(PAPER_SIZE_WIDTH_96, PAPER_SIZE_HEIGHT_96)); fixedPage.Arrange(new Rect(new Point(), new Size(PAPER_SIZE_WIDTH_96, PAPER_SIZE_HEIGHT_96))); fixedPage.UpdateLayout(); ((IAddChild)page).AddChild(fixedPage); doc.Pages.Add(page); #endregion } #region Finalize PDF Document objPDFDoc.Add(objPDFTable); objPDFDoc.Close(); #endregion } #region Write XPS Document if (!StringFunctions.IsNullOrWhiteSpace(_strFilePathXPS)) { if (File.Exists(_strFilePathXPS)) File.Delete(_strFilePathXPS); XpsDocument xpsd = new XpsDocument(_strFilePathXPS, FileAccess.ReadWrite); System.Windows.Xps.XpsDocumentWriter xw = XpsDocument.CreateXpsDocumentWriter(xpsd); xw.Write(doc); xpsd.Close(); } #endregion }
public void GeneratePDF() { string path = String.Format(@"{0}\routereport.pdf", Environment.CurrentDirectory); try { var pdfDoc = new Document(PageSize.LETTER, 40f, 40f, 60f, 60f); iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDoc, new FileStream(path, FileMode.OpenOrCreate)); pdfDoc.Open(); var spacer = new Paragraph("") { SpacingBefore = 10f, SpacingAfter = 10f, }; pdfDoc.Add(spacer); var headerTable = new iTextSharp.text.pdf.PdfPTable(new[] { .75f, 2f }) { HorizontalAlignment = 1, WidthPercentage = 75, DefaultCell = { MinimumHeight = 22f } }; headerTable.AddCell("Data"); headerTable.AddCell(route.CreationDateTime.ToString()); headerTable.AddCell("Nazwisko"); headerTable.AddCell(route.Employee.Name + " " + route.Employee.Surname.ToString()); headerTable.AddCell("Pojazd"); headerTable.AddCell(route.Vehicle.Model.ToString() + " " + route.Vehicle.Registration.ToString()); pdfDoc.Add(headerTable); pdfDoc.Add(spacer); var columnCount = 2; var columnWidths = new[] { 0.75f, 3f }; var table = new iTextSharp.text.pdf.PdfPTable(columnWidths) { HorizontalAlignment = 1, WidthPercentage = 80, DefaultCell = { MinimumHeight = 22f }, }; var cell = new iTextSharp.text.pdf.PdfPCell(new Phrase("Podsumowanie")) { Colspan = columnCount, HorizontalAlignment = 1, MinimumHeight = 15f, }; table.AddCell(cell); foreach (var point in route.RoutePoints) { Address addr = point.Parcel.ReceiverData.PersonalAddress; string addressText = string.Format("{0} {1}/{2}, {3}, {4}", addr.Street, addr.HomeNumber, addr.ApartmentNumber, addr.PostCode, addr.City); table.AddCell(point.ParcelId.ToString()); table.AddCell(addressText); } pdfDoc.Add(table); pdfDoc.Close(); } catch (iTextSharp.text.DocumentException dex) { Console.WriteLine(dex.Message); } new Process { StartInfo = new ProcessStartInfo(path) { UseShellExecute = true } }.Start(); }
///******************************************************************************************************* /// <summary> /// Método que exporta la tabla de resultados en el grid a PDF /// </summary> /// <param name="Documento">Objeto al cúal agregaremos el contenido del reporte</param> /// <creo>Juan Alberto Hernández Negrete</creo> /// <fecha_creo>27-nov-2013</fecha_creo> /// <modifico></modifico> /// <fecha_modifico></fecha_modifico> /// <causa_modificacion></causa_modificacion> ///******************************************************************************************************* public void Exportar_Datos_PDF(iTextSharp.text.Document Documento) { bool Es_Footer = false; try { iTextSharp.text.Phrase _frase = null; iTextSharp.text.pdf.PdfPCell _celda = null; iTextSharp.text.FontFactory.RegisterDirectory(@"C:\Windows\Fonts"); //Creamos el objeto de tipo tabla para almacenar el resultado de la búsqueda. iTextSharp.text.pdf.PdfPTable Rpt_Tabla = new iTextSharp.text.pdf.PdfPTable(Grd_Resultado.Columns.Count); //Obtenemos y establecemos el formato de las columnas de la tabla. float[] Ancho_Cabeceras = Obtener_Tamano_Columnas(Grd_Resultado); //Creamos y definimos algunas propiedades que tendrá la fuente que se aplicara a las celdas de la tabla de resultados. iTextSharp.text.Font Fuente_Tabla_Contenido = iTextSharp.text.FontFactory.GetFont("Courier New", 7, iTextSharp.text.Font.NORMAL); iTextSharp.text.Font Fuente_Tabla_Footer = iTextSharp.text.FontFactory.GetFont("Courier New", 9, iTextSharp.text.Font.BOLD); //Establecemos el formato que tendrá la tabla que mostrara el resultado de la búsqueda según el movimiento consultado. Rpt_Tabla.DefaultCell.Padding = 3; Rpt_Tabla.SetWidths(Ancho_Cabeceras); Rpt_Tabla.WidthPercentage = 100; Rpt_Tabla.DefaultCell.BorderWidth = 2; Rpt_Tabla.DefaultCell.HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER; Rpt_Tabla.HeaderRows = 1; // Creamos y establecemos el formato que tendrá el titulo del reporte. iTextSharp.text.Paragraph Titulo = new iTextSharp.text.Paragraph(); Titulo.Alignment = iTextSharp.text.Element.ALIGN_CENTER; Titulo.Font = iTextSharp.text.FontFactory.GetFont("Consolas"); Titulo.Font.SetStyle(iTextSharp.text.Font.BOLD); Titulo.Font.Size = 14; Titulo.Add("Museo de las Momias de Guanajuato"); // Creamos y establecemos el formato que tendrá el subtitulo del reporte. iTextSharp.text.Paragraph Subtitulo = new iTextSharp.text.Paragraph(); Subtitulo.Alignment = iTextSharp.text.Element.ALIGN_CENTER; Subtitulo.Font = iTextSharp.text.FontFactory.GetFont("Consolas"); Subtitulo.Font.SetStyle(iTextSharp.text.Font.BOLD); Subtitulo.Font.Size = 12; Subtitulo.Add("Log de eventos en " + Cmb_Tabla.Text.ToString() + ": " + (Dtp_Fecha_Inicio.Checked.Equals(true) ? Dtp_Fecha_Inicio.Text : "") + " - " + (Dtp_Fecha_Termino.Checked.Equals(true) ? Dtp_Fecha_Termino.Text : "")); // rango de fechas del reporte // fecha actual iTextSharp.text.Phrase Fecha = new iTextSharp.text.Phrase(DateTime.Today.ToString("dd-MMM-yyyy")); Fecha.Font.Size = 11; float[] Anchura_Tabla_Subtitulo = { 90, 10 }; // subtitulo con fecha en una tabla sin bordes (misma línea) iTextSharp.text.pdf.PdfPTable Tabla_Subtitulo = new iTextSharp.text.pdf.PdfPTable(Anchura_Tabla_Subtitulo); Tabla_Subtitulo.WidthPercentage = 100; Tabla_Subtitulo.DefaultCell.Border = iTextSharp.text.pdf.PdfPCell.NO_BORDER; Tabla_Subtitulo.DefaultCell.VerticalAlignment = iTextSharp.text.Element.ALIGN_RIGHT; Tabla_Subtitulo.DefaultCell.HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT; Tabla_Subtitulo.AddCell(Subtitulo); Tabla_Subtitulo.DefaultCell.HorizontalAlignment = iTextSharp.text.Element.ALIGN_RIGHT; Tabla_Subtitulo.AddCell(Fecha); //Agregamos los nombres de las columnas de la tabla que se imprimira en el reporte. Array.ForEach(Grd_Resultado.Columns.OfType <DataGridViewColumn>().ToArray(), columna => { var cabecera = new iTextSharp.text.pdf.PdfPCell(new iTextSharp.text.Phrase(columna.HeaderText, iTextSharp.text.FontFactory.GetFont("Consolas", 8, iTextSharp.text.Font.BOLD))); cabecera.BackgroundColor = iTextSharp.text.BaseColor.LIGHT_GRAY; cabecera.HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER; Rpt_Tabla.AddCell(cabecera); }); //Modificamos el tipo de border que tendrá las celdas que mostraran los datos, con respécto al borde que tiene asignado la cabeceras de las columnas. Rpt_Tabla.DefaultCell.BorderWidth = 1; //Agreamos el resultado de la búsqueda de movimientos al tabla que se enviara al reporte. Array.ForEach(Grd_Resultado.Rows.OfType <DataGridViewRow>().ToArray(), fila => { if (fila.Cells[0] != null) { if (fila.Cells[0].Value != null) { if (fila.Cells[0].Value.ToString().ToLower().Contains("totales")) { Es_Footer = true; } else { Es_Footer = false; } } else { Es_Footer = false; } } else { Es_Footer = false; } Array.ForEach(fila.Cells.OfType <DataGridViewCell>().ToArray(), celda => { string texto = string.Empty; if (celda.Value != null) { if (celda.ValueType.Name.Equals("DateTime")) { texto = string.Format("{0:dd MMM yyyy}", celda.Value); } else if (celda.ValueType.Name.Equals("Decimal") && !celda.OwningColumn.HeaderText.Equals("NoCaja")) { texto = string.Format("{0:n}", celda.Value); } else { texto = celda.Value.ToString(); } } if (Es_Footer) { //Establecemos el formato que llevaran las celdas de totales de la tabla del reporte. _frase = new iTextSharp.text.Phrase(texto, Fuente_Tabla_Footer); _celda = new iTextSharp.text.pdf.PdfPCell(_frase); _celda.BackgroundColor = iTextSharp.text.BaseColor.LIGHT_GRAY; } else { //Establecemos el formato que llevaran las celdas de contenido de la tabla del reporte. _frase = new iTextSharp.text.Phrase(texto, Fuente_Tabla_Contenido); _celda = new iTextSharp.text.pdf.PdfPCell(_frase); } if (texto.Contains("$")) { _celda.HorizontalAlignment = iTextSharp.text.Element.ALIGN_RIGHT; } else { _celda.HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER; } _celda.VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE; //Establecemos el valor de la celda. Rpt_Tabla.AddCell(_celda); }); //Indicamos que se completo de editar la fila y completamos la operación. Rpt_Tabla.CompleteRow(); }); // Se agrega el PDFTable al documento. Documento.Add(Titulo); Documento.Add(Tabla_Subtitulo); Documento.Add(new iTextSharp.text.Paragraph("\n")); Documento.Add(Rpt_Tabla); } catch (Exception Ex) { MessageBox.Show(this, Ex.Message, "Error - Método: [Exportar_Datos_PDF]", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
private void CreateDocument_STAThread() { #region Prep System.Collections.ArrayList data = objData; //Create new document FixedDocument doc = new FixedDocument(); //Set page size doc.DocumentPaginator.PageSize = new Size(PAPER_SIZE_WIDTH_96, PAPER_SIZE_HEIGHT_96); //Number of records double count = (double)data.Count; #endregion if (count > 0) { #region Declare Variables AveryBarcodeLabel label; //Determine number of pages to generate double pageCount = Math.Ceiling(count / LABELS_PER_SHEET); int dataIndex = 0; int currentColumn = 0; int currentPDFColumn = 0; int currentRow = 0; iTextSharp.text.pdf.PdfPTable objPDFTable = null; #endregion #region Open PDF Document iTextSharp.text.Rectangle rectPaperSize = new iTextSharp.text.Rectangle((float)PAPER_SIZE_WIDTH_72, (float)PAPER_SIZE_HEIGHT_72); iTextSharp.text.Document objPDFDoc = CreatePagePDF(_strFilePathPDF, rectPaperSize, (float)SIDE_MARGIN_72, (float)SIDE_MARGIN_72, (float)(TOP_MARGIN_72), 0); //objPDFDoc. #endregion #region Define PDF Column Widths //Define PDF Column Widths float[] columnWidth = new float[5]; columnWidth[0] = (float)LABEL_WIDTH_72; columnWidth[1] = (float)HORIZONTAL_GAP_72; columnWidth[2] = (float)LABEL_WIDTH_72; columnWidth[3] = (float)HORIZONTAL_GAP_72; columnWidth[4] = (float)LABEL_WIDTH_72; #endregion for (int i = 0; i < pageCount; i++) { #region Prep XPS Page //Create page PageContent page = new PageContent(); FixedPage fixedPage = this.CreatePageXPS(); #endregion //Create labels for (int j = 0; j < 30; j++) { #region Set currentRow if (j % 10 == 0) { currentRow = 0; } else { currentRow++; } #endregion #region Set curentColumn (Vertically) if (j < 10) { currentColumn = 0; } else if (j > 19) { currentColumn = 2; } else { currentColumn = 1; } #endregion #region Set currentPDFColumn (Horizontally) if (j % 3 == 0) { currentPDFColumn = 0; } else if (j % 3 == 1) { currentPDFColumn = 1; } else if (j % 3 == 2) { currentPDFColumn = 2; } #endregion if (dataIndex < count) { #region Start a New Page When Necessary if (dataIndex % 30 == 0 || dataIndex == 0) { if (objPDFTable != null) { objPDFDoc.Add(objPDFTable); objPDFDoc.NewPage(); } objPDFTable = new iTextSharp.text.pdf.PdfPTable(5); objPDFTable.SetTotalWidth(columnWidth); objPDFTable.LockedWidth = true; //objPDFTable.SplitLate = false; objPDFTable.SkipLastFooter = true; objPDFTable.KeepTogether = true; //objPDFTable.ExtendLastRow = true; } #endregion #region Get Data and Fill Lines label = new AveryBarcodeLabel(); if (data[dataIndex].GetType() == typeof(AveryBarcodeLabel)) { label = (AveryBarcodeLabel)data[dataIndex]; } else if (data[dataIndex].GetType() == typeof(AveryLabelDataModel)) { label = new AveryBarcodeLabel((AveryLabelDataModel)data[dataIndex]); } else if (data[dataIndex].GetType() == typeof(PostalAddress)) { PostalAddress objAddr = (PostalAddress)data[dataIndex]; label.Line1 = objAddr.Reference; label.Line2 = objAddr.Address1; if (!StringFunctions.IsNullOrWhiteSpace(objAddr.Address2)) { label.Line2 += " " + objAddr.Address2; } if (!StringFunctions.IsNullOrWhiteSpace(objAddr.Address3)) { label.Line2 += " " + objAddr.Address3; } label.Line3 = objAddr.ToLocationString() + " " + objAddr.PostalCode; } else if (data[dataIndex].GetType() == typeof(AddressBookEntry)) { AddressBookEntry objAddr = (AddressBookEntry)data[dataIndex]; label.Line1 = objAddr.FullName; label.Line2 = objAddr.Address1; if (!StringFunctions.IsNullOrWhiteSpace(objAddr.Address2)) { label.Line2 += " " + objAddr.Address2; } if (!StringFunctions.IsNullOrWhiteSpace(objAddr.Address3)) { label.Line2 += " " + objAddr.Address3; } label.Line3 = objAddr.ToLocationString() + " " + objAddr.PostalCode; label.Email = objAddr.Email; label.Phone = objAddr.Phone; } /* * line1 = (string)data.Rows[dataIndex]["Name"]; * line2 = (string)data.Rows[dataIndex]["Address"]; * postalCode = (string)data.Rows[dataIndex]["PostalCode"]; * line3 = (string)data.Rows[dataIndex]["City"] + " " + (string)data.Rows[dataIndex]["State"] + " " + postalCode; */ #endregion #region Draw Label Cell in PDF //Create individual label iTextSharp.text.pdf.PdfPTable tblCell; if ((label.Phone != null && label.Phone.Valid) || (label.Email != null && label.Email.Valid) || (label.Date != null && label.Date != DateTime.MinValue && label.Date != DateTime.MaxValue)) { #region Label With Phone/Email/Date Font objFont = new Font(); objFont.Size = Font.DEFAULTSIZE - 4; tblCell = new iTextSharp.text.pdf.PdfPTable(2); if (label.Date != null && label.Date != DateTime.MinValue && label.Date != DateTime.MaxValue) { iTextSharp.text.pdf.PdfPCell objLine1 = new iTextSharp.text.pdf.PdfPCell(new Phrase(label.Line1, objFont)); objLine1.Border = 0; tblCell.AddCell(objLine1); iTextSharp.text.pdf.PdfPCell objDate = new iTextSharp.text.pdf.PdfPCell(new Phrase("wd: " + label.Date.ToShortDateString(), objFont)); objDate.HorizontalAlignment = 2; //Right objDate.Border = 0; tblCell.AddCell(objDate); } else { iTextSharp.text.pdf.PdfPCell objLine1 = new iTextSharp.text.pdf.PdfPCell(new Phrase(label.Line1, objFont)); objLine1.Border = 0; objLine1.Colspan = 2; tblCell.AddCell(objLine1); } iTextSharp.text.pdf.PdfPCell objLine2 = new iTextSharp.text.pdf.PdfPCell(new Phrase(label.Line2, objFont)); objLine2.Border = 0; objLine2.Colspan = 2; tblCell.AddCell(objLine2); if (label.Phone != null && label.Phone.Valid) { iTextSharp.text.pdf.PdfPCell objLine3 = new iTextSharp.text.pdf.PdfPCell(new Phrase(label.Line3, objFont)); objLine3.Border = 0; objLine3.NoWrap = true; tblCell.AddCell(objLine3); iTextSharp.text.pdf.PdfPCell objPhone = new iTextSharp.text.pdf.PdfPCell(new Phrase(label.Phone.ToString(), objFont)); objPhone.HorizontalAlignment = 2; //Right objPhone.Border = 0; tblCell.AddCell(objPhone); } else { iTextSharp.text.pdf.PdfPCell objLine3 = new iTextSharp.text.pdf.PdfPCell(new Phrase(label.Line3, objFont)); objLine3.Border = 0; objLine3.Colspan = 2; tblCell.AddCell(objLine3); } if (label.Email != null && label.Email.Valid) { iTextSharp.text.pdf.PdfPCell objEmail = new iTextSharp.text.pdf.PdfPCell(new Phrase(label.Email.ToString(), objFont)); objEmail.HorizontalAlignment = 2; //Right objEmail.Border = 0; objEmail.Colspan = 2; tblCell.AddCell(objEmail); } #endregion } else { #region Standard Address Label tblCell = new iTextSharp.text.pdf.PdfPTable(1); Font objNameFont = new Font(); objNameFont.Size = Font.DEFAULTSIZE - 1; iTextSharp.text.pdf.PdfPCell objLine1 = new iTextSharp.text.pdf.PdfPCell(new Phrase(label.Line1, objNameFont)); objLine1.Border = 0; tblCell.AddCell(objLine1); Font objAddrFont = new Font(); objAddrFont.Size = Font.DEFAULTSIZE - 3; iTextSharp.text.pdf.PdfPCell objLine2 = new iTextSharp.text.pdf.PdfPCell(new Phrase(label.Line2, objAddrFont)); objLine2.Border = 0; tblCell.AddCell(objLine2); if (!StringFunctions.IsNullOrWhiteSpace(label.Line3)) { iTextSharp.text.pdf.PdfPCell objLine3 = new iTextSharp.text.pdf.PdfPCell(new Phrase(label.Line3, objAddrFont)); objLine3.Border = 0; tblCell.AddCell(objLine3); } #endregion } iTextSharp.text.pdf.PdfPCell pCell = new iTextSharp.text.pdf.PdfPCell(tblCell); pCell.FixedHeight = (float)(LABEL_HEIGHT_72); pCell.Padding = 5; pCell.Border = 0; objPDFTable.AddCell(pCell); #endregion #region Add Spacer Cell iTextSharp.text.pdf.PdfPCell objGap = new iTextSharp.text.pdf.PdfPCell(); objGap.Border = 0; if (currentPDFColumn == 0) { objPDFTable.AddCell(objGap); } else if (currentPDFColumn == 1) { objPDFTable.AddCell(objGap); } #endregion #region Set XPS Position and Add to Document //Set label location if (currentColumn == 0) { FixedPage.SetLeft(label, SIDE_MARGIN_96); } else if (currentColumn == 1) { FixedPage.SetLeft(label, SIDE_MARGIN_96 + LABEL_WIDTH_96 + HORIZONTAL_GAP_96); } else { FixedPage.SetLeft(label, SIDE_MARGIN_96 + LABEL_WIDTH_96 * 2 + HORIZONTAL_GAP_96 * 2); } FixedPage.SetTop(label, TOP_MARGIN_96 + currentRow * LABEL_HEIGHT_96); //Add label object to page fixedPage.Children.Add(label); #endregion #region Finish Last PDF Row By Adding Blanks if (dataIndex == count - 1) //If I'm on the last cell { if (currentPDFColumn != 3) { while (currentPDFColumn != 3) { currentPDFColumn++; objPDFTable.AddCell(objGap); } } } #endregion dataIndex++; } } #region Finalize XPS Page //Invoke Measure(), Arrange() and UpdateLayout() for drawing fixedPage.Measure(new Size(PAPER_SIZE_WIDTH_96, PAPER_SIZE_HEIGHT_96)); fixedPage.Arrange(new Rect(new Point(), new Size(PAPER_SIZE_WIDTH_96, PAPER_SIZE_HEIGHT_96))); fixedPage.UpdateLayout(); ((IAddChild)page).AddChild(fixedPage); doc.Pages.Add(page); #endregion } #region Finalize PDF Document objPDFDoc.Add(objPDFTable); objPDFDoc.Close(); #endregion } #region Write XPS Document if (!StringFunctions.IsNullOrWhiteSpace(_strFilePathXPS)) { if (File.Exists(_strFilePathXPS)) { File.Delete(_strFilePathXPS); } XpsDocument xpsd = new XpsDocument(_strFilePathXPS, FileAccess.ReadWrite); System.Windows.Xps.XpsDocumentWriter xw = XpsDocument.CreateXpsDocumentWriter(xpsd); xw.Write(doc); xpsd.Close(); } #endregion }
//------------FACTURA------------------------------- public static void CrearFactura(string PATH, string Archivo) { var Datos = LeerCFDI(PATH + Archivo + ".xml"); Font font = new Font(Font.FontFamily.HELVETICA, 6, Font.NORMAL); Font sellos = new Font(Font.FontFamily.HELVETICA, 5, Font.NORMAL); Font textBold = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 7); iTextSharp.text.Document doc = new iTextSharp.text.Document(iTextSharp.text.PageSize.LETTER); iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(doc, new FileStream(PATH + Archivo + ".pdf", FileMode.Create)); doc.AddTitle("Factura Electronica"); doc.AddCreator("Avenzo Proteccion"); doc.AddAuthor("Cristian Santiago Rosas"); doc.Open(); iTextSharp.text.Image avenzo = iTextSharp.text.Image.GetInstance("~/Images/Avenzo_Logo_Header.png"); iTextSharp.text.pdf.PdfPTable Header = new iTextSharp.text.pdf.PdfPTable(12); float[] widths = new float[] { .8f, .8f, .8f, .8f, .8f, .8f, .8f, .8f, .8f, .8f, .8f, .8f }; iTextSharp.text.Rectangle page = doc.PageSize; Header.WidthPercentage = 80; Header.LockedWidth = true; Header.SetWidths(widths); Header.TotalWidth = page.Width - 90; //--------------------------------------------- //-----------CABEZERA DEL DOCUMENTO------------ //--------------------------------------------- iTextSharp.text.pdf.PdfPCell cell = new iTextSharp.text.pdf.PdfPCell();//--Logo cell.AddElement(avenzo); cell.Colspan = 4; cell.Border = BORDER; iTextSharp.text.pdf.PdfPCell cell2 = new iTextSharp.text.pdf.PdfPCell();//--Domicilio Fiscal cell2.AddElement(new iTextSharp.text.Paragraph(Datos["EmisorNombre"] + "\n" + Datos["EmisorRFC"] + "\nDomicilio Fiscal\n" + Datos["DomicilioFiscal"] + "\nTel. 6645266573", new Font(Font.FontFamily.HELVETICA, 5, Font.BOLD))); cell2.Colspan = 4; cell2.Border = BORDER; cell2.HorizontalAlignment = 1; Header.AddCell(cell); Header.AddCell(cell2); iTextSharp.text.pdf.PdfPCell cell51 = new iTextSharp.text.pdf.PdfPCell(); cell51.Phrase = new Phrase("Factura No: " + Datos["folio"] + "\nFOLIO FISCAL (UUID):\n" + Datos["UUID"] + "\nNO. DE SERIE DEL CERTIFICADO DEL SAT:\n" + Datos["noCertificadoSAT"] + "\nNO. DE SERIE DEL CERTIFICADO DEL EMISOR:\n" + Datos["noCertificado"] + "\nFECHA Y HORA DE CERTIFICACIÓN:\n" + Datos["FechaTimbrado"] + "\nFECHA Y HORA DE EMISIÓN DE CFDI:\n" + Datos["FechaComprobante"], textBold); cell51.HorizontalAlignment = Element.ALIGN_CENTER; cell51.Colspan = 4; Header.AddCell(cell51); iTextSharp.text.pdf.PdfPCell salto = new iTextSharp.text.pdf.PdfPCell(); salto.AddElement(new Chunk("\n")); salto.Colspan = 12; salto.Border = BORDER; Header.AddCell(salto); //--------------------------------------------- //------------DATOS CLIENTE------------------- //--------------------------------------------- iTextSharp.text.pdf.PdfPCell cell4 = new iTextSharp.text.pdf.PdfPCell();//--Domicilio Fiscal cell4.Colspan = 1; cell4.Border = BORDER; cell4.PaddingTop = 0; cell4.PaddingBottom = 0; cell4.AddElement(new Paragraph("Cliente:", textBold)); iTextSharp.text.pdf.PdfPCell cell5 = new iTextSharp.text.pdf.PdfPCell();//--Domicilio Fiscal cell5.Colspan = 2; cell5.PaddingTop = 0; cell5.PaddingBottom = 0; cell5.Border = BORDER; cell5.AddElement(new Paragraph(Datos["ReceptorNombre"], font)); iTextSharp.text.pdf.PdfPCell cell6 = new iTextSharp.text.pdf.PdfPCell();//--Domicilio Fiscal cell6.Colspan = 2; cell6.Border = BORDER; cell6.PaddingTop = 0; cell6.PaddingBottom = 0; cell6.AddElement(new Paragraph("Régimen Fiscal:", textBold)); iTextSharp.text.pdf.PdfPCell cell7 = new iTextSharp.text.pdf.PdfPCell();//--Domicilio Fiscal cell7.Colspan = 7; cell7.Border = BORDER; cell7.PaddingTop = 0; cell7.PaddingBottom = 0; cell7.AddElement(new Paragraph(Datos["Regimen"], font)); iTextSharp.text.pdf.PdfPCell cell8 = new iTextSharp.text.pdf.PdfPCell();//--Domicilio Fiscal cell8.Colspan = 1; cell8.Border = BORDER; cell8.PaddingTop = 0; cell8.PaddingBottom = 0; cell8.AddElement(new Paragraph("RFC:", textBold)); iTextSharp.text.pdf.PdfPCell cell9 = new iTextSharp.text.pdf.PdfPCell();//--Domicilio Fiscal cell9.Colspan = 2; cell9.Border = BORDER; cell9.PaddingTop = 0; cell9.PaddingBottom = 0; cell9.AddElement(new Paragraph(Datos["ReceptorRFC"], font)); iTextSharp.text.pdf.PdfPCell cell10 = new iTextSharp.text.pdf.PdfPCell(); cell10.Colspan = 2; cell10.Border = BORDER; cell10.PaddingBottom = 0; cell10.PaddingTop = 0; cell10.AddElement(new Paragraph("Lugar de Expedición:", textBold)); iTextSharp.text.pdf.PdfPCell cell11 = new iTextSharp.text.pdf.PdfPCell(); cell11.Colspan = 3; cell11.Border = BORDER; cell11.PaddingTop = 0; cell11.PaddingBottom = 0; cell11.AddElement(new Paragraph(Datos["LugarExpedicion"], font)); iTextSharp.text.pdf.PdfPCell cell12 = new iTextSharp.text.pdf.PdfPCell(); cell12.AddElement(new Paragraph("Fecha de Expedicion:", textBold)); cell12.Colspan = 2; cell12.Border = BORDER; cell12.PaddingBottom = 0; cell12.PaddingTop = 0; iTextSharp.text.pdf.PdfPCell cell13 = new iTextSharp.text.pdf.PdfPCell(); cell13.Colspan = 3; cell13.Border = BORDER; cell13.PaddingTop = 0; cell13.PaddingBottom = 0; DateTime time = DateTime.Parse(Datos["FechaComprobante"]); System.Globalization.CultureInfo ci = new System.Globalization.CultureInfo("es-MX"); cell13.AddElement(new Paragraph(time.ToString("dd", ci) + " de " + time.ToString("MMMM", ci) + " del " + time.ToString("yyyy", ci), font)); //--- iTextSharp.text.pdf.PdfPCell cell14 = new iTextSharp.text.pdf.PdfPCell(); cell14.Colspan = 1; cell14.Rowspan = 2; cell14.PaddingTop = 0; cell14.PaddingBottom = 0; cell14.Border = BORDER; cell14.AddElement(new Paragraph("Direccion:", textBold)); iTextSharp.text.pdf.PdfPCell cell15 = new iTextSharp.text.pdf.PdfPCell(); cell15.Colspan = 2; cell15.Rowspan = 2; cell15.Border = BORDER; cell15.PaddingBottom = 0; cell15.PaddingTop = 0; cell15.AddElement(new Paragraph(Datos["ReceptorDomicilio"], font)); iTextSharp.text.pdf.PdfPCell cell16 = new iTextSharp.text.pdf.PdfPCell(); cell16.Colspan = 2; cell16.PaddingTop = 0; cell16.PaddingBottom = 0; cell16.AddElement(new Paragraph("Forma De Pago:", textBold)); cell16.Border = BORDER; iTextSharp.text.pdf.PdfPCell cell17 = new iTextSharp.text.pdf.PdfPCell(); cell17.PaddingBottom = 0; cell17.PaddingTop = 0; cell17.Colspan = 3; cell17.Border = BORDER; cell17.AddElement(new Paragraph(Datos["formaDePago"], font)); iTextSharp.text.pdf.PdfPCell cell18 = new iTextSharp.text.pdf.PdfPCell(); cell18.AddElement(new Paragraph("Clave Moneda:", textBold)); cell18.Colspan = 2; cell18.Border = BORDER; cell18.PaddingTop = 0; cell18.PaddingBottom = 0; iTextSharp.text.pdf.PdfPCell cell19 = new iTextSharp.text.pdf.PdfPCell(); cell19.Colspan = 2; cell19.Border = BORDER; cell19.PaddingBottom = 0; cell19.PaddingTop = 0; cell19.AddElement(new Paragraph(Datos["Moneda"], font)); iTextSharp.text.pdf.PdfPCell cell20 = new iTextSharp.text.pdf.PdfPCell(); cell20.Colspan = 2; cell20.Border = BORDER; cell20.PaddingTop = 0; cell20.PaddingBottom = 0; cell20.AddElement(new Paragraph("Método de Pago:", textBold)); iTextSharp.text.pdf.PdfPCell cell21 = new iTextSharp.text.pdf.PdfPCell(); cell21.Colspan = 3; cell21.Border = BORDER; cell21.PaddingTop = 0; cell21.PaddingBottom = 0; cell21.AddElement(new Paragraph(Datos["metodoDePago"], font)); iTextSharp.text.pdf.PdfPCell cell22 = new iTextSharp.text.pdf.PdfPCell(); cell22.Colspan = 2; cell22.Border = BORDER; cell22.PaddingTop = 0; cell22.PaddingBottom = 0; cell22.AddElement(new Paragraph("NumCtaPago:", textBold)); iTextSharp.text.pdf.PdfPCell cell23 = new iTextSharp.text.pdf.PdfPCell(); cell23.Colspan = 2; cell23.Border = BORDER; cell23.PaddingTop = 0; cell23.PaddingBottom = 0; cell23.AddElement(new Paragraph(Datos["NumCtaPago"], font)); //---------------------------------------------- //-----------------PRODUCTOS-------------------- //---------------------------------------------- iTextSharp.text.pdf.PdfPCell cell24 = new iTextSharp.text.pdf.PdfPCell(); cell24.Colspan = 1; cell24.AddElement(new Paragraph("Cantidad", textBold)); iTextSharp.text.pdf.PdfPCell cell25 = new iTextSharp.text.pdf.PdfPCell(); cell25.Colspan = 1; cell25.AddElement(new Paragraph("Unidad de Medida", textBold)); iTextSharp.text.pdf.PdfPCell cell26 = new iTextSharp.text.pdf.PdfPCell(); cell26.Colspan = 6; cell26.HorizontalAlignment = Element.ALIGN_CENTER; cell26.VerticalAlignment = Element.ALIGN_CENTER; cell26.AddElement(new Paragraph("Descripcion", textBold)); iTextSharp.text.pdf.PdfPCell cell27 = new iTextSharp.text.pdf.PdfPCell(); cell27.Colspan = 2; cell27.AddElement(new Paragraph("Producto Unitario", textBold)); iTextSharp.text.pdf.PdfPCell cell28 = new iTextSharp.text.pdf.PdfPCell(); cell28.Colspan = 2; cell28.HorizontalAlignment = Element.ALIGN_CENTER; cell28.VerticalAlignment = Element.ALIGN_CENTER; cell28.AddElement(new Paragraph("Importe", textBold)); //----------------------------------------------- iTextSharp.text.pdf.PdfPCell cell29 = new iTextSharp.text.pdf.PdfPCell(); cell29.AddElement(new Paragraph(Datos["cantidad"], font)); cell29.Colspan = 1; iTextSharp.text.pdf.PdfPCell cell30 = new iTextSharp.text.pdf.PdfPCell(); cell30.AddElement(new Paragraph(Datos["unidad"], font)); cell30.Colspan = 1; iTextSharp.text.pdf.PdfPCell cell31 = new iTextSharp.text.pdf.PdfPCell(); cell31.AddElement(new Paragraph(Datos["descripcion"], font)); cell31.Colspan = 6; iTextSharp.text.pdf.PdfPCell cell32 = new iTextSharp.text.pdf.PdfPCell(); cell32.AddElement(new Paragraph(Datos["valorUnitario"], font)); cell32.Colspan = 2; iTextSharp.text.pdf.PdfPCell cell33 = new iTextSharp.text.pdf.PdfPCell(); cell33.AddElement(new Paragraph(Datos["importe"], font)); cell33.Colspan = 2; cell33.FixedHeight = 200f; //------------------------------------------------------- //----------------------TOTAL---------------------------- //------------------------------------------------------- iTextSharp.text.pdf.PdfPCell cell34 = new iTextSharp.text.pdf.PdfPCell(); cell34.Colspan = 2; cell34.Rowspan = 3; cell34.Border = BORDER; cell34.PaddingBottom = 0; cell34.PaddingTop = 0; cell34.AddElement(new Paragraph("")); iTextSharp.text.pdf.PdfPCell cell35 = new iTextSharp.text.pdf.PdfPCell(); cell35.Colspan = 7; cell35.Border = BORDER; cell35.Rowspan = 3; cell35.PaddingTop = 0; cell35.PaddingBottom = 0; NumLetra nl = new NumLetra(); cell35.AddElement(new Paragraph("IMPORTE CON LETRA: " + nl.Convertir(Datos["total"], true, false), textBold)); iTextSharp.text.pdf.PdfPCell cell36 = new iTextSharp.text.pdf.PdfPCell(); cell36.Colspan = 2; cell36.Border = BORDER; cell36.PaddingBottom = 0; cell36.PaddingTop = 0; cell36.Phrase = new Phrase("SubTotal:", textBold); cell36.HorizontalAlignment = Element.ALIGN_RIGHT; cell36.VerticalAlignment = Element.ALIGN_BOTTOM; iTextSharp.text.pdf.PdfPCell cell37 = new iTextSharp.text.pdf.PdfPCell(); cell37.Colspan = 1; cell37.Border = BORDER; cell37.PaddingTop = 0; cell37.PaddingBottom = 0; cell37.AddElement(new Paragraph("$ " + Datos["subTotal"], font)); //-- iTextSharp.text.pdf.PdfPCell cell38 = new iTextSharp.text.pdf.PdfPCell(); cell38.Colspan = 2; cell38.PaddingBottom = 0; cell38.PaddingTop = 0; cell38.Border = BORDER; cell38.Phrase = new Phrase("IVA(IVA 16.00%):", textBold); cell38.HorizontalAlignment = Element.ALIGN_RIGHT; cell38.VerticalAlignment = Element.ALIGN_BOTTOM; iTextSharp.text.pdf.PdfPCell cell39 = new iTextSharp.text.pdf.PdfPCell(); cell39.Colspan = 1; cell39.PaddingTop = 0; cell39.PaddingBottom = 0; cell39.Border = BORDER; cell39.AddElement(new Paragraph("$ " + Datos["totalImpuestosTrasladados"], font)); //--- iTextSharp.text.pdf.PdfPCell cell40 = new iTextSharp.text.pdf.PdfPCell(); cell40.Colspan = 2; cell40.Border = BORDER; cell40.VerticalAlignment = Element.ALIGN_BOTTOM; cell40.Phrase = new Phrase("Total:", textBold); cell40.PaddingBottom = 0; cell40.PaddingTop = 0; cell40.HorizontalAlignment = Element.ALIGN_RIGHT; iTextSharp.text.pdf.PdfPCell cell41 = new iTextSharp.text.pdf.PdfPCell(); cell41.Colspan = 1; cell41.Border = BORDER; cell41.PaddingTop = 0; cell41.PaddingBottom = 0; cell41.AddElement(new Paragraph("$ " + Datos["total"], font)); //--------------------------------------------------------- //-------------------CDFI SELLOS--------------------------- //--------------------------------------------------------- iTextSharp.text.pdf.PdfPCell cell42 = new iTextSharp.text.pdf.PdfPCell(); cell42.Colspan = 10; cell42.Border = BORDER; cell42.Phrase = new Phrase("SELLO DIGITAL DEL CFDI", textBold); iTextSharp.text.pdf.BarcodeQRCode QR = new iTextSharp.text.pdf.BarcodeQRCode(Datos["QR"], 300, 300, null); Image img = QR.GetImage(); img.SetDpi(1400, 1400); iTextSharp.text.pdf.PdfPCell cell43 = new iTextSharp.text.pdf.PdfPCell(); cell43.Colspan = 2; cell43.Border = BORDER; cell43.Rowspan = 9; cell43.VerticalAlignment = Element.ALIGN_TOP; cell43.AddElement(img); iTextSharp.text.pdf.PdfPCell cell44 = new iTextSharp.text.pdf.PdfPCell(); cell44.Colspan = 10; cell44.Phrase = new Phrase(Datos["selloCFD"], sellos); iTextSharp.text.pdf.PdfPCell cell45 = new iTextSharp.text.pdf.PdfPCell(); cell45.Colspan = 10; cell45.Phrase = new Phrase("SELLO DIGITAL DEL SAT", textBold); cell45.Border = BORDER; iTextSharp.text.pdf.PdfPCell cell46 = new iTextSharp.text.pdf.PdfPCell(); cell46.Phrase = new Phrase(Datos["SelloSAT"], sellos); cell46.Colspan = 10; iTextSharp.text.pdf.PdfPCell cell47 = new iTextSharp.text.pdf.PdfPCell(); cell47.Phrase = new Phrase("CADENA ORIGINAL DEL COMPLEMENTO DE CERTIFICACIÓN DIGITAL DEL SAT", textBold); cell47.Border = BORDER; cell47.Colspan = 10; iTextSharp.text.pdf.PdfPCell cell48 = new iTextSharp.text.pdf.PdfPCell(); cell48.Colspan = 10; cell48.Phrase = new Phrase(Datos["CadenaOriginal"], sellos); iTextSharp.text.pdf.PdfPCell cell49 = new iTextSharp.text.pdf.PdfPCell(); cell49.Colspan = 10; cell49.Phrase = new Phrase(""); cell49.Border = BORDER; Header.AddCell(cell4); Header.AddCell(cell5); Header.AddCell(cell6); Header.AddCell(cell7); Header.AddCell(cell8); Header.AddCell(cell9); Header.AddCell(cell10); Header.AddCell(cell11); Header.AddCell(cell12); Header.AddCell(cell13); Header.AddCell(cell14); Header.AddCell(cell15); Header.AddCell(cell16); Header.AddCell(cell17); Header.AddCell(cell18); Header.AddCell(cell19); Header.AddCell(cell20); Header.AddCell(cell21); Header.AddCell(cell22); Header.AddCell(cell23); Header.AddCell(salto); Header.AddCell(cell24); Header.AddCell(cell25); Header.AddCell(cell26); Header.AddCell(cell27); Header.AddCell(cell28); Header.AddCell(cell29); Header.AddCell(cell30); Header.AddCell(cell31); Header.AddCell(cell32); Header.AddCell(cell33); Header.AddCell(cell34); Header.AddCell(cell35); Header.AddCell(cell36); Header.AddCell(cell37); Header.AddCell(cell38); Header.AddCell(cell39); Header.AddCell(cell40); Header.AddCell(cell41); Header.AddCell(salto); Header.AddCell(cell49); Header.AddCell(cell43); Header.AddCell(cell42); Header.AddCell(cell44); Header.AddCell(cell49); Header.AddCell(cell45); Header.AddCell(cell46); Header.AddCell(cell49); Header.AddCell(cell47); Header.AddCell(cell48); doc.Add(Header); doc.Close(); writer.Close(); }
private void imprimiPDF() { try { //Cria a iTextSharp Table da DataTable iTextSharp.text.pdf.PdfPTable pdfTable = new iTextSharp.text.pdf.PdfPTable(dgvConsulta.ColumnCount); pdfTable.DefaultCell.Padding = 2; pdfTable.WidthPercentage = 100; pdfTable.DefaultCell.BorderWidth = 0; pdfTable.DefaultCell.HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER; //Adiciona a linha do cabeçalho foreach (DataGridViewColumn column in dgvConsulta.Columns) { iTextSharp.text.pdf.PdfPCell cell = new iTextSharp.text.pdf.PdfPCell(new iTextSharp.text.Phrase(column.HeaderText)); cell.BackgroundColor = new iTextSharp.text.BaseColor(240, 240, 240); cell.HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER; cell.BorderWidth = 0; pdfTable.AddCell(cell); } //Adiciona as linhas foreach (DataGridViewRow row in dgvConsulta.Rows) { foreach (DataGridViewCell cell in row.Cells) { pdfTable.AddCell(cell.Value.ToString()); } } //Exporta para PDF string folderPath = @"\\10.0.3.35\d\Debug\report\RELATÓRIO DE " + frmMenu.lbTitulo.Text + ".pdf"; using (System.IO.FileStream stream = new System.IO.FileStream(folderPath, System.IO.FileMode.Create)) { //Configurando e adicionando os paragrafos iTextSharp.text.Paragraph ph1 = new iTextSharp.text.Paragraph("RELATÓRIO DE " + frmMenu.lbTitulo.Text); ph1.Alignment = iTextSharp.text.Element.ALIGN_CENTER; ph1.Font.SetStyle(5); iTextSharp.text.Paragraph ph2 = new iTextSharp.text.Paragraph(lbDeveloped.Text); //ph2.Alignment = iTextSharp.text.Element.ALIGN_CENTER; iTextSharp.text.Paragraph ph3 = new iTextSharp.text.Paragraph(lbRaf.Text); //ph3.Alignment = iTextSharp.text.Element.ALIGN_CENTER; ph3.Font.SetStyle(1); // 1 - negrito; iTextSharp.text.Paragraph ph4 = new iTextSharp.text.Paragraph(lLemail.Text); //ph4.Alignment = iTextSharp.text.Element.ALIGN_CENTER; iTextSharp.text.Document pdfDoc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4.Rotate(), 10, 10, 10, 10); iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDoc, stream); pdfDoc.Open(); iTextSharp.text.Image logo = iTextSharp.text.Image.GetInstance(@"\\10.0.3.35\d\Debug\image\logo_nova.JPG"); logo.ScalePercent(0.3f * 100); logo.Alignment = iTextSharp.text.Element.ALIGN_CENTER; pdfDoc.Add(logo); pdfDoc.Add(ph1); //pdfDoc.Add(new iTextSharp.text.Paragraph(" ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------")); pdfDoc.Add(new iTextSharp.text.Paragraph(" ")); pdfDoc.Add(new iTextSharp.text.Paragraph("Período.......: " + txtInicio.Text + " à " + txtFim.Text)); pdfDoc.Add(new iTextSharp.text.Paragraph("Usuário.......: " + frmMenu.lbNome.Text)); pdfDoc.Add(new iTextSharp.text.Paragraph("Emitido em.: " + DateTime.Now.ToString())); pdfDoc.Add(ph2); pdfDoc.Add(ph3); pdfDoc.Add(ph4); pdfDoc.Add(new iTextSharp.text.Paragraph(" ")); pdfDoc.Add(pdfTable); pdfDoc.Close(); stream.Close(); System.Diagnostics.Process.Start(folderPath); // iTextSharp.text.Document doc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4); // string caminho = Application.StartupPath + @"\Exemplo.pdf"; // iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(doc, new System.IO.FileStream(caminho, System.IO.FileMode.Create)); // try // { // doc.SetMargins(30, 30, 70, 70); // doc.AddCreationDate(); // doc.Open(); // iTextSharp.text.Paragraph par = new iTextSharp.text.Paragraph(brocaFornecedor().ToString()); // par.Alignment = iTextSharp.text.Element.ALIGN_JUSTIFIED; // par.Add("Teste na criação de um arquivo PDF"); // doc.Add(par); // doc.Close(); // System.Diagnostics.Process.Start(caminho); // } // catch (Exception Ex) // { // MessageBox.Show("Ocorreu um erro ao gerar o PDF - Erro:", Ex.Message); // } //} } } catch (Exception ex) { MessageBox.Show("OPSS.. OCORREU UM ERRO! " + ex.Message); } }
public static byte[] CrearRecibo(string Nombre, string RFC, Dictionary <string, string> conceptos, string direccion, string telefono, float Total, bool leyenda, string Imagen, bool Moneda) { Font font = new Font(Font.FontFamily.HELVETICA, 6, Font.NORMAL); Font sellos = new Font(Font.FontFamily.HELVETICA, 5, Font.NORMAL); Font textBold = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 7); DateTime now = DateTime.Now; iTextSharp.text.Document doc = new iTextSharp.text.Document(iTextSharp.text.PageSize.LETTER); MemoryStream memStream = new MemoryStream(); iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(doc, memStream); doc.AddTitle("Recibo Electronico"); doc.AddCreator("Avenzo Proteccion"); doc.AddAuthor("Cristian Santiago Rosas"); doc.Open(); iTextSharp.text.Image avenzo = iTextSharp.text.Image.GetInstance(Imagen); iTextSharp.text.pdf.PdfPTable Header = new iTextSharp.text.pdf.PdfPTable(12); float[] widths = new float[] { .8f, .8f, .8f, .8f, .8f, .8f, .8f, .8f, .8f, .8f, .8f, .8f }; iTextSharp.text.Rectangle page = doc.PageSize; Header.WidthPercentage = 80; Header.LockedWidth = true; Header.SetWidths(widths); Header.TotalWidth = page.Width - 90; //--------------------------------------------- //-----------CABEZERA DEL DOCUMENTO------------ //--------------------------------------------- iTextSharp.text.pdf.PdfPCell cell = new iTextSharp.text.pdf.PdfPCell();//--Logo cell.AddElement(avenzo); cell.Colspan = 4; cell.Border = BORDER; iTextSharp.text.pdf.PdfPCell cell2 = new iTextSharp.text.pdf.PdfPCell();//--Domicilio Fiscal cell2.AddElement(new iTextSharp.text.Paragraph("AVENZO BUSINESS GROUP S de RL de CV" + "\n" + "ABG1512109U1" + "\nDomicilio Fiscal\n" + "AVENIDA GRANDES LAGOS 19702 6\nFRACC. EL LAGO 22210\nTIJUANA, Baja California Mexico" + "\nTel. 6645266573", new Font(Font.FontFamily.HELVETICA, 7, Font.BOLD))); cell2.Colspan = 4; cell2.Border = BORDER; cell2.HorizontalAlignment = 1; Header.AddCell(cell); Header.AddCell(cell2); iTextSharp.text.pdf.PdfPCell cell51 = new iTextSharp.text.pdf.PdfPCell(); cell51.Phrase = new Phrase("", textBold); cell51.HorizontalAlignment = Element.ALIGN_CENTER; cell51.Colspan = 4; cell51.Border = 0; Header.AddCell(cell51); iTextSharp.text.pdf.PdfPCell salto = new iTextSharp.text.pdf.PdfPCell(); salto.AddElement(new Chunk("\n")); salto.Colspan = 12; salto.Border = BORDER; Header.AddCell(salto); //--------------------------------------------- //------------DATOS CLIENTE------------------- //--------------------------------------------- iTextSharp.text.pdf.PdfPCell cell4 = new iTextSharp.text.pdf.PdfPCell();//--Domicilio Fiscal cell4.Colspan = 1; cell4.Border = BORDER; cell4.PaddingTop = 0; cell4.PaddingBottom = 0; cell4.AddElement(new Paragraph("Cliente:", textBold)); iTextSharp.text.pdf.PdfPCell cell5 = new iTextSharp.text.pdf.PdfPCell();//--Domicilio Fiscal cell5.Colspan = 2; cell5.PaddingTop = 0; cell5.PaddingBottom = 0; cell5.Border = BORDER; cell5.AddElement(new Paragraph(Nombre, font)); iTextSharp.text.pdf.PdfPCell cell6 = new iTextSharp.text.pdf.PdfPCell();//--Domicilio Fiscal cell6.Colspan = 2; cell6.Border = BORDER; cell6.PaddingTop = 0; cell6.PaddingBottom = 0; cell6.AddElement(new Paragraph("", textBold)); iTextSharp.text.pdf.PdfPCell cell7 = new iTextSharp.text.pdf.PdfPCell();//--Domicilio Fiscal cell7.Colspan = 7; cell7.Border = BORDER; cell7.PaddingTop = 0; cell7.PaddingBottom = 0; cell7.AddElement(new Paragraph("", font)); iTextSharp.text.pdf.PdfPCell cell8 = new iTextSharp.text.pdf.PdfPCell();//--Domicilio Fiscal cell8.Colspan = 1; cell8.Border = BORDER; cell8.PaddingTop = 0; cell8.PaddingBottom = 0; cell8.AddElement(new Paragraph("RFC:", textBold)); iTextSharp.text.pdf.PdfPCell cell9 = new iTextSharp.text.pdf.PdfPCell();//--Domicilio Fiscal cell9.Colspan = 2; cell9.Border = BORDER; cell9.PaddingTop = 0; cell9.PaddingBottom = 0; cell9.AddElement(new Paragraph(RFC, font)); iTextSharp.text.pdf.PdfPCell cell10 = new iTextSharp.text.pdf.PdfPCell(); cell10.Colspan = 2; cell10.Border = BORDER; cell10.PaddingBottom = 0; cell10.PaddingTop = 0; cell10.AddElement(new Paragraph("Lugar de Expedición:", textBold)); iTextSharp.text.pdf.PdfPCell cell11 = new iTextSharp.text.pdf.PdfPCell(); cell11.Colspan = 3; cell11.Border = BORDER; cell11.PaddingTop = 0; cell11.PaddingBottom = 0; cell11.AddElement(new Paragraph("TIJUANA, Baja California", font)); iTextSharp.text.pdf.PdfPCell cell12 = new iTextSharp.text.pdf.PdfPCell(); cell12.AddElement(new Paragraph("Fecha de Expedicion:", textBold)); cell12.Colspan = 2; cell12.Border = BORDER; cell12.PaddingBottom = 0; cell12.PaddingTop = 0; iTextSharp.text.pdf.PdfPCell cell13 = new iTextSharp.text.pdf.PdfPCell(); cell13.Colspan = 3; cell13.Border = BORDER; cell13.PaddingTop = 0; cell13.PaddingBottom = 0; DateTime time = DateTime.Now; System.Globalization.CultureInfo ci = new System.Globalization.CultureInfo("es-MX"); cell13.AddElement(new Paragraph(time.ToString("dd", ci) + " de " + time.ToString("MMMM", ci) + " del " + time.ToString("yyyy", ci), font)); //--- iTextSharp.text.pdf.PdfPCell cell14 = new iTextSharp.text.pdf.PdfPCell(); cell14.Colspan = 1; cell14.Rowspan = 2; cell14.PaddingTop = 0; cell14.PaddingBottom = 0; cell14.Border = BORDER; cell14.AddElement(new Paragraph("Direccion:", textBold)); iTextSharp.text.pdf.PdfPCell cell15 = new iTextSharp.text.pdf.PdfPCell(); cell15.Colspan = 2; cell15.Rowspan = 2; cell15.Border = BORDER; cell15.PaddingBottom = 0; cell15.PaddingTop = 0; if (direccion.Split('|').Count() == 1) { cell15.AddElement(new Paragraph(direccion, font)); } else { cell15.AddElement(new Paragraph(direccion.Split('|')[0] + direccion.Split('|')[1] + direccion.Split('|')[2], font)); } iTextSharp.text.pdf.PdfPCell cell16 = new iTextSharp.text.pdf.PdfPCell(); cell16.Colspan = 2; cell16.PaddingTop = 0; cell16.PaddingBottom = 0; cell16.AddElement(new Paragraph("Mes de Pago:", textBold)); cell16.Border = BORDER; iTextSharp.text.pdf.PdfPCell cell17 = new iTextSharp.text.pdf.PdfPCell(); cell17.PaddingBottom = 0; cell17.PaddingTop = 0; cell17.Colspan = 3; cell17.Border = BORDER; cell17.AddElement(new Paragraph("" + time.ToString("MMMM", ci).ToUpper(), font)); iTextSharp.text.pdf.PdfPCell cell18 = new iTextSharp.text.pdf.PdfPCell(); cell18.AddElement(new Paragraph("", textBold)); cell18.Colspan = 2; cell18.Border = BORDER; cell18.PaddingTop = 0; cell18.PaddingBottom = 0; iTextSharp.text.pdf.PdfPCell cell19 = new iTextSharp.text.pdf.PdfPCell(); cell19.Colspan = 2; cell19.Border = BORDER; cell19.PaddingBottom = 0; cell19.PaddingTop = 0; cell19.AddElement(new Paragraph("", font)); iTextSharp.text.pdf.PdfPCell cell20 = new iTextSharp.text.pdf.PdfPCell(); cell20.Colspan = 2; cell20.Border = BORDER; cell20.PaddingTop = 0; cell20.PaddingBottom = 0; cell20.AddElement(new Paragraph("", textBold)); iTextSharp.text.pdf.PdfPCell cell21 = new iTextSharp.text.pdf.PdfPCell(); cell21.Colspan = 3; cell21.Border = BORDER; cell21.PaddingTop = 0; cell21.PaddingBottom = 0; cell21.AddElement(new Paragraph("", font)); iTextSharp.text.pdf.PdfPCell cell22 = new iTextSharp.text.pdf.PdfPCell(); cell22.Colspan = 2; cell22.Border = BORDER; cell22.PaddingTop = 0; cell22.PaddingBottom = 0; cell22.AddElement(new Paragraph("No. Cuenta Pago:", textBold)); iTextSharp.text.pdf.PdfPCell cell23 = new iTextSharp.text.pdf.PdfPCell(); cell23.Colspan = 2; cell23.Border = BORDER; cell23.PaddingTop = 0; cell23.PaddingBottom = 0; cell23.AddElement(new Paragraph("", font)); //---------------------------------------------- //-----------------PRODUCTOS-------------------- //---------------------------------------------- iTextSharp.text.pdf.PdfPCell cell24 = new iTextSharp.text.pdf.PdfPCell(); cell24.Colspan = 1; cell24.AddElement(new Paragraph("Cantidad", textBold)); iTextSharp.text.pdf.PdfPCell cell25 = new iTextSharp.text.pdf.PdfPCell(); cell25.Colspan = 1; cell25.AddElement(new Paragraph("Unidad de Medida", textBold)); iTextSharp.text.pdf.PdfPCell cell26 = new iTextSharp.text.pdf.PdfPCell(); cell26.Colspan = 6; cell26.HorizontalAlignment = Element.ALIGN_CENTER; cell26.VerticalAlignment = Element.ALIGN_CENTER; cell26.AddElement(new Paragraph("Descripcion", textBold)); iTextSharp.text.pdf.PdfPCell cell27 = new iTextSharp.text.pdf.PdfPCell(); cell27.Colspan = 2; cell27.AddElement(new Paragraph("Producto Unitario", textBold)); iTextSharp.text.pdf.PdfPCell cell28 = new iTextSharp.text.pdf.PdfPCell(); cell28.Colspan = 2; cell28.HorizontalAlignment = Element.ALIGN_CENTER; cell28.VerticalAlignment = Element.ALIGN_CENTER; cell28.AddElement(new Paragraph("Importe", textBold)); //----------------------------------------------- iTextSharp.text.pdf.PdfPCell cell29 = new iTextSharp.text.pdf.PdfPCell(); cell29.AddElement(new Paragraph(conceptos["cantidad"], font)); cell29.Colspan = 1; iTextSharp.text.pdf.PdfPCell cell30 = new iTextSharp.text.pdf.PdfPCell(); cell30.AddElement(new Paragraph(conceptos["unidad"], font)); cell30.Colspan = 1; iTextSharp.text.pdf.PdfPCell cell31 = new iTextSharp.text.pdf.PdfPCell(); cell31.AddElement(new Paragraph(conceptos["descripcion"], font)); cell31.Colspan = 6; iTextSharp.text.pdf.PdfPCell cell32 = new iTextSharp.text.pdf.PdfPCell(); cell32.AddElement(new Paragraph(conceptos["valorUnitario"], font)); cell32.Colspan = 2; iTextSharp.text.pdf.PdfPCell cell33 = new iTextSharp.text.pdf.PdfPCell(); cell33.AddElement(new Paragraph(conceptos["importe"], font)); cell33.Colspan = 2; cell33.FixedHeight = 200f; //------------------------------------------------------- //----------------------TOTAL---------------------------- //------------------------------------------------------- iTextSharp.text.pdf.PdfPCell cell34 = new iTextSharp.text.pdf.PdfPCell(); cell34.Colspan = 2; cell34.Rowspan = 3; cell34.Border = BORDER; cell34.PaddingBottom = 0; cell34.PaddingTop = 0; cell34.AddElement(new Paragraph("")); iTextSharp.text.pdf.PdfPCell cell35 = new iTextSharp.text.pdf.PdfPCell(); cell35.Colspan = 7; cell35.Border = BORDER; cell35.Rowspan = 3; cell35.PaddingTop = 0; cell35.PaddingBottom = 0; NumLetra nl = new NumLetra(); cell35.AddElement(new Paragraph("IMPORTE CON LETRA: " + nl.Convertir("" + Total, true, Moneda), textBold)); iTextSharp.text.pdf.PdfPCell cell36 = new iTextSharp.text.pdf.PdfPCell(); cell36.Colspan = 2; cell36.Border = BORDER; cell36.PaddingBottom = 0; cell36.PaddingTop = 0; cell36.Phrase = new Phrase("SubTotal:", textBold); cell36.HorizontalAlignment = Element.ALIGN_RIGHT; cell36.VerticalAlignment = Element.ALIGN_BOTTOM; iTextSharp.text.pdf.PdfPCell cell37 = new iTextSharp.text.pdf.PdfPCell(); cell37.Colspan = 1; cell37.Border = BORDER; cell37.PaddingTop = 0; cell37.PaddingBottom = 0; cell37.AddElement(new Paragraph("$ " + ((Total / 1.16)).ToString("f2"), font)); //-- iTextSharp.text.pdf.PdfPCell cell38 = new iTextSharp.text.pdf.PdfPCell(); cell38.Colspan = 2; cell38.PaddingBottom = 0; cell38.PaddingTop = 0; cell38.Border = BORDER; cell38.Phrase = new Phrase("IVA(IVA 16.00%):", textBold); cell38.HorizontalAlignment = Element.ALIGN_RIGHT; cell38.VerticalAlignment = Element.ALIGN_BOTTOM; iTextSharp.text.pdf.PdfPCell cell39 = new iTextSharp.text.pdf.PdfPCell(); cell39.Colspan = 1; cell39.PaddingTop = 0; cell39.PaddingBottom = 0; cell39.Border = BORDER; cell39.AddElement(new Paragraph("$ " + (Total - (Total / 1.16)).ToString("f2"), font)); //--- iTextSharp.text.pdf.PdfPCell cell40 = new iTextSharp.text.pdf.PdfPCell(); cell40.Colspan = 2; cell40.Border = BORDER; cell40.VerticalAlignment = Element.ALIGN_BOTTOM; cell40.Phrase = new Phrase("Total:", textBold); cell40.PaddingBottom = 0; cell40.PaddingTop = 0; cell40.HorizontalAlignment = Element.ALIGN_RIGHT; iTextSharp.text.pdf.PdfPCell cell41 = new iTextSharp.text.pdf.PdfPCell(); cell41.Colspan = 1; cell41.Border = BORDER; cell41.PaddingTop = 0; cell41.PaddingBottom = 0; cell41.AddElement(new Paragraph("$ " + Total.ToString("f2"), font)); //--------------------------------------------------------------------- iTextSharp.text.pdf.PdfPCell cell42 = new iTextSharp.text.pdf.PdfPCell(); cell42.Colspan = 12; cell42.Border = BORDER; cell42.AddElement(new Paragraph("CONDICIONES GENERALES", textBold)); iTextSharp.text.pdf.PdfPCell cell43 = new iTextSharp.text.pdf.PdfPCell(); cell43.Colspan = 12; cell43.Border = BORDER; cell43.Rowspan = 9; string condiciones = "1.- Unicamente se atenderán productos comercializados por Avenzo Business Group S.de R.L.de C.V."; condiciones = condiciones + "\n2.- Todos los equipos cuentan con 1(un) año de garantía después de su fecha de facturación, excepto que se indique lo contrario en la factura."; condiciones = condiciones + "\n3.- Esta garantía es valida solo hasta el " + time.ToString("dd", ci) + " de " + time.ToString("MMMM", ci) + " del " + (time.AddYears(1).ToString("yyyy", ci)); condiciones = condiciones + "\n4.- Es indispensable indicar la descripción clara del problema.No se aceptará equipo a reparación y / o garantía con descripciones tales como \"NO FUNCIONA\", \"NO SIRVE\", etc."; condiciones = condiciones + "\n5.- Se recomienda conservar su factura o recibo de compra como protección adicional ya que puede sustituir a la póliza de garantía en caso de que ésta se extravíe o exista alguna discrepancia para comprobar la vigencia de la póliza."; condiciones = condiciones + "\n6.- Avenzo Business Group S.R.L.de C.V.se compromete a cambiar el producto defectuoso o en caso que se haya descontinuado cambiarlo por uno nuevo igual, similar o bien se ofrecerá una nota de crédito por el equipo a valor actual, cuando no sea posible la reparación a consecuencia de un defecto de fabricación previo diagnostico realizado en las oficinas sin ningún cargo para el cliente."; condiciones = condiciones + "\n7.- El tiempo de cambio no será mayor de 30(treinta) dias naturales contados a partir de la fecha de recepción del producto."; condiciones = condiciones + "\n\nNOTA: Esta garantía incluye los gastos de transportación internos del producto que se deriven en el cumplimiento de la misma."; cell43.AddElement(new Paragraph(condiciones, font)); iTextSharp.text.pdf.PdfPCell cell44 = new iTextSharp.text.pdf.PdfPCell(); cell44.Colspan = 12; cell44.Border = BORDER; cell44.AddElement(new Paragraph("EXEPCIONES Y RESTRICCIONES", textBold)); iTextSharp.text.pdf.PdfPCell cell45 = new iTextSharp.text.pdf.PdfPCell(); cell45.Colspan = 12; cell45.Rowspan = 9; cell45.Border = BORDER; string casos = "\na. La garantía No cubre desperfectos ocacionados:\n •Por Variaciones de voltaje(equipo quemado)."; casos = casos + "\n •Equipo mutilado en cables, accesorios o cualquiera de sus partes."; casos = casos + "\n •Cuando se demuestre que se hizo algun cambio ala instalación original o se ha hecho mal uso del equipo (de acuerdo a manuales)."; casos = casos + "\nb. Para servicio posterior al periodo de garantia o por equipo dañada que no aplica la garantia Avenzo ofrecerá"; casos = casos + "\n •Reparación en un periodo de 30-90 días previa cotización autorizaada por el distribuidor."; casos = casos + "\n •Remplazar el equipo ofreciendo el máximo descuento."; cell45.AddElement(new Paragraph("Avenzo Business Group S.de R.L.de C.V. SE EXIME DE HACER EFECTIVA ESTA PÓLIZA DE GARANTIA EN LOS SIGUINTES CASOS:" + casos, font)); Header.AddCell(cell4); Header.AddCell(cell5); Header.AddCell(cell6); Header.AddCell(cell7); Header.AddCell(cell8); Header.AddCell(cell9); Header.AddCell(cell10); Header.AddCell(cell11); Header.AddCell(cell12); Header.AddCell(cell13); Header.AddCell(cell14); Header.AddCell(cell15); Header.AddCell(cell16); Header.AddCell(cell17); Header.AddCell(cell18); Header.AddCell(cell19); Header.AddCell(cell20); Header.AddCell(cell21); Header.AddCell(cell22); Header.AddCell(cell23); Header.AddCell(salto); Header.AddCell(cell24); Header.AddCell(cell25); Header.AddCell(cell26); Header.AddCell(cell27); Header.AddCell(cell28); Header.AddCell(cell29); Header.AddCell(cell30); Header.AddCell(cell31); Header.AddCell(cell32); Header.AddCell(cell33); Header.AddCell(cell34); Header.AddCell(cell35); Header.AddCell(cell36); Header.AddCell(cell37); Header.AddCell(cell38); Header.AddCell(cell39); Header.AddCell(cell40); Header.AddCell(cell41); Header.AddCell(salto); if (leyenda == true) { Header.AddCell(cell42); Header.AddCell(cell43); Header.AddCell(cell44); Header.AddCell(cell45); } doc.Add(Header); doc.Close(); writer.Close(); return(memStream.ToArray()); }
/// <summary> /// Método para exportar a formato PDF una colección de objetos /// </summary> /// <typeparam name="T">Clase que define a la colección de objetos</typeparam> /// <param name="_data">Colección de objetos tipo T a exportar</param> /// <param name="_typeSheet">Enum que indica el tipo de hoja y orientación del PDF</param> /// <param name="_columnsToPrint">Arreglo de cadenas con los nombres de las propiedades a imprimir</param> /// <param name="_dateTimeFormat">Representa el formato de impresión para propiedades del objeto tipo DateTime</param> /// <param name="_printHeader">Indica si se imprime los títulos en la cabecera</param> /// <returns>Regresa un Tuple con el archivo generado en el primer item /// y un comentario en el segundo item</returns> /// <remarks>Este método hace uso de la librería iTextSharp. /// El nombre de la columna se toma del atributo DisplatAttribute</remarks> public Tuple <byte[], string> ExportToPdf <T>(IEnumerable <T> _data, EnumExport.TypeSheet _typeSheet, IEnumerable <string> _columnsToPrint = null, string _dateTimeFormat = "dd/MM/yyyy", bool _printHeader = true) where T : class { try { PropertyInfo[] _properties = typeof(T).GetProperties(); iTextSharp.text.pdf.PdfPTable table = new iTextSharp.text.pdf.PdfPTable(_columnsToPrint != null && _columnsToPrint.Any() ? _columnsToPrint.Count() : _properties.Length) { WidthPercentage = 100f }; iTextSharp.text.Font font8 = iTextSharp.text.FontFactory.GetFont("ARIAL", 9); bool _print; if (_printHeader) { for (int _counter = 0; _counter < _properties.Length; _counter++) { _print = true; if (_columnsToPrint != null && _columnsToPrint.Any()) { _print = _columnsToPrint.Select(x => x.ToLowerInvariant()) .Contains(_properties[_counter].Name.ToLowerInvariant()); } if (_print) { var _displayAttribute = _properties[_counter].GetCustomAttributes(false) .FirstOrDefault(a => a is DisplayAttribute) as DisplayAttribute; iTextSharp.text.pdf.PdfPCell cell = new iTextSharp.text.pdf.PdfPCell( new iTextSharp.text.Phrase( new iTextSharp.text.Chunk( _displayAttribute != null ? GetDisplayAttributeFromResourceType(_displayAttribute) : _properties[_counter].Name, font8))); table.AddCell(cell); } } } font8 = iTextSharp.text.FontFactory.GetFont("ARIAL", 7); foreach (var x in _data) { for (int _counter = 0; _counter < _properties.Length; _counter++) { _print = true; if (_columnsToPrint != null && _columnsToPrint.Any()) { _print = _columnsToPrint.Select(z => z.ToLowerInvariant()) .Contains(_properties[_counter].Name.ToLowerInvariant()); } if (_print) { iTextSharp.text.pdf.PdfPCell cell = null; var _value = _properties[_counter].GetValue(x); switch ( _value != null ? _properties[_counter].GetValue(x).GetType().ToString() : string.Empty) { case "System.DateTime": if (_value != null) { DateTime?_datetime = (DateTime)_value; cell = new iTextSharp.text.pdf.PdfPCell( new iTextSharp.text.Phrase( new iTextSharp.text.Chunk( ((DateTime)_datetime).ToString(_dateTimeFormat), font8))); } break; case "": case "System.String": case "System.Boolean": case "System.Int16": case "System.Int32": case "System.Int64": case "System.Byte": case "System.Decimal": case "System.Double": case "System.DBNull": cell = new iTextSharp.text.pdf.PdfPCell( new iTextSharp.text.Phrase( new iTextSharp.text.Chunk( _value != null ? _value.ToString() : string.Empty, font8))); break; default: cell = new iTextSharp.text.pdf.PdfPCell( new iTextSharp.text.Phrase( new iTextSharp.text.Chunk(Resources.DefaultTypeText, font8))); break; } cell.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right table.AddCell(cell); } } } iTextSharp.text.Document pdfDoc; switch (_typeSheet) { case EnumExport.TypeSheet.Letter: pdfDoc = new iTextSharp.text.Document(iTextSharp.text.PageSize.LETTER, 10, 10, 10, 10); break; case EnumExport.TypeSheet.LetterHorizontal: pdfDoc = new iTextSharp.text.Document(iTextSharp.text.PageSize.LETTER.Rotate(), 10, 10, 10, 10); break; case EnumExport.TypeSheet.A4: pdfDoc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 10, 10, 10, 10); break; case EnumExport.TypeSheet.A4Horizontal: pdfDoc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4.Rotate(), 10, 10, 10, 10); break; case EnumExport.TypeSheet.Legal: pdfDoc = new iTextSharp.text.Document(iTextSharp.text.PageSize.LEGAL, 10, 10, 10, 10); break; case EnumExport.TypeSheet.LegalHorizontal: pdfDoc = new iTextSharp.text.Document(iTextSharp.text.PageSize.LEGAL.Rotate(), 10, 10, 10, 10); break; default: pdfDoc = new iTextSharp.text.Document(iTextSharp.text.PageSize.LETTER, 10, 10, 10, 10); break; } System.IO.MemoryStream _stream = new System.IO.MemoryStream(); iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDoc, _stream); pdfDoc.Open(); pdfDoc.Add(table); pdfDoc.Close(); return(new Tuple <byte[], string>(_stream.ToArray(), null)); } catch (Exception ex) { return(new Tuple <byte[], string>(null, Resources.ExceptionText + ex.Message)); } }
public static void ToPdfFile <T>(this System.Collections.Generic.IEnumerable <T> source, string path = null) where T : class { source.ThrowIfNull(); iTextSharp.text.Document document = new iTextSharp.text.Document(); if (string.IsNullOrWhiteSpace(path)) { path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Desktop); } path += $"\\{System.DateTime.Now.ToShortDateString().Replace('/', '-')}_table.pdf"; iTextSharp.text.pdf.PdfWriter.GetInstance(document, new System.IO.FileStream(path, System.IO.FileMode.Create)); document.Open(); iTextSharp.text.pdf.BaseFont baseFont = iTextSharp.text.pdf.BaseFont.CreateFont(@"C:\Windows\Fonts\arial.ttf", iTextSharp.text.pdf.BaseFont.IDENTITY_H, iTextSharp.text.pdf.BaseFont.NOT_EMBEDDED); iTextSharp.text.Font font = new iTextSharp.text.Font(baseFont, iTextSharp.text.Font.DEFAULTSIZE); var propertyInfoArray = typeof(T).GetProperties().ToList(); var properties = propertyInfoArray.Select(x => x.Name).ToList(); properties.ThrowIfNull(new System.Exception("Properties count is 0.")); iTextSharp.text.pdf.PdfPTable table = new iTextSharp.text.pdf.PdfPTable(properties.Count); iTextSharp.text.pdf.PdfPCell cell = new iTextSharp.text.pdf.PdfPCell(new iTextSharp.text.Phrase($"Database table writed at - {System.DateTime.Now.Date}", font)) { Colspan = properties.Count, HorizontalAlignment = 1, Border = 0 }; table.AddCell(cell); foreach (string item in properties) { cell = new iTextSharp.text.pdf.PdfPCell(new iTextSharp.text.Phrase(item, font)); cell.BackgroundColor = iTextSharp.text.BaseColor.GREEN; table.AddCell(cell); } var listOfObjects = source.ToList(); foreach (var item in listOfObjects) { foreach (System.Reflection.PropertyInfo propertyInfo in propertyInfoArray) { string propertyName = propertyInfo.Name; object propertyValue = item?.GetType().GetProperty(propertyName)?.GetValue(item, null); if (propertyValue is System.Collections.IEnumerable && !(propertyValue is string)) { cell = new iTextSharp.text.pdf.PdfPCell(new iTextSharp.text.Phrase("Collection", font)); font.Color = iTextSharp.text.BaseColor.RED; } else { bool isNull = propertyValue.IsNull(); string text = isNull ? "Empty" : propertyValue?.ToString(); cell = new iTextSharp.text.pdf.PdfPCell(new iTextSharp.text.Phrase($"{text}", font)); font.Color = iTextSharp.text.BaseColor.BLACK; cell.BackgroundColor = iTextSharp.text.BaseColor.WHITE; } table.AddCell(cell); font.Color = iTextSharp.text.BaseColor.BLACK; } } bool added = document.Add(table); if (!added) { throw new System.Exception("Table wasn't added to document. Please verify your object."); } document.Close(); }