private static void addCell(PdfPTable table, string text, string type = "TD", int rowspan = 0, int Colsapn = 0) { BaseFont bfTimes = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false); BaseFont bfTimes1 = BaseFont.CreateFont(BaseFont.TIMES_BOLD, BaseFont.CP1252, false); iTextSharp.text.Font times; if (type == "TH") { times = new iTextSharp.text.Font(bfTimes1, 10, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK); } else { times = new iTextSharp.text.Font(bfTimes, 10, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK); } PdfPCell cell = new PdfPCell(new Phrase(text, times)); if (rowspan != 0) { cell.Rowspan = rowspan; } if (Colsapn != 0) { cell.Colspan = Colsapn; } cell.HorizontalAlignment = PdfPCell.ALIGN_LEFT; cell.VerticalAlignment = PdfPCell.ALIGN_MIDDLE; cell.MinimumHeight = 20f; BaseColor color = WebColors.GetRGBColor("#008CF9"); cell.BorderColor = color; table.AddCell(cell); }
// --------------------------------------------------------------------------- public byte[] FillTemplate(byte[] pdf, Movie movie) { using (MemoryStream ms = new MemoryStream()) { PdfReader reader = new PdfReader(pdf); using (PdfStamper stamper = new PdfStamper(reader, ms)) { AcroFields form = stamper.AcroFields; BaseColor color = WebColors.GetRGBColor( "#" + movie.entry.category.color ); PushbuttonField bt = form.GetNewPushbuttonFromField(POSTER); bt.Layout = PushbuttonField.LAYOUT_ICON_ONLY; bt.ProportionalIcon = true; bt.Image = Image.GetInstance(Path.Combine(IMAGE, movie.Imdb + ".jpg")); bt.BackgroundColor = color; form.ReplacePushbuttonField(POSTER, bt.Field); PdfContentByte canvas = stamper.GetOverContent(1); float size = 12; AcroFields.FieldPosition f = form.GetFieldPositions(TEXT)[0]; while (AddParagraph(CreateMovieParagraph(movie, size), canvas, f, true) && size > 6) { size -= 0.2f; } AddParagraph(CreateMovieParagraph(movie, size), canvas, f, false); form.SetField(YEAR, movie.Year.ToString()); form.SetFieldProperty(YEAR, "bgcolor", color, null); form.SetField(YEAR, movie.Year.ToString()); stamper.FormFlattening = true; } return(ms.ToArray()); } }
public virtual void MoreColorTest() { String colorStr = "#888"; String colorStrLong = "#888888"; Assert.AreEqual(WebColors.GetRGBColor(colorStr), WebColors.GetRGBColor(colorStrLong), "Oh Nooo colors are different"); }
public PdfDocument(object model) { _model = model; _titleFont = new Font(BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1250, BaseFont.CACHED), 16); _itemFont = new Font(BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1250, BaseFont.CACHED), 12); _boldFont = new Font(BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1250, BaseFont.CACHED), 12, Font.BOLD); _tableHeaderGrayColor = WebColors.GetRGBColor("#999999"); }
internal static float GetAlphaFromRGBA(String value) { try { return(WebColors.GetRGBAColor(value)[3]); } catch (Exception) { return(1f); } }
/// <summary>Parses the RGBA color.</summary> /// <param name="colorValue">the color value</param> /// <returns>an RGBA value expressed as an array with four float values</returns> public static float[] ParseRgbaColor(String colorValue) { float[] rgbaColor = WebColors.GetRGBAColor(colorValue); if (rgbaColor == null) { logger.Error(MessageFormatUtil.Format(iText.IO.LogMessageConstant.COLOR_NOT_PARSED, colorValue)); rgbaColor = new float[] { 0, 0, 0, 1 }; } return(rgbaColor); }
/// <summary>Operations to perform before drawing an element.</summary> /// <remarks> /// Operations to perform before drawing an element. /// This includes setting stroke color and width, fill color. /// </remarks> /// <param name="context">the svg draw context</param> internal virtual void PreDraw(SvgDrawContext context) { if (this.attributesAndStyles != null) { PdfCanvas currentCanvas = context.GetCurrentCanvas(); if (!partOfClipPath) { { // fill String fillRawValue = GetAttribute(SvgConstants.Attributes.FILL); this.doFill = !SvgConstants.Values.NONE.EqualsIgnoreCase(fillRawValue); if (doFill && CanElementFill()) { Color color = ColorConstants.BLACK; if (fillRawValue != null) { color = WebColors.GetRGBColor(fillRawValue); } currentCanvas.SetFillColor(color); } } { // stroke String strokeRawValue = GetAttribute(SvgConstants.Attributes.STROKE); if (!SvgConstants.Values.NONE.EqualsIgnoreCase(strokeRawValue)) { DeviceRgb rgbColor = WebColors.GetRGBColor(strokeRawValue); if (strokeRawValue != null && rgbColor != null) { currentCanvas.SetStrokeColor(rgbColor); String strokeWidthRawValue = GetAttribute(SvgConstants.Attributes.STROKE_WIDTH); float strokeWidth = 1f; if (strokeWidthRawValue != null) { strokeWidth = CssUtils.ParseAbsoluteLength(strokeWidthRawValue); } currentCanvas.SetLineWidth(strokeWidth); doStroke = true; } } } { // opacity String opacityValue = GetAttribute(SvgConstants.Attributes.FILL_OPACITY); if (opacityValue != null && !SvgConstants.Values.NONE.EqualsIgnoreCase(opacityValue)) { PdfExtGState gs1 = new PdfExtGState(); gs1.SetFillOpacity(float.Parse(opacityValue, System.Globalization.CultureInfo.InvariantCulture)); currentCanvas.SetExtGState(gs1); } } } } }
//add table cell private void addTableCell(PdfPTable table, String text, Font font, int collapse, int allignement, String color) { PdfPCell cell = new PdfPCell(new Phrase(text, font)); BaseColor cellBackColor = WebColors.GetRGBColor(color); cell.BackgroundColor = cellBackColor; cell.Colspan = collapse; cell.Padding = 4; cell.HorizontalAlignment = allignement; table.AddCell(cell); }
/// <summary>Parses the RGBA color.</summary> /// <param name="colorValue">the color value</param> /// <returns>an RGBA value expressed as an array with four float values</returns> public static float[] ParseRgbaColor(String colorValue) { float[] rgbaColor = WebColors.GetRGBAColor(colorValue); if (rgbaColor == null) { ILog logger = LogManager.GetLogger(typeof(iText.StyledXmlParser.Css.Util.CssUtils)); logger.Error(MessageFormatUtil.Format(iText.IO.LogMessageConstant.COLOR_NOT_PARSED, colorValue)); rgbaColor = new float[] { 0, 0, 0, 1 }; } return(rgbaColor); }
internal static float GetAlphaFromRGBA(String value) { try { return(WebColors.GetRGBAColor(value)[3]); } catch (IndexOutOfRangeException) { return(1f); } catch (NullReferenceException) { return(1f); } }
private string TransformColor(string originalColor) { float[] rgbaColor = WebColors.GetRGBAColor(originalColor); float[] rgbColor = { rgbaColor[0], rgbaColor[1], rgbaColor[2] }; float[] newColorRgb = ColorBlindnessTransforms.SimulateColorBlindness(colorBlindness, rgbColor); float[] newColorRgba = { newColorRgb[0], newColorRgb[1], newColorRgb[2], rgbaColor[3] }; double[] newColorArray = ScaleColorFloatArray(newColorRgba); string newColorString = "rgba(" + (int)newColorArray[0] + "," + (int)newColorArray[1] + "," + (int)newColorArray[2] + "," + newColorArray[3] + ")"; return(newColorString); }
public void RoundTrip(Color color) { var abgrHex = color.ToAbgrHex(); var reconverted = WebColors.FromAbgrHex(abgrHex); var lookup = _colorTable[reconverted.ToArgb()] .FirstOrDefault(x => x.A == reconverted.A && x.R == reconverted.R && x.G == reconverted.G && x.B == reconverted.B); lookup.Should().NotBeNull(); lookup.Should().Be(color); }
/// <summary>Evaluates the rgba array of the specified stop color</summary> /// <returns> /// the array of 4 floats which contains the rgba value corresponding /// to the specified stop color /// </returns> public virtual float[] GetStopColor() { float[] color = null; String colorValue = GetAttribute(SvgConstants.Tags.STOP_COLOR); if (colorValue != null) { color = WebColors.GetRGBAColor(colorValue); } if (color == null) { color = WebColors.GetRGBAColor("black"); } return(color); }
/// <summary> /// Process table row for PDF export /// </summary> /// <param name="table"></param> /// <param name="line"></param> /// <param name="font"></param> /// <param name="isHeader"></param> private static void process(Table table, String line, PdfFont font, Boolean isHeader) { StringTokenizer tokenizer = new StringTokenizer(line, ","); while (tokenizer.HasMoreTokens()) { if (isHeader) { table.AddHeaderCell(new Cell().SetBackgroundColor(WebColors.GetRGBColor("A6B8AE")).Add(new Paragraph(tokenizer.NextToken()).SetFont(font))); } else { table.AddCell(new Cell().Add(new iText.Layout.Element.Paragraph(tokenizer.NextToken()).SetFont(font))); } } }
// --------------------------------------------------------------------------- /** * Create a table with information about a movie. * @param screening a Screening * @return a table */ private PdfPTable GetTable(Screening screening) { // Create a table with 4 columns PdfPTable table = new PdfPTable(4); table.SetWidths(new int[] { 1, 5, 10, 10 }); // Get the movie Movie movie = screening.movie; // A cell with the title as a nested table spanning the complete row PdfPCell cell = new PdfPCell(); // nesting is done with addElement() in this example cell.AddElement(FullTitle(screening)); cell.Colspan = 4; cell.Border = PdfPCell.NO_BORDER; BaseColor color = WebColors.GetRGBColor( "#" + movie.entry.category.color ); cell.BackgroundColor = color; table.AddCell(cell); // empty cell cell = new PdfPCell(); cell.Border = PdfPCell.NO_BORDER; cell.UseAscender = true; cell.UseDescender = true; table.AddCell(cell); // cell with the movie poster cell = new PdfPCell(GetImage(movie.Imdb)); cell.Border = PdfPCell.NO_BORDER; table.AddCell(cell); // cell with the list of directors cell = new PdfPCell(); cell.AddElement(PojoToElementFactory.GetDirectorList(movie)); cell.Border = PdfPCell.NO_BORDER; cell.UseAscender = true; cell.UseDescender = true; table.AddCell(cell); // cell with the list of countries cell = new PdfPCell(); cell.AddElement(PojoToElementFactory.GetCountryList(movie)); cell.Border = PdfPCell.NO_BORDER; cell.UseAscender = true; cell.UseDescender = true; table.AddCell(cell); return(table); }
private string TransformColor(string originalColor) { // Get RGB colors values float[] rgbaColor = WebColors.GetRGBAColor(originalColor); float[] rgbColor = { rgbaColor[0], rgbaColor[1], rgbaColor[2] }; // Change RGB colors values to corresponding colour blindness RGB values float[] newColourRgb = ColorBlindnessTransforms.SimulateColorBlindness(colorBlindness, rgbColor); float[] newColourRgba = { newColourRgb[0], newColourRgb[1], newColourRgb[2], rgbaColor[3] }; // Scale and return changed color values double[] newColorArray = ScaleColorFloatArray(newColourRgba); string newColorString = "rgba(" + (int)newColorArray[0] + "," + (int)newColorArray[1] + "," + (int)newColorArray[2] + "," + newColorArray[3] + ")"; return(newColorString); }
public virtual void GoodColorTests() { String[] colors = { "#00FF00", "00FF00", "#0F0", "0F0", "LIme", "rgb(0,255,0 )" }; // TODO webColor creates colors with a zero alpha channel (save // "transparent"), BaseColor's 3-param constructor creates them with a // 0xFF alpha channel. Which is right?! BaseColor testCol = new BaseColor(0, 255, 0); foreach (String colStr in colors) { BaseColor curCol = WebColors.GetRGBColor(colStr); Assert.IsTrue(testCol.Equals(curCol), DumpColor(testCol) + "!=" + DumpColor(curCol)); } }
private TransparentColor GetColorFromAttributeValue(SvgDrawContext context, String rawColorValue, float objectBoundingBoxMargin , float parentOpacity) { if (rawColorValue == null) { return(null); } CssDeclarationValueTokenizer tokenizer = new CssDeclarationValueTokenizer(rawColorValue); CssDeclarationValueTokenizer.Token token = tokenizer.GetNextValidToken(); if (token == null) { return(null); } String tokenValue = token.GetValue(); if (tokenValue.StartsWith("url(#") && tokenValue.EndsWith(")")) { Color resolvedColor = null; float resolvedOpacity = 1; String normalizedName = tokenValue.JSubstring(5, tokenValue.Length - 1).Trim(); ISvgNodeRenderer colorRenderer = context.GetNamedObject(normalizedName); if (colorRenderer is AbstractGradientSvgNodeRenderer) { resolvedColor = ((AbstractGradientSvgNodeRenderer)colorRenderer).CreateColor(context, GetObjectBoundingBox (context), objectBoundingBoxMargin, parentOpacity); } if (resolvedColor != null) { return(new TransparentColor(resolvedColor, resolvedOpacity)); } token = tokenizer.GetNextValidToken(); } // may become null after function parsing and reading the 2nd token if (token != null) { String value = token.GetValue(); if (!SvgConstants.Values.NONE.EqualsIgnoreCase(value)) { return(new TransparentColor(WebColors.GetRGBColor(value), parentOpacity * GetAlphaFromRGBA(value))); } } return(null); }
public void BadColorTests() { String[] badColors = { "", null, "#xyz", "#12345", "notAColor" }; foreach (String curStr in badColors) { try { // we can ignore the return value that'll never happen here WebColors.GetRGBColor(curStr); Assert.IsTrue(false, "getRGBColor should have thrown for: " + curStr); } catch (FormatException e) { // Non-null bad colors will throw an illArgEx Assert.IsTrue(curStr != null); // good, it was supposed to throw } catch (NullReferenceException e) { // the null color will NPE Assert.IsTrue(curStr == null); } } }
// --------------------------------------------------------------------------- /** * Draws a colored block on the time table, corresponding with * the screening of a specific movie. * @param screening a screening POJO, contains a movie and a category * @param under the canvas to which the block is drawn */ protected void DrawBlock( Screening screening, PdfContentByte under, PdfContentByte over ) { under.SaveState(); BaseColor color = WebColors.GetRGBColor( "#" + screening.movie.entry.category.color ); under.SetColorFill(color); Rectangle rect = GetPosition(screening); under.Rectangle( rect.Left, rect.Bottom, rect.Width, rect.Height ); under.Fill(); over.Rectangle( rect.Left, rect.Bottom, rect.Width, rect.Height ); over.Stroke(); under.RestoreState(); }
// --------------------------------------------------------------------------- /** * Manipulates a PDF file src with the file dest as result * @param src the original PDF */ public virtual byte[] ManipulatePdf(byte[] src) { locations = PojoFactory.GetLocations(); // Create a reader PdfReader reader = new PdfReader(src); using (MemoryStream ms = new MemoryStream()) { // Create a stamper using (PdfStamper stamper = new PdfStamper(reader, ms)) { // Add the annotations int page = 1; Rectangle rect; PdfAnnotation annotation; Movie movie; foreach (string day in PojoFactory.GetDays()) { foreach (Screening screening in PojoFactory.GetScreenings(day)) { movie = screening.movie; rect = GetPosition(screening); annotation = PdfAnnotation.CreateText( stamper.Writer, rect, movie.MovieTitle, string.Format(INFO, movie.Year, movie.Duration), false, "Help" ); annotation.Color = WebColors.GetRGBColor( "#" + movie.entry.category.color ); stamper.AddAnnotation(annotation, page); } page++; } } return(ms.ToArray()); } }
protected override void SetupChart() { var chart = (FlexChart)Chart; var clrs = WebColors.GetColors(); chart.BeginUpdate(); chart.ChartType = ChartType.Scatter; chart.Legend.Position = Position.Right; chart.Legend.Title = "Web (X11) Colors"; chart.Legend.GroupHeaderStyle.Font = new Font(chart.Font.FontFamily, chart.Font.Size, FontStyle.Bold); chart.Legend.ScrollBars = LegendScrollBars.Vertical; chart.LegendToggle = true; chart.AxisX.AxisLine = false; chart.AxisX.MajorGrid = true; chart.ToolTip.Content = "{Name}\nR={R}\nG={G}\nB={B}"; foreach (var clr in clrs) { var ser = new Series() { Name = clr.Name }; ser.Style.FillColor = clr.Color; ser.SymbolStyle.StrokeWidth = 0; ser.DataSource = new WebColor[] { clr }; chart.Series.Add(ser); } chart.Binding = "B"; chart.BindingX = "G"; chart.EndUpdate(); }
public virtual void TestGetRGBColorChannelsMissingBlue() { Assert.AreEqual(0, WebColors.GetRGBColor(RGB_MISSING_COLOR_VALUES).B); }
public virtual void TestGetRGBColorChannelsMissingGreen() { Assert.AreEqual(63, WebColors.GetRGBColor(RGB_MISSING_COLOR_VALUES).G); }
public virtual void TestGetRGBColorChannelsMissingRed() { Assert.AreEqual(127, WebColors.GetRGBColor(RGB_MISSING_COLOR_VALUES).R); }
public virtual void TestGetRGBColorNegativeValue() { Assert.AreEqual(0, WebColors.GetRGBColor(RGB_OUT_OF_RANGE).R); }
public virtual void TestGetRGBColorInPercentAlpha() { Assert.AreEqual(255, WebColors.GetRGBColor(RGB_PERCENT).A); }
public override IList <IElement> Start(IWorkerContext ctx, Tag tag) { IList <IElement> result; LineSeparator lineSeparator; var cssUtil = CssUtils.GetInstance(); try { IList <IElement> list = new List <IElement>(); HtmlPipelineContext htmlPipelineContext = this.GetHtmlPipelineContext(ctx); Paragraph paragraph = new Paragraph(); IDictionary <string, string> css = tag.CSS; float baseValue = 12f; if (css.ContainsKey("font-size")) { baseValue = cssUtil.ParsePxInCmMmPcToPt(css["font-size"]); } string text; css.TryGetValue("margin-top", out text); if (text == null) { text = "0.5em"; } string text2; css.TryGetValue("margin-bottom", out text2); if (text2 == null) { text2 = "0.5em"; } string border; css.TryGetValue(CSS.Property.BORDER_BOTTOM_STYLE, out border); lineSeparator = border != null && border == "dotted" ? new DottedLineSeparator() : new LineSeparator(); var element = (LineSeparator)this.GetCssAppliers().Apply( lineSeparator, tag, htmlPipelineContext ); string color; css.TryGetValue(CSS.Property.BORDER_BOTTOM_COLOR, out color); if (color != null) { // WebColors deprecated, but docs don't state replacement element.LineColor = WebColors.GetRGBColor(color); } paragraph.SpacingBefore += cssUtil.ParseValueToPt(text, baseValue); paragraph.SpacingAfter += cssUtil.ParseValueToPt(text2, baseValue); paragraph.Leading = 0f; paragraph.Add(element); list.Add(paragraph); result = list; } catch (NoCustomContextException cause) { throw new RuntimeWorkerException( LocaleMessages.GetInstance().GetMessage("customcontext.404"), cause ); } return(result); }
public FileStreamResult GenerarReporte(string dniAlumno) { Document document = new Document(PageSize.A4); MemoryStream stream = new MemoryStream(); // Datos necesarios var ex = _repository.Alumnos.GetAll(); try { PdfWriter pdfWriter = PdfWriter.GetInstance(document, stream); pdfWriter.CloseStream = false; document.Open(); // Fonts Font title = FontFactory.GetFont("Arial", 12, Font.BOLD); Font bold10 = FontFactory.GetFont("Arial", 10, Font.BOLD); Font body10 = FontFactory.GetFont("Arial", 10); // Membrete String baseUrl = _env.WebRootPath; Image imagen = Image.GetInstance(baseUrl + "/img/logo_trilce_reporte.png"); imagen.ScaleAbsoluteWidth(150); document.Add(imagen); // Título del reporte Paragraph titulo = new Paragraph("\nBOLETA DE MATRÍCULA", title); titulo.Alignment = Element.ALIGN_CENTER; document.Add(titulo); var alumno = _repository.Alumnos.GetByDni(dniAlumno); var nextGrado = _repository.Alumnos.GetGrado(alumno.Id); var nextCursos = _repository.Grados.GetCursos(nextGrado.Id); // Fecha y hora Chunk fechaCab = new Chunk("\nFECHA: ", bold10); Chunk fecha = new Chunk(DateTime.Now.ToString(), body10); Phrase pFecha = new Phrase(); pFecha.Add(fechaCab); pFecha.Add(fecha); // Datos del alumno Chunk nombreCab = new Chunk("\nNOMBRE: ", bold10); Chunk nombre = new Chunk(alumno.ApellidoPaterno + " " + alumno.ApellidoMaterno + ", " + alumno.Nombres, body10); Phrase pNombre = new Phrase(); pNombre.Add(nombreCab); pNombre.Add(nombre); Chunk dniCab = new Chunk("\nDNI: ", bold10); Chunk dni = new Chunk(alumno.Dni, body10); Phrase pDni = new Phrase(); pDni.Add(dniCab); pDni.Add(dni); Chunk gradoCab = new Chunk("\nGRADO: ", bold10); Chunk grado = new Chunk(nextGrado.Nombre + " de " + nextGrado.Nivel.Nombre, body10); Phrase pGrado = new Phrase(); pGrado.Add(gradoCab); pGrado.Add(grado); Chunk cursosCab = new Chunk("\nCURSOS:\n ", bold10); Phrase pCursos = new Phrase(); pCursos.Add(cursosCab); Paragraph pDatos = new Paragraph(); pDatos.Add(pFecha); pDatos.Add(pNombre); pDatos.Add(pDni); pDatos.Add(pGrado); pDatos.Add(pCursos); document.Add(pDatos); PdfPTable table = new PdfPTable(2); float[] anchoDeColumnas = new float[] { 20f, 10f }; table.SetWidths(anchoDeColumnas); table.WidthPercentage = 50; PdfPCell header1 = new PdfPCell(new Paragraph("NOMBRE", bold10)); header1.HorizontalAlignment = (Element.ALIGN_CENTER); header1.BackgroundColor = WebColors.GetRgbColor("#aaaaaa"); table.AddCell(header1); PdfPCell header2 = new PdfPCell(new Paragraph("HORAS", bold10)); header2.HorizontalAlignment = (Element.ALIGN_CENTER); header2.BackgroundColor = WebColors.GetRgbColor("#aaaaaa"); table.AddCell(header2); table.HeaderRows = 2; foreach (Curso curso in nextCursos) { PdfPCell nombreCurso = new PdfPCell(new Paragraph(curso.Nombre, body10)); nombreCurso.HorizontalAlignment = (Element.ALIGN_LEFT); table.AddCell(nombreCurso); PdfPCell horasCurso = new PdfPCell(new Paragraph(curso.HorasAcademicas.ToString(), body10)); horasCurso.HorizontalAlignment = (Element.ALIGN_CENTER); table.AddCell(horasCurso); } document.Add(table); } catch (DocumentException de) { Console.Error.WriteLine(de.Message); } catch (IOException ioe) { Console.Error.WriteLine(ioe.Message); } document.Close(); stream.Flush(); //Always catches me out stream.Position = 0; //Not sure if this is required return(new FileStreamResult(stream, "application/pdf")); }
public virtual void TestGetRGBColorValueOutOfRange() { Assert.AreEqual(255, WebColors.GetRGBColor(RGB_OUT_OF_RANGE).B); }