public static RenderFont GetRenderFont(StyleInfo styleInfo) { //face name RenderFont renderFont = new RenderFont(); renderFont.FaceName = getFontNameNormalized(styleInfo.FontFamily); //font style switch (renderFont.FaceName) { //this font only have one file with italic style case "Monotype Corsiva": if (styleInfo.IsFontBold()) renderFont.SimulateBold = true; break; //standard fonts default: if (styleInfo.IsFontBold() && styleInfo.FontStyle == FontStyleEnum.Italic) renderFont.Style = RenderFont.FontStyle.BoldItalic; else if (styleInfo.IsFontBold()) renderFont.Style = RenderFont.FontStyle.Bold; else if (styleInfo.FontStyle == FontStyleEnum.Italic) renderFont.Style = RenderFont.FontStyle.Italic; break; } return renderFont; }
public List<PageItem> Process(int Flags, byte[] RecordData) { MemoryStream _ms = null; BinaryReader _br = null; try { _ms = new MemoryStream(RecordData); _br = new BinaryReader(_ms); Byte[] PrivateData = _br.ReadBytes(RecordData.Length); //Ok we should have our private data which I am storing my tooltip value in... //now lets interpret it... string PData = new System.Text.ASCIIEncoding().GetString(PrivateData); //If string starts with "ToolTip" then lets do something with it.. otherwise I don't care about it. if (PData.StartsWith("ToolTip")) { PageRectangle pr = new PageRectangle(); StyleInfo si = new StyleInfo(); pr.SI = si; //si.BackgroundColor = Color.Blue;// Just a test to see where the tooltip is being drawn string[] ttd = PData.Split('|'); pr.Tooltip = ttd[0].Split(':')[1]; pr.X = X + Single.Parse(ttd[1].Split(':')[1]) * SCALEFACTOR; pr.Y = Y + Single.Parse(ttd[2].Split(':')[1]) * SCALEFACTOR; pr.W = Single.Parse(ttd[3].Split(':')[1]) * SCALEFACTOR; pr.H = Single.Parse(ttd[4].Split(':')[1]) * SCALEFACTOR; items.Add(pr); } else if (PData.StartsWith("PolyToolTip")) { PagePolygon pp = new PagePolygon(); StyleInfo si = new StyleInfo(); pp.SI = si; //si.BackgroundColor = Color.Blue;// Just a test to see where the tooltip is being drawn string[] ttd = PData.Split('|'); PointF[] pts = new PointF[(ttd.Length - 1) / 2]; pp.Points = pts; pp.Tooltip = ttd[0].Split(':')[1]; for (int i = 0; i < pts.Length; i++) { pts[i].X = X + Single.Parse(ttd[i*2 +1]) * SCALEFACTOR; pts[i].Y = Y + Single.Parse(ttd[i*2 +2]) * SCALEFACTOR; } items.Add(pp); } return items; } finally { if (_br != null) _br.Close(); if (_ms != null) _ms.Dispose(); } }
/// <summary> /// Add border /// </summary> private void addBorder(StyleInfo styleInfo, float x, float y, float width, float height) { //no bounding box to use if (height <= 0 || width <= 0) return; float bottom = y + height; float right = x + width; if (styleInfo.BStyleTop != BorderStyleEnum.None && styleInfo.BWidthTop > 0) addLine(x, y, right, y, styleInfo.BWidthTop, styleInfo.BColorTop, styleInfo.BStyleTop); if (styleInfo.BStyleRight != BorderStyleEnum.None && styleInfo.BWidthRight > 0) addLine(right, y, right, bottom, styleInfo.BWidthRight, styleInfo.BColorRight, styleInfo.BStyleRight); if (styleInfo.BStyleLeft != BorderStyleEnum.None && styleInfo.BWidthLeft > 0) addLine(x, y, x, bottom, styleInfo.BWidthLeft, styleInfo.BColorLeft, styleInfo.BStyleLeft); if (styleInfo.BStyleBottom != BorderStyleEnum.None && styleInfo.BWidthBottom > 0) addLine(x, bottom, right, bottom, styleInfo.BWidthBottom, styleInfo.BColorBottom, styleInfo.BStyleBottom); }
private void DrawBackground(Graphics g, System.Drawing.RectangleF rect, StyleInfo si) { LinearGradientBrush linGrBrush = null; SolidBrush sb = null; HatchBrush hb = null; try { if (si.BackgroundGradientType != BackgroundGradientTypeEnum.None && !si.BackgroundGradientEndColor.IsEmpty && !si.BackgroundColor.IsEmpty) { Color c = si.BackgroundColor; Color ec = si.BackgroundGradientEndColor; switch (si.BackgroundGradientType) { case BackgroundGradientTypeEnum.LeftRight: linGrBrush = new LinearGradientBrush(rect, c, ec, LinearGradientMode.Horizontal); break; case BackgroundGradientTypeEnum.TopBottom: linGrBrush = new LinearGradientBrush(rect, c, ec, LinearGradientMode.Vertical); break; case BackgroundGradientTypeEnum.Center: linGrBrush = new LinearGradientBrush(rect, c, ec, LinearGradientMode.Horizontal); break; case BackgroundGradientTypeEnum.DiagonalLeft: linGrBrush = new LinearGradientBrush(rect, c, ec, LinearGradientMode.ForwardDiagonal); break; case BackgroundGradientTypeEnum.DiagonalRight: linGrBrush = new LinearGradientBrush(rect, c, ec, LinearGradientMode.BackwardDiagonal); break; case BackgroundGradientTypeEnum.HorizontalCenter: linGrBrush = new LinearGradientBrush(rect, c, ec, LinearGradientMode.Horizontal); break; case BackgroundGradientTypeEnum.VerticalCenter: linGrBrush = new LinearGradientBrush(rect, c, ec, LinearGradientMode.Vertical); break; default: break; } } if (si.PatternType != patternTypeEnum.None) { switch (si.PatternType) { case patternTypeEnum.BackwardDiagonal: hb = new HatchBrush(HatchStyle.BackwardDiagonal, si.Color, si.BackgroundColor); break; case patternTypeEnum.CheckerBoard: hb = new HatchBrush(HatchStyle.LargeCheckerBoard, si.Color, si.BackgroundColor); break; case patternTypeEnum.Cross: hb = new HatchBrush(HatchStyle.Cross, si.Color, si.BackgroundColor); break; case patternTypeEnum.DarkDownwardDiagonal: hb = new HatchBrush(HatchStyle.DarkDownwardDiagonal, si.Color, si.BackgroundColor); break; case patternTypeEnum.DarkHorizontal: hb = new HatchBrush(HatchStyle.DarkHorizontal, si.Color, si.BackgroundColor); break; case patternTypeEnum.DiagonalBrick: hb = new HatchBrush(HatchStyle.DiagonalBrick, si.Color, si.BackgroundColor); break; case patternTypeEnum.HorizontalBrick: hb = new HatchBrush(HatchStyle.HorizontalBrick, si.Color, si.BackgroundColor); break; case patternTypeEnum.LargeConfetti: hb = new HatchBrush(HatchStyle.LargeConfetti, si.Color, si.BackgroundColor); break; case patternTypeEnum.OutlinedDiamond: hb = new HatchBrush(HatchStyle.OutlinedDiamond, si.Color, si.BackgroundColor); break; case patternTypeEnum.SmallConfetti: hb = new HatchBrush(HatchStyle.SmallConfetti, si.Color, si.BackgroundColor); break; case patternTypeEnum.SolidDiamond: hb = new HatchBrush(HatchStyle.SolidDiamond, si.Color, si.BackgroundColor); break; case patternTypeEnum.Vertical: hb = new HatchBrush(HatchStyle.Vertical, si.Color, si.BackgroundColor); break; } } if (linGrBrush != null) { g.FillRectangle(linGrBrush, rect); linGrBrush.Dispose(); } else if (hb != null) { g.FillRectangle(hb, rect); hb.Dispose(); } else if (!si.BackgroundColor.IsEmpty) { sb = new SolidBrush(si.BackgroundColor); g.FillRectangle(sb, rect); sb.Dispose(); } } finally { if (linGrBrush != null) linGrBrush.Dispose(); if (sb != null) sb.Dispose(); } return; }
public void TableRowStart(TableRow tr, Row row) { Table t = null; Header head = null; for (ReportLink rl = tr.Parent.Parent; rl != null; rl = rl.Parent) { if (rl is Table) { t = rl as Table; break; } else if (rl is Header) { head = rl as Header; } } if (t == null) { return; } tw.Write(@"\trowd \trql\trgaph108\trrh0\trleft236"); if (head != null && head.RepeatOnNewPage) // repeat table header on multiple pages { tw.Write(@"\trhdr"); } int pos = 0; int ci = 0; int columnIndex = 0; for (int i = 0; i < tr.TableCells.Items.Count; i++) { var cell = tr.TableCells.Items[i]; for (int offset = 0; offset < cell.ColSpan; offset++) { var column = t.TableColumns[columnIndex]; pos += column.Width.Twips; } string border = @"\clbrdrt\brdrth\clbrdrl\brdrs\clbrdrb\brdrs\clbrdrr\brdrs"; var style = cell.ReportItems[0].Style; if (style != null) { StyleInfo si = style.GetStyleInfo(r, row); border = string.Format(@"\clbrdrt\{0}\clbrdrl\{1}\clbrdrb\{2}\clbrdrr\{3}", GetBorderStyle(si.BStyleTop), GetBorderStyle(si.BStyleLeft), GetBorderStyle(si.BStyleBottom), GetBorderStyle(si.BStyleRight)); } tw.Write(@"{1}\cellx{0}", pos, border); } tw.Write(@"\pard \intbl"); }
private void HandleStyle(string token, StyleInfo model) { StyleInfo si= model.Clone() as StyleInfo; // always push a StyleInfo _StyleStack.Push(si); // since they will always be popped Hashtable ht = ParseHtmlCmd(token); string style = (string) ht["style"]; HandleStyleString(style, si); return; }
public List <PageItem> Process(int Flags, byte[] RecordData) { MemoryStream _ms = null; BinaryReader _br = null; try { _ms = new MemoryStream(RecordData); _br = new BinaryReader(_ms); Byte[] PrivateData = _br.ReadBytes(RecordData.Length); //Ok we should have our private data which I am storing my tooltip value in... //now lets interpret it... string PData = new System.Text.ASCIIEncoding().GetString(PrivateData); //If string starts with "ToolTip" then lets do something with it.. otherwise I don't care about it. if (PData.StartsWith("ToolTip")) { PageRectangle pr = new PageRectangle(); StyleInfo si = new StyleInfo(); pr.SI = si; //si.BackgroundColor = Color.Blue;// Just a test to see where the tooltip is being drawn string[] ttd = PData.Split('|'); pr.Tooltip = ttd[0].Split(':')[1]; pr.X = X + Single.Parse(ttd[1].Split(':')[1]) * SCALEFACTOR; pr.Y = Y + Single.Parse(ttd[2].Split(':')[1]) * SCALEFACTOR; pr.W = Single.Parse(ttd[3].Split(':')[1]) * SCALEFACTOR; pr.H = Single.Parse(ttd[4].Split(':')[1]) * SCALEFACTOR; items.Add(pr); } else if (PData.StartsWith("PolyToolTip")) { PagePolygon pp = new PagePolygon(); StyleInfo si = new StyleInfo(); pp.SI = si; //si.BackgroundColor = Color.Blue;// Just a test to see where the tooltip is being drawn string[] ttd = PData.Split('|'); PointF[] pts = new PointF[(ttd.Length - 1) / 2]; pp.Points = pts; pp.Tooltip = ttd[0].Split(':')[1]; for (int i = 0; i < pts.Length; i++) { pts[i].X = X + Single.Parse(ttd[i * 2 + 1]) * SCALEFACTOR; pts[i].Y = Y + Single.Parse(ttd[i * 2 + 2]) * SCALEFACTOR; } items.Add(pp); } return(items); } finally { if (_br != null) { _br.Close(); } if (_ms != null) { _ms.Dispose(); } } }
/// <summary> /// Page line element at the X Y to X2 Y2 position /// </summary> /// <returns></returns> private void addLine(float x, float y, float x2, float y2, StyleInfo styleInfo) { addLine(x, y, x2, y2, styleInfo.BWidthTop, styleInfo.BColorTop, styleInfo.BStyleTop); }
/// <summary> /// Create curve /// </summary> private void doCurve(PointF[] points, PointF[] tangents, StyleInfo styleInfo) { for (int i = 0; i < points.Length - 1; i++) { float x0 = points[i].X; float y0 = points[i].Y; float x1 = points[i].X + tangents[i].X; float y1 = points[i].Y + tangents[i].Y; float x2 = points[i + 1].X - tangents[i + 1].X; float y2 = points[i + 1].Y - tangents[i + 1].Y; float x3 = points[i + 1].X; float y3 = points[i + 1].Y; addCurve(x0, y0, x1, y1, x2, y2, x3, y3, styleInfo, null); } }
private void DrawBackground(Graphics g, System.Drawing.RectangleF rect, StyleInfo si) { LinearGradientBrush linGrBrush = null; SolidBrush sb = null; try { if (si.BackgroundGradientType != BackgroundGradientTypeEnum.None && !si.BackgroundGradientEndColor.IsEmpty && !si.BackgroundColor.IsEmpty) { Color c = si.BackgroundColor; Color ec = si.BackgroundGradientEndColor; switch (si.BackgroundGradientType) { case BackgroundGradientTypeEnum.LeftRight: linGrBrush = new LinearGradientBrush(rect, c, ec, LinearGradientMode.Horizontal); break; case BackgroundGradientTypeEnum.TopBottom: linGrBrush = new LinearGradientBrush(rect, c, ec, LinearGradientMode.Vertical); break; case BackgroundGradientTypeEnum.Center: linGrBrush = new LinearGradientBrush(rect, c, ec, LinearGradientMode.Horizontal); break; case BackgroundGradientTypeEnum.DiagonalLeft: linGrBrush = new LinearGradientBrush(rect, c, ec, LinearGradientMode.ForwardDiagonal); break; case BackgroundGradientTypeEnum.DiagonalRight: linGrBrush = new LinearGradientBrush(rect, c, ec, LinearGradientMode.BackwardDiagonal); break; case BackgroundGradientTypeEnum.HorizontalCenter: linGrBrush = new LinearGradientBrush(rect, c, ec, LinearGradientMode.Horizontal); break; case BackgroundGradientTypeEnum.VerticalCenter: linGrBrush = new LinearGradientBrush(rect, c, ec, LinearGradientMode.Vertical); break; default: break; } } if (linGrBrush != null) { g.FillRectangle(linGrBrush, rect); linGrBrush.Dispose(); } else if (!si.BackgroundColor.IsEmpty) { sb = new SolidBrush(si.BackgroundColor); g.FillRectangle(sb, rect); sb.Dispose(); } } finally { if (linGrBrush != null) linGrBrush.Dispose(); if (sb != null) sb.Dispose(); } return; }
// Generate an evaluated version of all the style parameters; used for page processing internal StyleInfo GetStyleInfo(Report rpt, Row r) { WorkClass wc = GetWC(rpt); if (wc != null && wc.StyleInfo != null) // When StyleInfo is available; style is a constant { return (StyleInfo) wc.StyleInfo.Clone(); // clone it because others can modify it after this } StyleInfo si = new StyleInfo(); if (this.BorderColor != null) { StyleBorderColor bc = this.BorderColor; si.BColorLeft = bc.EvalLeft(rpt, r); si.BColorRight = bc.EvalRight(rpt, r); si.BColorTop = bc.EvalTop(rpt, r); si.BColorBottom = bc.EvalBottom(rpt, r); } if (this.BorderStyle != null) { StyleBorderStyle bs = this.BorderStyle; si.BStyleLeft = bs.EvalLeft(rpt, r); si.BStyleRight = bs.EvalRight(rpt, r); si.BStyleTop = bs.EvalTop(rpt, r); si.BStyleBottom = bs.EvalBottom(rpt, r); } if (this.BorderWidth != null) { StyleBorderWidth bw = this.BorderWidth; si.BWidthLeft = bw.EvalLeft(rpt, r); si.BWidthRight = bw.EvalRight(rpt, r); si.BWidthTop = bw.EvalTop(rpt, r); si.BWidthBottom = bw.EvalBottom(rpt, r); } si.BackgroundColor = this.EvalBackgroundColor(rpt, r); // When background color not specified; and reportitem part of table // use the tables background color if (si.BackgroundColor == System.Drawing.Color.Empty) { ReportItem ri = this.Parent as ReportItem; if (ri != null) { if (ri.TC != null) { Table t = ri.TC.OwnerTable; if (t.Style != null) si.BackgroundColor = t.Style.EvalBackgroundColor(rpt, r); } } } si.BackgroundGradientType = this.EvalBackgroundGradientType(rpt, r); si.BackgroundGradientEndColor = this.EvalBackgroundGradientEndColor(rpt, r); if (this._BackgroundImage != null) { si.BackgroundImage = _BackgroundImage.GetPageImage(rpt, r); } else si.BackgroundImage = null; si.FontStyle = this.EvalFontStyle(rpt, r); si.FontFamily = this.EvalFontFamily(rpt, r); si.FontSize = this.EvalFontSize(rpt, r); si.FontWeight = this.EvalFontWeight(rpt, r); si._Format = this.EvalFormat(rpt, r); //(string) .NET Framework formatting string1 si.TextDecoration = this.EvalTextDecoration(rpt, r); si.TextAlign = this.EvalTextAlign(rpt, r); si.VerticalAlign = this.EvalVerticalAlign(rpt, r); si.Color = this.EvalColor(rpt, r); si.PaddingLeft = this.EvalPaddingLeft(rpt, r); si.PaddingRight = this.EvalPaddingRight(rpt, r); si.PaddingTop = this.EvalPaddingTop(rpt, r); si.PaddingBottom = this.EvalPaddingBottom(rpt, r); si.LineHeight = this.EvalLineHeight(rpt, r); si.Direction = this.EvalDirection(rpt, r); si.WritingMode = this.EvalWritingMode(rpt, r); si.Language = this.EvalLanguage(rpt, r); si.UnicodeBiDirectional = this.EvalUnicodeBiDirectional(rpt, r); si.Calendar = this.EvalCalendar(rpt, r); si.NumeralLanguage = this.EvalNumeralLanguage(rpt, r); si.NumeralVariant = this.EvalNumeralVariant(rpt, r); if (this._ConstantStyle) // We'll only do this work once { wc.StyleInfo = si; // when all are constant si = (StyleInfo) wc.StyleInfo.Clone(); } return si; }
private SizeF MeasureString(string s, StyleInfo si, Graphics g, out float descent) { Font drawFont=null; StringFormat drawFormat=null; SizeF ms = SizeF.Empty; descent = 0; if (s == null || s.Length == 0) return ms; try { // STYLE System.Drawing.FontStyle fs = 0; if (si.FontStyle == FontStyleEnum.Italic) fs |= System.Drawing.FontStyle.Italic; // WEIGHT switch (si.FontWeight) { case FontWeightEnum.Bold: case FontWeightEnum.Bolder: case FontWeightEnum.W500: case FontWeightEnum.W600: case FontWeightEnum.W700: case FontWeightEnum.W800: case FontWeightEnum.W900: fs |= System.Drawing.FontStyle.Bold; break; default: break; } try { FontFamily ff = si.GetFontFamily(); drawFont = new Font(ff, si.FontSize, fs); // following algorithm comes from the C# Font Metrics documentation float descentPixel = si.FontSize * ff.GetCellDescent(fs) / ff.GetEmHeight(fs); descent = RSize.PointsFromPixels(g, descentPixel); } catch { drawFont = new Font("Arial", si.FontSize, fs); // usually because font not found descent = 0; } drawFormat = new StringFormat(); drawFormat.Alignment = StringAlignment.Near; CharacterRange[] cr = {new CharacterRange(0, s.Length)}; drawFormat.SetMeasurableCharacterRanges(cr); Region[] rs = new Region[1]; rs = g.MeasureCharacterRanges(s, drawFont, new RectangleF(0,0,float.MaxValue,float.MaxValue), drawFormat); RectangleF mr = rs[0].GetBounds(g); ms.Height = RSize.PointsFromPixels(g, mr.Height); // convert to points from pixels ms.Width = RSize.PointsFromPixels(g, mr.Width); // convert to points from pixels return ms; } finally { if (drawFont != null) drawFont.Dispose(); if (drawFormat != null) drawFont.Dispose(); } }
private void DoInstructions(PointF[] points, Pen p, UInt32 Offset, UInt32 NumberOfPoints, float Tension) { BorderStyleEnum ls = getLineStyle(p); //Well we only draw lines at the moment.... switch (p.Brush.GetType().Name) { case "SolidBrush": System.Drawing.SolidBrush theBrush = (System.Drawing.SolidBrush)p.Brush; PageCurve pc = new PageCurve(); for (int i = 0; i < points.Length; i++) { points[i].X = X + points[i].X * SCALEFACTOR; points[i].Y = Y + points[i].Y * SCALEFACTOR; } pc.Points = points; pc.Offset = (int) Offset; pc.Tension = Tension; StyleInfo SI = new StyleInfo(); SI.Color = theBrush.Color; SI.BColorTop = theBrush.Color; SI.BStyleTop = ls; SI.BWidthTop = p.Width * SCALEFACTOR; SI.BColorBottom = theBrush.Color; SI.BStyleBottom = ls; SI.BWidthBottom = p.Width * SCALEFACTOR; SI.BColorLeft = theBrush.Color; SI.BStyleLeft = ls; SI.BWidthLeft = p.Width * SCALEFACTOR; SI.BColorRight = theBrush.Color; SI.BStyleRight = ls; SI.BWidthRight = p.Width * SCALEFACTOR; pc.SI = SI; items.Add(pc); break; default: break; } }
private void HandleStyleString(string style, StyleInfo si) { if (style == null || style.Length < 1) return; string[] styleList = style.Split(new char[] {';'}); foreach (string item in styleList) { string[] val = item.Split(new char[] {':'}); if (val.Length != 2) continue; // must be illegal syntax string tval = val[1].Trim(); switch (val[0].ToLower().Trim()) { case "background": case "background-color": si.BackgroundColor = XmlUtil.ColorFromHtml(tval, si.Color); break; case "color": si.Color = XmlUtil.ColorFromHtml(tval, si.Color); break; case "font-family": si.FontFamily = tval; break; case "font-size": HandleStyleFontSize(si, tval); break; case "font-style": if (tval == "italic") si.FontStyle = FontStyleEnum.Italic; break; case "font-weight": HandleStyleFontWeight(si, tval); break; } } return; }
private void HandleStyleFontWeight(StyleInfo si, string w) { try { switch (w) { case "bold": si.FontWeight = FontWeightEnum.Bold; break; case "bolder": if (si.FontWeight > FontWeightEnum.Bolder) { if (si.FontWeight < FontWeightEnum.W900) si.FontWeight++; } else if (si.FontWeight == FontWeightEnum.Normal) si.FontWeight = FontWeightEnum.W700; else if (si.FontWeight == FontWeightEnum.Bold) si.FontWeight = FontWeightEnum.W900; else if (si.FontWeight != FontWeightEnum.Bolder) si.FontWeight = FontWeightEnum.Normal; break; case "lighter": if (si.FontWeight > FontWeightEnum.Bolder) { if (si.FontWeight > FontWeightEnum.W100) si.FontWeight--; } else if (si.FontWeight == FontWeightEnum.Normal) si.FontWeight = FontWeightEnum.W300; else if (si.FontWeight == FontWeightEnum.Bold) si.FontWeight = FontWeightEnum.W400; else if (si.FontWeight != FontWeightEnum.Lighter) si.FontWeight = FontWeightEnum.Normal; break; case "normal": si.FontWeight = FontWeightEnum.Normal; break; case "100": si.FontWeight = FontWeightEnum.W100; break; case "200": si.FontWeight = FontWeightEnum.W200; break; case "300": si.FontWeight = FontWeightEnum.W300; break; case "400": si.FontWeight = FontWeightEnum.W400; break; case "500": si.FontWeight = FontWeightEnum.W500; break; case "600": si.FontWeight = FontWeightEnum.W600; break; case "700": si.FontWeight = FontWeightEnum.W700; break; case "800": si.FontWeight = FontWeightEnum.W800; break; case "900": si.FontWeight = FontWeightEnum.W900; break; } } catch {} // lots of user errors will cause an exception; ignore return; }
private void HandleStyleFontSize(StyleInfo si, string size) { try { int i = size.IndexOf("pt"); if (i > 0) { size = size.Remove(i, 2); float n = (float) Convert.ToDouble(size); if (size[0] == '+') si.FontSize += n; else si.FontSize = n; return; } i = size.IndexOf("%"); if (i > 0) { size = size.Remove(i, 1); float n = (float) Convert.ToDouble(size); si.FontSize = n*si.FontSize; return; } switch (size) { case "xx-small": si.FontSize = 6; break; case "x-small": si.FontSize = 8; break; case "small": si.FontSize = 10; break; case "medium": si.FontSize = 12; break; case "large": si.FontSize = 14; break; case "x-large": si.FontSize = 16; break; case "xx-large": si.FontSize = 18; break; case "1": si.FontSize = 8; break; case "2": si.FontSize = 10; break; case "3": si.FontSize = 12; break; case "4": si.FontSize = 14; break; case "5": si.FontSize = 18; break; case "6": si.FontSize = 24; break; case "7": si.FontSize = 36; break; } } catch {} // lots of user errors will cause an exception; ignore return; }
/// <summary> /// Add curve /// </summary> private void addCurve(float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4, StyleInfo styleInfo, string url) { if (styleInfo.BStyleTop != BorderStyleEnum.None) { switch (styleInfo.BStyleTop) { case BorderStyleEnum.Dashed: pdfContent.SetLineDash(new float[] { '3', '2' }, 0); break; case BorderStyleEnum.Dotted: pdfContent.SetLineDash(new float[] { '2' }, 0); break; case BorderStyleEnum.Solid: default: pdfContent.SetLineDash(new float[] { }, 0); break; } pdfContent.SetRGBColorStroke(styleInfo.BColorTop.R, styleInfo.BColorTop.G, styleInfo.BColorTop.B); } if (!styleInfo.BackgroundColor.IsEmpty) { pdfContent.SetRGBColorStrokeF(styleInfo.BackgroundColor.R, styleInfo.BackgroundColor.G, styleInfo.BackgroundColor.B); } pdfContent.CurveTo(x1, pageHeight - y1, x2, pageHeight - y1, x3, pageHeight - y3); if (styleInfo.BackgroundColor.IsEmpty) pdfContent.ClosePathStroke(); else pdfContent.ClosePathFillStroke(); }
internal StyleInfo StyleInfo; // When ConstantStyle is true; this will hold cache of StyleInfo #endregion Fields #region Constructors internal WorkClass() { CssStyle = null; StyleInfo = null; }
/// <summary> /// Add a filled and stroked rectangle /// </summary> /// <returns></returns> private void addFillRectangle(float x, float y, float width, float height, StyleInfo styleInfo) { //first design the filled rectangle addFillRectangle(x, y, width, height, styleInfo.BackgroundColor); //second, stroke the rectangle pdfContent.SetColorStroke(new BaseColor(styleInfo.Color)); pdfContent.ClosePathStroke(); }
private void HandleStyleFontWeight(StyleInfo si, string w) { try { switch (w) { case "bold": si.FontWeight = FontWeightEnum.Bold; break; case "bolder": if (si.FontWeight > FontWeightEnum.Bolder) { if (si.FontWeight < FontWeightEnum.W900) { si.FontWeight++; } } else if (si.FontWeight == FontWeightEnum.Normal) { si.FontWeight = FontWeightEnum.W700; } else if (si.FontWeight == FontWeightEnum.Bold) { si.FontWeight = FontWeightEnum.W900; } else if (si.FontWeight != FontWeightEnum.Bolder) { si.FontWeight = FontWeightEnum.Normal; } break; case "lighter": if (si.FontWeight > FontWeightEnum.Bolder) { if (si.FontWeight > FontWeightEnum.W100) { si.FontWeight--; } } else if (si.FontWeight == FontWeightEnum.Normal) { si.FontWeight = FontWeightEnum.W300; } else if (si.FontWeight == FontWeightEnum.Bold) { si.FontWeight = FontWeightEnum.W400; } else if (si.FontWeight != FontWeightEnum.Lighter) { si.FontWeight = FontWeightEnum.Normal; } break; case "normal": si.FontWeight = FontWeightEnum.Normal; break; case "100": si.FontWeight = FontWeightEnum.W100; break; case "200": si.FontWeight = FontWeightEnum.W200; break; case "300": si.FontWeight = FontWeightEnum.W300; break; case "400": si.FontWeight = FontWeightEnum.W400; break; case "500": si.FontWeight = FontWeightEnum.W500; break; case "600": si.FontWeight = FontWeightEnum.W600; break; case "700": si.FontWeight = FontWeightEnum.W700; break; case "800": si.FontWeight = FontWeightEnum.W800; break; case "900": si.FontWeight = FontWeightEnum.W900; break; } } catch {} // lots of user errors will cause an exception; ignore return; }
/// <summary> /// Add rectangle at the X Y position /// </summary> private void addRectangle(float x, float y, float width, float height, StyleInfo styleInfo, string url, string tooltip) { //draw background rectangle if needed (background color, height and width are specified) if (!styleInfo.BackgroundColor.IsEmpty && height > 0 && width > 0) addFillRectangle(x, y, width, height, styleInfo); //add any required border addBorder(styleInfo, x, y, width, height); //add url if (url != null) document.Add(new Annotation(x, pageHeight - y, height, width, url)); //add tooltip if (!string.IsNullOrEmpty(tooltip)) document.Add(new Annotation(x, pageHeight - y, height, width, tooltip)); }
private SizeF MeasureString(string s, StyleInfo si, Graphics g, out float descent) { Font drawFont = null; StringFormat drawFormat = null; SizeF ms = SizeF.Empty; descent = 0; if (s == null || s.Length == 0) { return(ms); } try { // STYLE System.Drawing.FontStyle fs = 0; if (si.FontStyle == FontStyleEnum.Italic) { fs |= System.Drawing.FontStyle.Italic; } // WEIGHT switch (si.FontWeight) { case FontWeightEnum.Bold: case FontWeightEnum.Bolder: case FontWeightEnum.W500: case FontWeightEnum.W600: case FontWeightEnum.W700: case FontWeightEnum.W800: case FontWeightEnum.W900: fs |= System.Drawing.FontStyle.Bold; break; default: break; } try { FontFamily ff = si.GetFontFamily(); drawFont = new Font(ff, si.FontSize, fs); // following algorithm comes from the C# Font Metrics documentation float descentPixel = si.FontSize * ff.GetCellDescent(fs) / ff.GetEmHeight(fs); descent = RSize.PointsFromPixels(g, descentPixel); } catch { drawFont = new Font("Arial", si.FontSize, fs); // usually because font not found descent = 0; } drawFormat = new StringFormat(); drawFormat.Alignment = StringAlignment.Near; CharacterRange[] cr = { new CharacterRange(0, s.Length) }; drawFormat.SetMeasurableCharacterRanges(cr); Region[] rs = new Region[1]; rs = g.MeasureCharacterRanges(s, drawFont, new RectangleF(0, 0, float.MaxValue, float.MaxValue), drawFormat); RectangleF mr = rs[0].GetBounds(g); ms.Height = RSize.PointsFromPixels(g, mr.Height); // convert to points from pixels ms.Width = RSize.PointsFromPixels(g, mr.Width); // convert to points from pixels return(ms); } finally { if (drawFont != null) { drawFont.Dispose(); } if (drawFormat != null) { drawFont.Dispose(); } } }
private void DoEllipse(Pen p, Single Xp, Single Yp, Single Wid, Single Hgt) { BorderStyleEnum ls = getLineStyle(p); Color col = Color.Black; if (p.Brush.GetType().Name.Equals("SolidBrush")) { System.Drawing.SolidBrush theBrush = (System.Drawing.SolidBrush)p.Brush; col = theBrush.Color; } PageEllipse pl = new PageEllipse(); pl.X = X + Xp * SCALEFACTOR; pl.Y = Y + Yp * SCALEFACTOR; pl.W = Wid * SCALEFACTOR; pl.H = Hgt * SCALEFACTOR; StyleInfo SI = new StyleInfo(); SI.Color = col; SI.BColorTop = col; SI.BStyleTop = ls; SI.BWidthTop = p.Width * SCALEFACTOR; pl.SI = SI; items.Add(pl); //Lines.AppendFormat("\r\n"); //CrLf //Lines.AppendFormat("q\t"); //Push graphics state onto stack //Lines.AppendFormat("{0} w\t", p.Width * ScaleX); //set width of path //Lines.AppendFormat("{0} \t", linestyle); //line style from pen... //Lines.AppendFormat("{0} {1} {2} RG\t", Math.Round(R / 255.0, 3), Math.Round(G / 255.0, 3), Math.Round(B / 255.0, 3)); //Set RGB colours //Lines.AppendFormat("{0} {1} {2} rg\t", Math.Round(R / 255.0, 3), Math.Round(G / 255.0, 3), Math.Round(B / 255.0, 3)); //Set RGB colours ////Need some bezier curves to draw an ellipse.. we can't draw a circle, but we can get close. //Double k = 0.5522847498; //Double RadiusX = (Wid / 2.0) * ScaleX; //Double RadiusY = (Hgt / 2.0) * ScaleY; //Double Y4 = Y + Height - Yp * ScaleY; //Double X1 = Xp * ScaleX + X; //Double Y1 = Y4 - RadiusY; //Double X4 = X1 + RadiusX; //Lines.AppendFormat("{0} {1} m\t", X1, Y1);//FirstPoint.. //Double kRy = k * RadiusY; //Double kRx = k * RadiusX; ////Control Point 1 will be on the same X as point 1 and be -kRy Y //Double X2 = X1; //Double Y2 = Y1 + kRy; //Double X3 = X4 - kRx; //Double Y3 = Y4; //Lines.AppendFormat("{0} {1} {2} {3} {4} {5} c\t", X2, Y2, X3, Y3, X4, Y4); //Upper Left Quadrant //X1 += 2 * RadiusX; //X2 = X1; //X3 += 2 * kRx; //Lines.AppendFormat("{0} {1} {2} {3} {4} {5} c\t", X3, Y3, X2, Y2, X1, Y1); //Upper Right Quadrant //Y2 -= 2 * kRy; //Y3 -= 2 * RadiusY; //Y4 = Y3; //Lines.AppendFormat("{0} {1} {2} {3} {4} {5} c\t", X2, Y2, X3, Y3, X4, Y4); //Lower Right Quadrant //X1 -= 2 * RadiusX; //X2 = X1; //X3 -= 2 * kRx; //Lines.AppendFormat("{0} {1} {2} {3} {4} {5} c\t", X3, Y3, X2, Y2, X1, Y1); //Lower Right Quadrant //Lines.AppendFormat("S\t");//Stroke path //Lines.AppendFormat("Q\t");//Pop graphics state from stack }
private void BuildPrivate(Graphics g) { this.SI.TextAlign = TextAlignEnum.Left; this.SI.VerticalAlign = VerticalAlignEnum.Top; this.SI.WritingMode = WritingModeEnum.lr_tb; PageText model = new PageText(""); model.AllowSelect = false; model.Page = this.Page; model.HyperLink = null; model.Tooltip = null; int fontSizeModel = 3; if (_items != null) // this has already been built { return; } _items = new List <PageItem>(); _StyleStack = new Stack(); // The first item is always a text box with the border and background attributes PageText pt = new PageText(""); pt.AllowSelect = true; // This item represents HTML item for selection in RdlViewer pt.Page = this.Page; pt.HtmlParent = this; pt.X = this.X; pt.Y = this.Y; pt.H = this.H; pt.W = this.W; pt.CanGrow = false; pt.SI = this.SI.Clone() as StyleInfo; pt.SI.PaddingBottom = pt.SI.PaddingLeft = pt.SI.PaddingRight = pt.SI.PaddingTop = 0; _items.Add(pt); // Now we create multiple items that represent what is in the box PageTextHtmlLexer hl = new PageTextHtmlLexer(this.Text); List <string> tokens = hl.Lex(); float textWidth = this.W - pt.SI.PaddingLeft - pt.SI.PaddingRight; // Now set the default style for the rest of the members StyleInfo si = this.SI.Clone() as StyleInfo; si.BStyleBottom = si.BStyleLeft = si.BStyleRight = si.BStyleTop = BorderStyleEnum.None; si.BackgroundColor = Color.Empty; si.BackgroundGradientType = BackgroundGradientTypeEnum.None; si.BackgroundImage = null; bool bFirstInLine = true; StringBuilder sb = new StringBuilder(); // this will hold the accumulating line float lineXPos = 0; float xPos = 0; float yPos = 0; float maxLineHeight = 0; float maxDescent = 0; float descent; // working value for descent SizeF ms; bool bWhiteSpace = false; List <PageItem> lineItems = new List <PageItem>(); foreach (string token in tokens) { if (token[0] == PageTextHtmlLexer.HTMLCMD) // indicates an HTML command { // we need to create a PageText since the styleinfo is changing if (sb.Length != 0) { pt = new PageText(sb.ToString()); pt.AllowSelect = false; pt.Page = this.Page; pt.HtmlParent = this; pt.HyperLink = model.HyperLink; pt.Tooltip = model.Tooltip; pt.NoClip = true; sb = new StringBuilder(); pt.X = this.X + lineXPos; pt.Y = this.Y + yPos; pt.CanGrow = false; pt.SI = CurrentStyle(si).Clone() as StyleInfo; _items.Add(pt); lineItems.Add(pt); ms = this.MeasureString(pt.Text, pt.SI, g, out descent); maxDescent = Math.Max(maxDescent, descent); pt.W = ms.Width; pt.H = ms.Height; pt.Descent = descent; maxLineHeight = Math.Max(maxLineHeight, ms.Height); lineXPos = xPos; } // Now reset the styleinfo StyleInfo cs = CurrentStyle(si); string ltoken = token.Substring(1, Math.Min(token.Length - 1, 10)).ToLower(); if (ltoken == "<b>" || ltoken == "<strong>") { cs.FontWeight = FontWeightEnum.Bold; } else if (ltoken == "</b>" || ltoken == "</strong>") { cs.FontWeight = FontWeightEnum.Normal; } else if (ltoken == "<i>" || ltoken == "<cite>" || ltoken == "<var>" || ltoken == "<em>") { cs.FontStyle = FontStyleEnum.Italic; } else if (ltoken == "</i>" || ltoken == "</cite>" || ltoken == "</var>" || ltoken == "</em>") { cs.FontStyle = FontStyleEnum.Normal; } else if (ltoken == "<code>" || ltoken == "<samp>") { cs.FontFamily = "Courier New"; } else if (ltoken == "</code>" || ltoken == "</samp>") { cs.FontFamily = this.SI.FontFamily; } else if (ltoken == "<kbd>") { cs.FontFamily = "Courier New"; cs.FontWeight = FontWeightEnum.Bold; } else if (ltoken == "</kdd>") { cs.FontFamily = this.SI.FontFamily; cs.FontWeight = FontWeightEnum.Normal; } else if (ltoken == "<big>") { // big makes it bigger by 20% for each time over the baseline of 3 fontSizeModel++; float inc = 1; for (int i = 3; i < fontSizeModel; i++) { inc += .2f; } float h = this.SI.FontSize * inc; cs.FontSize = h; } else if (ltoken == "</big>") { // undoes the effect of big fontSizeModel--; float inc = 1; for (int i = 3; i < fontSizeModel; i++) { inc += .2f; } float h = this.SI.FontSize / inc; cs.FontSize = h; } else if (ltoken == "<small>") { // small makes it smaller by 20% for each time under the baseline of 3 fontSizeModel--; float inc = 1; for (int i = 3; i > fontSizeModel; i--) { inc += .2f; } float h = this.SI.FontSize / inc; cs.FontSize = h; } else if (ltoken == "</small>") { // undoes the effect of small fontSizeModel++; float inc = 1; for (int i = 3; i > fontSizeModel; i--) { inc += .2f; } float h = this.SI.FontSize * inc; cs.FontSize = h; } else if (ltoken.StartsWith("<br")) { yPos += maxLineHeight; NormalizeLineHeight(lineItems, maxLineHeight, maxDescent); maxLineHeight = xPos = lineXPos = maxDescent = 0; bFirstInLine = true; bWhiteSpace = false; } else if (ltoken.StartsWith("<hr")) { // Add a line // Process existing line if any yPos += maxLineHeight; NormalizeLineHeight(lineItems, maxLineHeight, maxDescent); maxLineHeight = xPos = lineXPos = maxDescent = 0; bFirstInLine = true; bWhiteSpace = false; PageLine pl = new PageLine(); pl.AllowSelect = false; pl.Page = this.Page; const int horzLineHeight = 10; pl.SI = cs.Clone() as StyleInfo; pl.SI.BStyleLeft = BorderStyleEnum.Ridge; pl.Y = pl.Y2 = this.Y + yPos + horzLineHeight / 2; pl.X = this.X; pl.X2 = pl.X + this.W; _items.Add(pl); yPos += horzLineHeight; // skip past horizontal line } else if (ltoken.StartsWith("<p")) { yPos += maxLineHeight * 2; NormalizeLineHeight(lineItems, maxLineHeight, maxDescent); maxLineHeight = xPos = lineXPos = maxDescent = 0; bFirstInLine = true; bWhiteSpace = false; } else if (ltoken.StartsWith("<a")) { BuildAnchor(token.Substring(1), cs, model); } else if (ltoken.StartsWith("<img")) { PageImage pimg = BuildImage(g, token.Substring(1), cs, model); if (pimg != null) // We got an image; add to process list { pimg.Y = this.Y + yPos; pimg.X = this.X; _items.Add(pimg); yPos += pimg.H; // Increment y position maxLineHeight = xPos = lineXPos = maxDescent = 0; bFirstInLine = true; bWhiteSpace = false; } } else if (ltoken == "</a>") { model.HyperLink = model.Tooltip = null; PopStyle(); } else if (ltoken.StartsWith("<span")) { HandleStyle(token.Substring(1), si); } else if (ltoken == "</span>") { // we really should match span and font but it shouldn't matter very often? PopStyle(); } else if (ltoken.StartsWith("<font")) { HandleFont(token.Substring(1), si); } else if (ltoken == "</font>") { // we really should match span and font but it shouldn't matter very often? PopStyle(); } continue; } if (token == PageTextHtmlLexer.WHITESPACE) { if (!bFirstInLine) { bWhiteSpace = true; } continue; } if (token != PageTextHtmlLexer.EOF) { string ntoken; if (token == PageTextHtmlLexer.NBSP.ToString()) { ntoken = bWhiteSpace ? " " : " "; } else { ntoken = bWhiteSpace ? " " + token : token; } ntoken = ntoken.Replace(PageTextHtmlLexer.NBSP, ' '); bWhiteSpace = false; // can only use whitespace once ms = this.MeasureString(ntoken, CurrentStyle(si), g, out descent); if (xPos + ms.Width < textWidth) { bFirstInLine = false; sb.Append(ntoken); maxDescent = Math.Max(maxDescent, descent); maxLineHeight = Math.Max(maxLineHeight, ms.Height); xPos += ms.Width; continue; } } else if (sb.Length == 0) // EOF and no previous string means we're done { continue; } pt = new PageText(sb.ToString()); pt.AllowSelect = false; pt.Page = this.Page; pt.HtmlParent = this; pt.NoClip = true; pt.HyperLink = model.HyperLink; pt.Tooltip = model.Tooltip; sb = new StringBuilder(); sb.Append(token.Replace(PageTextHtmlLexer.NBSP, ' ')); pt.SI = CurrentStyle(si).Clone() as StyleInfo; ms = this.MeasureString(pt.Text, pt.SI, g, out descent); pt.X = this.X + lineXPos; pt.Y = this.Y + yPos; pt.H = ms.Height; pt.W = ms.Width; pt.Descent = descent; pt.CanGrow = false; _items.Add(pt); lineItems.Add(pt); maxDescent = Math.Max(maxDescent, descent); maxLineHeight = Math.Max(maxLineHeight, ms.Height); yPos += maxLineHeight; // Increment y position NormalizeLineHeight(lineItems, maxLineHeight, maxDescent); lineXPos = maxLineHeight = maxDescent = 0; // start line height over // Now set the xPos just after the current token ms = this.MeasureString(token, CurrentStyle(si), g, out descent); xPos = ms.Width; } _TotalHeight = yPos; // set the calculated height of the result _StyleStack = null; return; }
private void DrawString(PageText pt, Graphics g, RectangleF r) { StyleInfo si = pt.SI; string s = pt.Text; Font drawFont = null; StringFormat drawFormat = null; Brush drawBrush = null; try { // STYLE System.Drawing.FontStyle fs = 0; if (si.FontStyle == FontStyleEnum.Italic) { fs |= System.Drawing.FontStyle.Italic; } switch (si.TextDecoration) { case TextDecorationEnum.Underline: fs |= System.Drawing.FontStyle.Underline; break; case TextDecorationEnum.LineThrough: fs |= System.Drawing.FontStyle.Strikeout; break; case TextDecorationEnum.Overline: case TextDecorationEnum.None: break; } // WEIGHT switch (si.FontWeight) { case FontWeightEnum.Bold: case FontWeightEnum.Bolder: case FontWeightEnum.W500: case FontWeightEnum.W600: case FontWeightEnum.W700: case FontWeightEnum.W800: case FontWeightEnum.W900: fs |= System.Drawing.FontStyle.Bold; break; default: break; } try { drawFont = new Font(si.GetFontFamily(), si.FontSize, fs); // si.FontSize already in points } catch (ArgumentException) { drawFont = new Font("Arial", si.FontSize, fs); // if this fails we'll let the error pass thru } // ALIGNMENT drawFormat = new StringFormat(); switch (si.TextAlign) { case TextAlignEnum.Right: drawFormat.Alignment = StringAlignment.Far; break; case TextAlignEnum.Center: drawFormat.Alignment = StringAlignment.Center; break; case TextAlignEnum.Left: default: drawFormat.Alignment = StringAlignment.Near; break; } if (pt.SI.WritingMode == WritingModeEnum.tb_rl) { drawFormat.FormatFlags |= StringFormatFlags.DirectionRightToLeft; drawFormat.FormatFlags |= StringFormatFlags.DirectionVertical; } switch (si.VerticalAlign) { case VerticalAlignEnum.Bottom: drawFormat.LineAlignment = StringAlignment.Far; break; case VerticalAlignEnum.Middle: drawFormat.LineAlignment = StringAlignment.Center; break; case VerticalAlignEnum.Top: default: drawFormat.LineAlignment = StringAlignment.Near; break; } // draw the background DrawBackground(g, r, si); // adjust drawing rectangle based on padding RectangleF r2 = new RectangleF(r.Left + si.PaddingLeft, r.Top + si.PaddingTop, r.Width - si.PaddingLeft - si.PaddingRight, r.Height - si.PaddingTop - si.PaddingBottom); drawBrush = new SolidBrush(si.Color); if (pt.NoClip) // request not to clip text { g.DrawString(pt.Text, drawFont, drawBrush, new PointF(r.Left, r.Top), drawFormat); //HighlightString(g, pt, new RectangleF(r.Left, r.Top, float.MaxValue, float.MaxValue),drawFont, drawFormat); } else { g.DrawString(pt.Text, drawFont, drawBrush, r2, drawFormat); //HighlightString(g, pt, r2, drawFont, drawFormat); } } finally { if (drawFont != null) { drawFont.Dispose(); } if (drawFormat != null) { drawFont.Dispose(); } if (drawBrush != null) { drawBrush.Dispose(); } } }
private void DoInstructions(PointF[] Ps, Brush b) { PagePolygon pl = new PagePolygon(); //pl.X = X * SCALEFACTOR; //pl.Y = Y * SCALEFACTOR; pl.Points = Ps; StyleInfo SI = new StyleInfo(); switch (b.GetType().Name) { case "SolidBrush": System.Drawing.SolidBrush theBrush = (System.Drawing.SolidBrush)b; SI.Color = theBrush.Color; SI.BackgroundColor = theBrush.Color; break; case "LinearGradientBrush": System.Drawing.Drawing2D.LinearGradientBrush linBrush = (System.Drawing.Drawing2D.LinearGradientBrush)b; SI.BackgroundGradientType = BackgroundGradientTypeEnum.LeftRight; SI.BackgroundColor = linBrush.LinearColors[0]; SI.BackgroundGradientEndColor = linBrush.LinearColors[1]; break; case "HatchBrush": System.Drawing.Drawing2D.HatchBrush hatBrush = (System.Drawing.Drawing2D.HatchBrush)b; SI.BackgroundColor = hatBrush.BackgroundColor; SI.Color = hatBrush.ForegroundColor; SI.PatternType = StyleInfo.GetPatternType(hatBrush.HatchStyle); break; default: break; } pl.SI = SI; items.Add(pl); }
private void DrawImageSized(PageImage pi, System.Drawing.Image im, System.Drawing.Graphics g, System.Drawing.RectangleF r) { float height, width; // some work variables StyleInfo si = pi.SI; // adjust drawing rectangle based on padding System.Drawing.RectangleF r2 = new System.Drawing.RectangleF(r.Left + PixelsX(si.PaddingLeft), r.Top + PixelsY(si.PaddingTop), r.Width - PixelsX(si.PaddingLeft + si.PaddingRight), r.Height - PixelsY(si.PaddingTop + si.PaddingBottom)); System.Drawing.Rectangle ir; // int work rectangle switch (pi.Sizing) { case ImageSizingEnum.AutoSize: // Note: GDI+ will stretch an image when you only provide // the left/top coordinates. This seems pretty stupid since // it results in the image being out of focus even though // you don't want the image resized. if (g.DpiX == im.HorizontalResolution && g.DpiY == im.VerticalResolution) { ir = new System.Drawing.Rectangle(Convert.ToInt32(r2.Left), Convert.ToInt32(r2.Top), im.Width, im.Height); } else { ir = new System.Drawing.Rectangle(Convert.ToInt32(r2.Left), Convert.ToInt32(r2.Top), Convert.ToInt32(r2.Width), Convert.ToInt32(r2.Height)); } g.DrawImage(im, ir); break; case ImageSizingEnum.Clip: Region saveRegion = g.Clip; Region clipRegion = new Region(g.Clip.GetRegionData()); clipRegion.Intersect(r2); g.Clip = clipRegion; if (g.DpiX == im.HorizontalResolution && g.DpiY == im.VerticalResolution) { ir = new System.Drawing.Rectangle(Convert.ToInt32(r2.Left), Convert.ToInt32(r2.Top), im.Width, im.Height); } else { ir = new System.Drawing.Rectangle(Convert.ToInt32(r2.Left), Convert.ToInt32(r2.Top), Convert.ToInt32(r2.Width), Convert.ToInt32(r2.Height)); } g.DrawImage(im, ir); g.Clip = saveRegion; break; case ImageSizingEnum.FitProportional: float ratioIm = (float)im.Height / (float)im.Width; float ratioR = r2.Height / r2.Width; height = r2.Height; width = r2.Width; if (ratioIm > ratioR) { // this means the rectangle width must be corrected width = height * (1 / ratioIm); } else if (ratioIm < ratioR) { // this means the ractangle height must be corrected height = width * ratioIm; } r2 = new RectangleF(r2.X, r2.Y, width, height); g.DrawImage(im, r2); break; case ImageSizingEnum.Fit: default: g.DrawImage(im, r2); break; } return; }
private void DoInstructions(Single recX, Single recY, Single recWidth, Single recHeight, Brush b, Single StartAngle, Single SweepAngle) { PagePie pl = new PagePie(); pl.StartAngle = StartAngle; pl.SweepAngle = SweepAngle; StyleInfo SI = new StyleInfo(); pl.X = X + recX * SCALEFACTOR; pl.Y = Y + recY * SCALEFACTOR; pl.W = recWidth * SCALEFACTOR; pl.H = recHeight * SCALEFACTOR; switch (b.GetType().Name) { case "SolidBrush": System.Drawing.SolidBrush theBrush = (System.Drawing.SolidBrush)b; SI.Color = theBrush.Color; SI.BackgroundColor = theBrush.Color; break; case "LinearGradientBrush": System.Drawing.Drawing2D.LinearGradientBrush linBrush = (System.Drawing.Drawing2D.LinearGradientBrush)b; SI.BackgroundGradientType = BackgroundGradientTypeEnum.LeftRight; SI.BackgroundColor = linBrush.LinearColors[0]; SI.BackgroundGradientEndColor = linBrush.LinearColors[1]; break; case "HatchBrush": System.Drawing.Drawing2D.HatchBrush hatBrush = (System.Drawing.Drawing2D.HatchBrush)b; SI.BackgroundColor = hatBrush.BackgroundColor; SI.Color = hatBrush.ForegroundColor; SI.PatternType = StyleInfo.GetPatternType(hatBrush.HatchStyle); break; default: break; } pl.SI = SI; items.Add(pl); }
private void DrawBackground(Graphics g, System.Drawing.RectangleF rect, StyleInfo si) { LinearGradientBrush linGrBrush = null; SolidBrush sb = null; try { if (si.BackgroundGradientType != BackgroundGradientTypeEnum.None && !si.BackgroundGradientEndColor.IsEmpty && !si.BackgroundColor.IsEmpty) { Color c = si.BackgroundColor; Color ec = si.BackgroundGradientEndColor; switch (si.BackgroundGradientType) { case BackgroundGradientTypeEnum.LeftRight: linGrBrush = new LinearGradientBrush(rect, c, ec, LinearGradientMode.Horizontal); break; case BackgroundGradientTypeEnum.TopBottom: linGrBrush = new LinearGradientBrush(rect, c, ec, LinearGradientMode.Vertical); break; case BackgroundGradientTypeEnum.Center: linGrBrush = new LinearGradientBrush(rect, c, ec, LinearGradientMode.Horizontal); break; case BackgroundGradientTypeEnum.DiagonalLeft: linGrBrush = new LinearGradientBrush(rect, c, ec, LinearGradientMode.ForwardDiagonal); break; case BackgroundGradientTypeEnum.DiagonalRight: linGrBrush = new LinearGradientBrush(rect, c, ec, LinearGradientMode.BackwardDiagonal); break; case BackgroundGradientTypeEnum.HorizontalCenter: linGrBrush = new LinearGradientBrush(rect, c, ec, LinearGradientMode.Horizontal); break; case BackgroundGradientTypeEnum.VerticalCenter: linGrBrush = new LinearGradientBrush(rect, c, ec, LinearGradientMode.Vertical); break; default: break; } } if (linGrBrush != null) { g.FillRectangle(linGrBrush, rect); linGrBrush.Dispose(); } else if (!si.BackgroundColor.IsEmpty) { sb = new SolidBrush(si.BackgroundColor); g.FillRectangle(sb, rect); sb.Dispose(); } } finally { if (linGrBrush != null) { linGrBrush.Dispose(); } if (sb != null) { sb.Dispose(); } } return; }
private void DrawImageBackground(PageImage pi, StyleInfo si, Graphics g, RectangleF r) { Stream strm = null; System.Drawing.Image im = null; try { strm = new MemoryStream(pi.ImageData); im = System.Drawing.Image.FromStream(strm); RectangleF r2 = new RectangleF(r.Left + PixelsX(si.PaddingLeft), r.Top + PixelsY(si.PaddingTop), r.Width - PixelsX(si.PaddingLeft + si.PaddingRight), r.Height - PixelsY(si.PaddingTop + si.PaddingBottom)); int repeatX = 0; int repeatY = 0; switch (pi.Repeat) { case ImageRepeat.Repeat: repeatX = (int)Math.Floor(r2.Width / pi.SamplesW); repeatY = (int)Math.Floor(r2.Height / pi.SamplesH); break; case ImageRepeat.RepeatX: repeatX = (int)Math.Floor(r2.Width / pi.SamplesW); repeatY = 1; break; case ImageRepeat.RepeatY: repeatY = (int)Math.Floor(r2.Height / pi.SamplesH); repeatX = 1; break; case ImageRepeat.NoRepeat: default: repeatX = repeatY = 1; break; } //make sure the image is drawn at least 1 times repeatX = Math.Max(repeatX, 1); repeatY = Math.Max(repeatY, 1); float startX = r2.Left; float startY = r2.Top; Region saveRegion = g.Clip; Region clipRegion = new Region(g.Clip.GetRegionData()); clipRegion.Intersect(r2); g.Clip = clipRegion; for (int i = 0; i < repeatX; i++) { for (int j = 0; j < repeatY; j++) { float currX = startX + i * pi.SamplesW; float currY = startY + j * pi.SamplesH; g.DrawImage(im, new RectangleF(currX, currY, pi.SamplesW, pi.SamplesH)); } } g.Clip = saveRegion; } finally { if (strm != null) strm.Close(); if (im != null) im.Dispose(); } }
private void DoInstructions(Single recX, Single recY, Single recWidth, Single recHeight, Pen p,Single StartAngle,Single SweepAngle) { BorderStyleEnum ls = getLineStyle(p); switch (p.Brush.GetType().Name) { case "SolidBrush": System.Drawing.SolidBrush theBrush = (System.Drawing.SolidBrush)p.Brush; PagePie pl = new PagePie(); pl.StartAngle = StartAngle; pl.SweepAngle = SweepAngle; pl.X = X + recX * SCALEFACTOR; pl.Y = Y + recY * SCALEFACTOR; pl.W = recWidth * SCALEFACTOR; pl.H = recHeight * SCALEFACTOR; StyleInfo SI = new StyleInfo(); SI.Color = theBrush.Color; SI.BColorTop = SI.BColorBottom = SI.BColorLeft = SI.BColorRight = theBrush.Color; SI.BStyleTop = SI.BStyleBottom = SI.BStyleLeft = SI.BStyleRight = ls; SI.BWidthTop = SI.BWidthBottom = SI.BWidthLeft = SI.BWidthRight = p.Width * SCALEFACTOR; pl.SI = SI; items.Add(pl); break; default: break; } }
/// <summary> /// Add polygon /// </summary> internal void addPolygon(PointF[] points, StyleInfo styleInfo, string url) { //nothing to do if (styleInfo.BackgroundColor.IsEmpty) return; //get the fill color - could be a gradient or pattern etc ... Color color = styleInfo.BackgroundColor; addPoints(points); pdfContent.SetRGBColorFillF(color.R, color.G, color.B); pdfContent.ClosePathFillStroke(); }
/// <summary> /// Add curve /// </summary> private void addCurve(PointF[] points, StyleInfo styleInfo) { //do a spline curve or just do a line segment if (points.Length > 2) doCurve(points, getCurveTangents(points), styleInfo); else addLine(points[0].X, points[0].Y, points[1].X, points[1].Y, styleInfo); }
/// <summary> /// Add curve /// </summary> private void addCurve(float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4, StyleInfo styleInfo, string url) { if (styleInfo.BStyleTop != BorderStyleEnum.None) { switch (styleInfo.BStyleTop) { case BorderStyleEnum.Dashed: pdfContent.SetLineDash(new float[] { '3', '2' }, 0); break; case BorderStyleEnum.Dotted: pdfContent.SetLineDash(new float[] { '2' }, 0); break; case BorderStyleEnum.Solid: default: pdfContent.SetLineDash(new float[] { }, 0); break; } pdfContent.SetRGBColorStroke(styleInfo.BColorTop.R, styleInfo.BColorTop.G, styleInfo.BColorTop.B); } if (!styleInfo.BackgroundColor.IsEmpty) { pdfContent.SetRGBColorStrokeF(styleInfo.BackgroundColor.R, styleInfo.BackgroundColor.G, styleInfo.BackgroundColor.B); } pdfContent.CurveTo(x1, pageHeight - y1, x2, pageHeight - y1, x3, pageHeight - y3); if (styleInfo.BackgroundColor.IsEmpty) { pdfContent.ClosePathStroke(); } else { pdfContent.ClosePathFillStroke(); } }
/// <summary> /// Add ellipse /// </summary> private void addEllipse(float x, float y, float width, float height, StyleInfo styleInfo, string url) { if (styleInfo.BStyleTop != BorderStyleEnum.None) { switch (styleInfo.BStyleTop) { case BorderStyleEnum.Dashed: pdfContent.SetLineDash(new float[] { '3', '2' }, 0); break; case BorderStyleEnum.Dotted: pdfContent.SetLineDash(new float[] { '2' }, 0); break; case BorderStyleEnum.Solid: default: pdfContent.SetLineDash(new float[] { }, 0); break; } pdfContent.SetRGBColorStroke(styleInfo.BColorTop.R, styleInfo.BColorTop.G, styleInfo.BColorTop.B); } pdfContent.Ellipse(x, pageHeight - y, x + (width / 2.0f), y + (height / 2.0f)); if (!styleInfo.BackgroundColor.IsEmpty) pdfContent.SetRGBColorStrokeF(styleInfo.BackgroundColor.R, styleInfo.BackgroundColor.G, styleInfo.BackgroundColor.B); if (styleInfo.BackgroundColor.IsEmpty) pdfContent.ClosePathStroke(); else pdfContent.ClosePathFillStroke(); }
/// <summary> /// Add text at the X Y position; multiple lines handled /// </summary> private void addText(float x, float y, float width, float height, string[] textLines, StyleInfo styleInfo, float[] textWidths, bool wrap, string url, bool noClip, string tooltip) { RenderFont renderFont = RenderUtility.GetRenderFont(styleInfo); BaseFont baseFont = null; //convert the render font type to iTextSharp type int fontType = 0; switch (renderFont.Style) { case RenderFont.FontStyle.Bold: fontType = iTextSharp.text.Font.BOLD; break; case RenderFont.FontStyle.Italic: fontType = iTextSharp.text.Font.ITALIC; break; case RenderFont.FontStyle.BoldItalic: fontType = iTextSharp.text.Font.BOLDITALIC; break; default: fontType = iTextSharp.text.Font.NORMAL; break; } //get the index of the font name in the list font name int indexBaseFont = BaseFontNames.FindIndex(delegate(string _fontname) { return(_fontname == renderFont.FaceName + "_" + fontType); }); //if not found then add the new BaseFont if (indexBaseFont == -1) { //create a new font or a with a new type baseFont = FontFactory.GetFont(renderFont.FaceName, BaseFont.IDENTITY_H, 0, fontType).BaseFont; //add the font face name and font to the lists BaseFontNames.Add(renderFont.FaceName + "_" + fontType); BaseFonts.Add(baseFont); } else { baseFont = BaseFonts[indexBaseFont]; } //text alignment int align = 0; //first position x and y and the leading (usefull for all kind of justified text) float firstStartX = -1; float firstStartY = -1; float leading = -1; //chunks of text List <Chunk> chunks = new List <Chunk>(); //loop thru the lines of text for (int i = 0; i < textLines.Length; i++) { string text = textLines[i]; float textwidth = textWidths[i]; float startX = x + styleInfo.PaddingLeft; // TODO: handle tb_rl float startY = y + styleInfo.PaddingTop + (i * styleInfo.FontSize); // TODO: handle tb_rl if (styleInfo.WritingMode == WritingModeEnum.lr_tb) { //calculate the x position switch (styleInfo.TextAlign) { case TextAlignEnum.Center: if (width > 0) { startX = x + styleInfo.PaddingLeft + (width - styleInfo.PaddingLeft - styleInfo.PaddingRight) / 2 - textwidth / 2; align = Element.ALIGN_CENTER; } break; case TextAlignEnum.Right: if (width > 0) { startX = x + width - textwidth - styleInfo.PaddingRight - 2; align = Element.ALIGN_RIGHT; } break; case TextAlignEnum.Justified: case TextAlignEnum.JustifiedLine: case TextAlignEnum.JustifiedDottedLine: if (width > 0) { startX += 2; align = Element.ALIGN_JUSTIFIED; } break; case TextAlignEnum.Left: default: if (width > 0) { startX += 2; } align = Element.ALIGN_LEFT; break; } //calculate the y position switch (styleInfo.VerticalAlign) { case VerticalAlignEnum.Middle: if (height <= 0) { break; } //calculate the middle of the region startY = y + styleInfo.PaddingTop + (height - styleInfo.PaddingTop - styleInfo.PaddingBottom) / 2 - styleInfo.FontSize / 2; //now go up or down depending on which line if (textLines.Length == 1) { break; } //even number if (textLines.Length % 2 == 0) { startY = startY - ((textLines.Length / 2 - i) * styleInfo.FontSize) + styleInfo.FontSize / 2; } else { startY = startY - ((textLines.Length / 2 - i) * styleInfo.FontSize); } break; case VerticalAlignEnum.Bottom: if (height <= 0) { break; } startY = y + height - styleInfo.PaddingBottom - (styleInfo.FontSize * (textLines.Length - i)); break; case VerticalAlignEnum.Top: default: break; } } else { //move x in a little - it draws to close to the edge of the rectangle (25% of the font size seems to work!) and Center or right align vertical text startX += styleInfo.FontSize / 4; switch (styleInfo.TextAlign) { case TextAlignEnum.Center: if (height > 0) { startY = y + styleInfo.PaddingLeft + (height - styleInfo.PaddingLeft - styleInfo.PaddingRight) / 2 - textwidth / 2; } break; case TextAlignEnum.Right: if (width > 0) { startY = y + height - textwidth - styleInfo.PaddingRight; } break; case TextAlignEnum.Left: default: break; } } //mark the first x position for justify text if (firstStartX == -1) { firstStartX = startX; } //mark the first y position for justify text if (firstStartY == -1) { firstStartY = startY; } //mark the first leading height for justify text else if (leading == -1) { leading = startY - firstStartY; } //draw background rectangle if needed (only put out on the first line, since we do whole rectangle) if (!styleInfo.BackgroundColor.IsEmpty && height > 0 && width > 0 && i == 0) { addFillRectangle(x, y, width, height, styleInfo.BackgroundColor); } //set the clipping path, (Itext have no clip) if (height > 0 && width > 0) { pdfContent.SetRGBColorFill(styleInfo.Color.R, styleInfo.Color.G, styleInfo.Color.B); if (align == Element.ALIGN_JUSTIFIED) { chunks.Add(new Chunk(text)); } else { if (styleInfo.WritingMode == WritingModeEnum.lr_tb) { //if textline after measure with word break can fit just simple show Text if (width >= textwidth) { pdfContent.SaveState(); pdfContent.BeginText(); pdfContent.SetFontAndSize(baseFont, styleInfo.FontSize); //same fonts dont have nativelly bold so we could simulate that if (renderFont.SimulateBold) { pdfContent.SetTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL_STROKE); pdfContent.SetLineWidth(0.2f); } pdfContent.SetTextMatrix(startX, pageHeight - startY - styleInfo.FontSize); pdfContent.ShowText(text); pdfContent.EndText(); pdfContent.RestoreState(); } else { //else use Column text to wrap or clip (wrap: for example a text like an URL so word break is not working here //itextsharp ColumnText do the work for us) ColumnText columnText = new ColumnText(pdfContent); columnText.SetSimpleColumn(new Phrase(text, new iTextSharp.text.Font(baseFont, styleInfo.FontSize)), x + styleInfo.PaddingLeft, pageHeight - startY, x + width - styleInfo.PaddingRight, pageHeight - y - styleInfo.PaddingBottom - height, 10f, align); columnText.Go(); } } else { //not checked double rads = -283.0 / 180.0; double radsCos = Math.Cos(rads); double radsSin = Math.Sin(rads); pdfContent.BeginText(); pdfContent.SetFontAndSize(baseFont, styleInfo.FontSize); pdfContent.SetTextMatrix((float)radsCos, (float)radsSin, (float)-radsSin, (float)radsCos, startX, pageHeight - startY); pdfContent.ShowText(text); pdfContent.EndText(); } } //add URL if (url != null) { document.Add(new Annotation(x, pageHeight - y, height, width, url)); } //add tooltip if (tooltip != null) { document.Add(new Annotation(x, pageHeight - y, height, width, tooltip)); } } //handle underlining etc ... float maxX; switch (styleInfo.TextDecoration) { case TextDecorationEnum.Underline: maxX = width > 0 ? Math.Min(x + width, startX + textwidth) : startX + textwidth; addLine(startX, startY + styleInfo.FontSize + 1, maxX, startY + styleInfo.FontSize + 1, 1, styleInfo.Color, BorderStyleEnum.Solid); break; case TextDecorationEnum.LineThrough: maxX = width > 0 ? Math.Min(x + width, startX + textwidth) : startX + textwidth; addLine(startX, startY + (styleInfo.FontSize / 2) + 1, maxX, startY + (styleInfo.FontSize / 2) + 1, 1, styleInfo.Color, BorderStyleEnum.Solid); break; case TextDecorationEnum.Overline: maxX = width > 0 ? Math.Min(x + width, startX + textwidth) : startX + textwidth; addLine(startX, startY + 1, maxX, startY + 1, 1, styleInfo.Color, BorderStyleEnum.Solid); break; case TextDecorationEnum.None: default: break; } } //add text to justify if (chunks.Count > 0) { Paragraph paragraph = new Paragraph(); paragraph.Alignment = align; paragraph.Leading = leading; paragraph.Font = new iTextSharp.text.Font(baseFont, styleInfo.FontSize); //join all text (is necessary to justify alignment) foreach (Chunk chunk in chunks) { paragraph.Add(chunk); } //add separator for kind of justified alignments if (styleInfo.TextAlign == TextAlignEnum.JustifiedLine) { iTextSharp.text.pdf.draw.LineSeparator lineSeparator = new iTextSharp.text.pdf.draw.LineSeparator(); lineSeparator.Offset = 3f; lineSeparator.LineColor = new BaseColor(styleInfo.Color); paragraph.Add(new Chunk(lineSeparator)); } else if (styleInfo.TextAlign == TextAlignEnum.JustifiedDottedLine) { iTextSharp.text.pdf.draw.DottedLineSeparator dottedLineSeparator = new iTextSharp.text.pdf.draw.DottedLineSeparator(); dottedLineSeparator.Offset = 3f; dottedLineSeparator.LineColor = new BaseColor(styleInfo.Color); paragraph.Add(new Chunk(dottedLineSeparator)); } ColumnText columnText = new ColumnText(pdfContent); //start from the top of the column columnText.UseAscender = true; //width, y position from the bottom page (compensate 2 units), x position, 0 columnText.SetSimpleColumn(firstStartX, pageHeight - firstStartY - 2, firstStartX + width - styleInfo.PaddingRight, 0); columnText.AddElement(paragraph); columnText.Go(); } //add any required border addBorder(styleInfo, x, y, width, height); }
/// <summary> /// Add image /// </summary> private void addImage(StyleInfo styleInfo, float x, float y, float width, float height, RectangleF clipRectangle, byte[] image, string url, string tooltip) { //add the image with the zoom and position iTextSharp.text.Image pdfImge = iTextSharp.text.Image.GetInstance(image); pdfImge.ScaleAbsolute(width, height); pdfImge.SetAbsolutePosition(x, pageHeight - y - height); document.Add(pdfImge); //add url if (url != null) document.Add(new Annotation(x, pageHeight - y, height, width, url)); //add tooltip if (!string.IsNullOrEmpty(tooltip)) document.Add(new Annotation(x, pageHeight - y, height, width, tooltip)); //add any required border addBorder(styleInfo, x - styleInfo.PaddingLeft, y - styleInfo.PaddingTop, width + styleInfo.PaddingLeft + styleInfo.PaddingRight, height + styleInfo.PaddingTop + styleInfo.PaddingBottom); }
public static string[] MeasureString(PageText pt, Graphics g, out float[] width) { StyleInfo si = pt.SI; string s = pt.Text; System.Drawing.Font drawFont = null; StringFormat drawFormat = null; SizeF ms; string[] sa = null; width = null; try { // STYLE System.Drawing.FontStyle fs = 0; if (si.FontStyle == FontStyleEnum.Italic) { fs |= System.Drawing.FontStyle.Italic; } // WEIGHT switch (si.FontWeight) { case FontWeightEnum.Bold: case FontWeightEnum.Bolder: case FontWeightEnum.W500: case FontWeightEnum.W600: case FontWeightEnum.W700: case FontWeightEnum.W800: case FontWeightEnum.W900: fs |= System.Drawing.FontStyle.Bold; break; default: break; } drawFont = new System.Drawing.Font(StyleInfo.GetFontFamily(si.FontFamilyFull), si.FontSize, fs); drawFormat = new StringFormat(); drawFormat.Alignment = StringAlignment.Near; // Measure string // pt.NoClip indicates that this was generated by PageTextHtml Build. It has already word wrapped. if (pt.NoClip || pt.SI.WritingMode == WritingModeEnum.tb_rl) // TODO: support multiple lines for vertical text { ms = MeasureString(s, g, drawFont, drawFormat); width = new float[1]; width[0] = RSize.PointsFromPixels(g, ms.Width); // convert to points from pixels sa = new string[1]; sa[0] = s; return(sa); } // handle multiple lines; // 1) split the string into the forced line breaks (ie "\n and \r") // 2) foreach of the forced line breaks; break these into words and recombine s = s.Replace("\r\n", "\n"); // don't want this to result in double lines string[] flines = s.Split(lineBreak); List <string> lines = new List <string>(); List <float> lineWidths = new List <float>(); // remove the size reserved for left and right padding float ptWidth = pt.W - pt.SI.PaddingLeft - pt.SI.PaddingRight; if (ptWidth <= 0) { ptWidth = 1; } foreach (string tfl in flines) { string fl; if (tfl.Length > 0 && tfl[tfl.Length - 1] == ' ') { fl = tfl.TrimEnd(' '); } else { fl = tfl; } // Check if entire string fits into a line ms = MeasureString(fl, g, drawFont, drawFormat); float tw = RSize.PointsFromPixels(g, ms.Width); if (tw <= ptWidth) { // line fits don't need to break it down further lines.Add(fl); lineWidths.Add(tw); continue; } // Line too long; need to break into multiple lines // 1) break line into parts; then build up again keeping track of word positions string[] parts = fl.Split(wordBreak); // this is the maximum split of lines StringBuilder sb = new StringBuilder(fl.Length); CharacterRange[] cra = new CharacterRange[parts.Length]; for (int i = 0; i < parts.Length; i++) { int sc = sb.Length; // starting character sb.Append(parts[i]); // endding character if (i != parts.Length - 1) // last item doesn't need blank { sb.Append(" "); } int ec = sb.Length; CharacterRange cr = new CharacterRange(sc, ec - sc); cra[i] = cr; // add to character array } // 2) Measure the word locations within the line string wfl = sb.ToString(); WordStartFinish[] wordLocations = MeasureString(wfl, g, drawFont, drawFormat, cra); if (wordLocations == null) { continue; } // 3) Loop thru creating new lines as needed int startLoc = 0; CharacterRange crs = cra[startLoc]; CharacterRange cre = cra[startLoc]; float cwidth = wordLocations[0].end; // length of the first float bwidth = wordLocations[0].start; // characters need a little extra on start string ts; bool bLine = true; for (int i = 1; i < cra.Length; i++) { cwidth = wordLocations[i].end - wordLocations[startLoc].start + bwidth; if (cwidth > ptWidth) { // time for a new line cre = cra[i - 1]; ts = wfl.Substring(crs.First, cre.First + cre.Length - crs.First); lines.Add(ts); lineWidths.Add(wordLocations[i - 1].end - wordLocations[startLoc].start + bwidth); // Find the first non-blank character of the next line while (i < cra.Length && cra[i].Length == 1 && fl[cra[i].First] == ' ') { i++; } if (i < cra.Length) // any lines left? { // yes, continue on startLoc = i; crs = cre = cra[startLoc]; cwidth = wordLocations[i].end - wordLocations[startLoc].start + bwidth; } else // no, we can stop { bLine = false; } // bwidth = wordLocations[startLoc].start - wordLocations[startLoc - 1].end; } else { cre = cra[i]; } } if (bLine) { ts = fl.Substring(crs.First, cre.First + cre.Length - crs.First); lines.Add(ts); lineWidths.Add(cwidth); } } // create the final array from the Lists string[] la = lines.ToArray(); width = lineWidths.ToArray(); return(la); } finally { if (drawFont != null) { drawFont.Dispose(); } if (drawFormat != null) { drawFont.Dispose(); } } }
/// <summary> /// Add pie /// </summary> private void addPie(float x, float y, float width, float height, StyleInfo si, string url, string tooltip) { //add any required border addBorder(si, x, y, width, height); //add url if (url != null) document.Add(new Annotation(x, pageHeight - y, height, width, url)); //add tooltip if (!string.IsNullOrEmpty(tooltip)) document.Add(new Annotation(x, pageHeight - y, height, width, tooltip)); }
private PageImage BuildImage(Graphics g, string token, StyleInfo oldsi, PageText model) { PageTextHtmlCmdLexer hc = new PageTextHtmlCmdLexer(token.Substring(4)); Hashtable ht = hc.Lex(); string src = (string)ht["src"]; if (src == null || src.Length < 1) { return(null); } string alt = (string)ht["alt"]; string height = (string)ht["height"]; string width = (string)ht["width"]; string align = (string)ht["align"]; Stream strm = null; System.Drawing.Image im = null; PageImage pi = null; try { // Obtain the image stream if (src.StartsWith("http:") || src.StartsWith("file:") || src.StartsWith("https:")) { WebRequest wreq = WebRequest.Create(src); WebResponse wres = wreq.GetResponse(); strm = wres.GetResponseStream(); } else { strm = new FileStream(src, System.IO.FileMode.Open, FileAccess.Read); } im = System.Drawing.Image.FromStream(strm); int h = im.Height; int w = im.Width; MemoryStream ostrm = new MemoryStream(); ImageFormat imf; imf = ImageFormat.Jpeg; im.Save(ostrm, imf); byte[] ba = ostrm.ToArray(); ostrm.Close(); pi = new PageImage(imf, ba, w, h); pi.AllowSelect = false; pi.Page = this.Page; pi.HyperLink = model.HyperLink; pi.Tooltip = alt == null ? model.Tooltip : alt; pi.X = 0; pi.Y = 0; pi.W = RSize.PointsFromPixels(g, width != null? Convert.ToInt32(width): w); pi.H = RSize.PointsFromPixels(g, height != null? Convert.ToInt32(height): h); pi.SI = new StyleInfo(); } catch { pi = null; } finally { if (strm != null) { strm.Close(); } if (im != null) { im.Dispose(); } } return(pi); }
/// <summary> /// Add text at the X Y position; multiple lines handled /// </summary> private void addText(float x, float y, float width, float height, string[] textLines, StyleInfo styleInfo, float[] textWidths, bool wrap, string url, bool noClip, string tooltip) { RenderFont renderFont = RenderUtility.GetRenderFont(styleInfo); BaseFont baseFont = null; //convert the render font type to iTextSharp type int fontType = 0; switch (renderFont.Style) { case RenderFont.FontStyle.Bold: fontType = iTextSharp.text.Font.BOLD; break; case RenderFont.FontStyle.Italic: fontType = iTextSharp.text.Font.ITALIC; break; case RenderFont.FontStyle.BoldItalic: fontType = iTextSharp.text.Font.BOLDITALIC; break; default: fontType = iTextSharp.text.Font.NORMAL; break; } //get the index of the font name in the list font name int indexBaseFont = BaseFontNames.FindIndex(delegate(string _fontname) { return _fontname == renderFont.FaceName + "_" + fontType; }); //if not found then add the new BaseFont if (indexBaseFont == -1) { //create a new font or a with a new type baseFont = FontFactory.GetFont(renderFont.FaceName, BaseFont.IDENTITY_H, 0, fontType).BaseFont; //add the font face name and font to the lists BaseFontNames.Add(renderFont.FaceName + "_" + fontType); BaseFonts.Add(baseFont); } else baseFont = BaseFonts[indexBaseFont]; //text alignment int align = 0; //first position x and y and the leading (usefull for all kind of justified text) float firstStartX = -1; float firstStartY = -1; float leading = -1; //chunks of text List<Chunk> chunks = new List<Chunk>(); //loop thru the lines of text for (int i = 0; i < textLines.Length; i++) { string text = textLines[i]; float textwidth = textWidths[i]; float startX = x + styleInfo.PaddingLeft; // TODO: handle tb_rl float startY = y + styleInfo.PaddingTop + (i * styleInfo.FontSize); // TODO: handle tb_rl if (styleInfo.WritingMode == WritingModeEnum.lr_tb) { //calculate the x position switch (styleInfo.TextAlign) { case TextAlignEnum.Center: if (width > 0) { startX = x + styleInfo.PaddingLeft + (width - styleInfo.PaddingLeft - styleInfo.PaddingRight) / 2 - textwidth / 2; align = Element.ALIGN_CENTER; } break; case TextAlignEnum.Right: if (width > 0) { startX = x + width - textwidth - styleInfo.PaddingRight - 2; align = Element.ALIGN_RIGHT; } break; case TextAlignEnum.Justified: case TextAlignEnum.JustifiedLine: case TextAlignEnum.JustifiedDottedLine: if (width > 0) { startX += 2; align = Element.ALIGN_JUSTIFIED; } break; case TextAlignEnum.Left: default: if (width > 0) startX += 2; align = Element.ALIGN_LEFT; break; } //calculate the y position switch (styleInfo.VerticalAlign) { case VerticalAlignEnum.Middle: if (height <= 0) break; //calculate the middle of the region startY = y + styleInfo.PaddingTop + (height - styleInfo.PaddingTop - styleInfo.PaddingBottom) / 2 - styleInfo.FontSize / 2; //now go up or down depending on which line if (textLines.Length == 1) break; //even number if (textLines.Length % 2 == 0) startY = startY - ((textLines.Length / 2 - i) * styleInfo.FontSize) + styleInfo.FontSize / 2; else startY = startY - ((textLines.Length / 2 - i) * styleInfo.FontSize); break; case VerticalAlignEnum.Bottom: if (height <= 0) break; startY = y + height - styleInfo.PaddingBottom - (styleInfo.FontSize * (textLines.Length - i)); break; case VerticalAlignEnum.Top: default: break; } } else { //move x in a little - it draws to close to the edge of the rectangle (25% of the font size seems to work!) and Center or right align vertical text startX += styleInfo.FontSize / 4; switch (styleInfo.TextAlign) { case TextAlignEnum.Center: if (height > 0) startY = y + styleInfo.PaddingLeft + (height - styleInfo.PaddingLeft - styleInfo.PaddingRight) / 2 - textwidth / 2; break; case TextAlignEnum.Right: if (width > 0) startY = y + height - textwidth - styleInfo.PaddingRight; break; case TextAlignEnum.Left: default: break; } } //mark the first x position for justify text if (firstStartX == -1) firstStartX = startX; //mark the first y position for justify text if (firstStartY == -1) firstStartY = startY; //mark the first leading height for justify text else if (leading == -1) leading = startY - firstStartY; //draw background rectangle if needed (only put out on the first line, since we do whole rectangle) if (!styleInfo.BackgroundColor.IsEmpty && height > 0 && width > 0 && i == 0) addFillRectangle(x, y, width, height, styleInfo.BackgroundColor); //set the clipping path, (Itext have no clip) if (height > 0 && width > 0) { pdfContent.SetRGBColorFill(styleInfo.Color.R, styleInfo.Color.G, styleInfo.Color.B); if (align == Element.ALIGN_JUSTIFIED) chunks.Add(new Chunk(text)); else { if (styleInfo.WritingMode == WritingModeEnum.lr_tb) { //if textline after measure with word break can fit just simple show Text if (width >= textwidth) { pdfContent.SaveState(); pdfContent.BeginText(); pdfContent.SetFontAndSize(baseFont, styleInfo.FontSize); //same fonts dont have nativelly bold so we could simulate that if (renderFont.SimulateBold) { pdfContent.SetTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL_STROKE); pdfContent.SetLineWidth(0.2f); } pdfContent.SetTextMatrix(startX, pageHeight - startY - styleInfo.FontSize); pdfContent.ShowText(text); pdfContent.EndText(); pdfContent.RestoreState(); } else { //else use Column text to wrap or clip (wrap: for example a text like an URL so word break is not working here //itextsharp ColumnText do the work for us) ColumnText columnText = new ColumnText(pdfContent); columnText.SetSimpleColumn(new Phrase(text, new iTextSharp.text.Font(baseFont, styleInfo.FontSize)), x + styleInfo.PaddingLeft, pageHeight - startY, x + width - styleInfo.PaddingRight, pageHeight - y - styleInfo.PaddingBottom - height, 10f, align); columnText.Go(); } } else { //not checked double rads = -283.0 / 180.0; double radsCos = Math.Cos(rads); double radsSin = Math.Sin(rads); pdfContent.BeginText(); pdfContent.SetFontAndSize(baseFont, styleInfo.FontSize); pdfContent.SetTextMatrix((float)radsCos, (float)radsSin, (float)-radsSin, (float)radsCos, startX, pageHeight - startY); pdfContent.ShowText(text); pdfContent.EndText(); } } //add URL if (url != null) document.Add(new Annotation(x, pageHeight - y, height, width, url)); //add tooltip if (tooltip != null) document.Add(new Annotation(x, pageHeight - y, height, width, tooltip)); } //handle underlining etc ... float maxX; switch (styleInfo.TextDecoration) { case TextDecorationEnum.Underline: maxX = width > 0 ? Math.Min(x + width, startX + textwidth) : startX + textwidth; addLine(startX, startY + styleInfo.FontSize + 1, maxX, startY + styleInfo.FontSize + 1, 1, styleInfo.Color, BorderStyleEnum.Solid); break; case TextDecorationEnum.LineThrough: maxX = width > 0 ? Math.Min(x + width, startX + textwidth) : startX + textwidth; addLine(startX, startY + (styleInfo.FontSize / 2) + 1, maxX, startY + (styleInfo.FontSize / 2) + 1, 1, styleInfo.Color, BorderStyleEnum.Solid); break; case TextDecorationEnum.Overline: maxX = width > 0 ? Math.Min(x + width, startX + textwidth) : startX + textwidth; addLine(startX, startY + 1, maxX, startY + 1, 1, styleInfo.Color, BorderStyleEnum.Solid); break; case TextDecorationEnum.None: default: break; } } //add text to justify if (chunks.Count > 0) { Paragraph paragraph = new Paragraph(); paragraph.Alignment = align; paragraph.Leading = leading; paragraph.Font = new iTextSharp.text.Font(baseFont, styleInfo.FontSize); //join all text (is necessary to justify alignment) foreach (Chunk chunk in chunks) paragraph.Add(chunk); //add separator for kind of justified alignments if (styleInfo.TextAlign == TextAlignEnum.JustifiedLine) { iTextSharp.text.pdf.draw.LineSeparator lineSeparator = new iTextSharp.text.pdf.draw.LineSeparator(); lineSeparator.Offset = 3f; lineSeparator.LineColor = new BaseColor(styleInfo.Color); paragraph.Add(new Chunk(lineSeparator)); } else if (styleInfo.TextAlign == TextAlignEnum.JustifiedDottedLine) { iTextSharp.text.pdf.draw.DottedLineSeparator dottedLineSeparator = new iTextSharp.text.pdf.draw.DottedLineSeparator(); dottedLineSeparator.Offset = 3f; dottedLineSeparator.LineColor = new BaseColor(styleInfo.Color); paragraph.Add(new Chunk(dottedLineSeparator)); } ColumnText columnText = new ColumnText(pdfContent); //start from the top of the column columnText.UseAscender = true; //width, y position from the bottom page (compensate 2 units), x position, 0 columnText.SetSimpleColumn(firstStartX, pageHeight - firstStartY - 2, firstStartX + width - styleInfo.PaddingRight, 0); columnText.AddElement(paragraph); columnText.Go(); } //add any required border addBorder(styleInfo, x, y, width, height); }
private void HandleStyleFontSize(StyleInfo si, string size) { try { int i = size.IndexOf("pt"); if (i > 0) { size = size.Remove(i, 2); float n = (float)Convert.ToDouble(size); if (size[0] == '+') { si.FontSize += n; } else { si.FontSize = n; } return; } i = size.IndexOf("%"); if (i > 0) { size = size.Remove(i, 1); float n = (float)Convert.ToDouble(size); si.FontSize = n * si.FontSize; return; } switch (size) { case "xx-small": si.FontSize = 6; break; case "x-small": si.FontSize = 8; break; case "small": si.FontSize = 10; break; case "medium": si.FontSize = 12; break; case "large": si.FontSize = 14; break; case "x-large": si.FontSize = 16; break; case "xx-large": si.FontSize = 18; break; case "1": si.FontSize = 8; break; case "2": si.FontSize = 10; break; case "3": si.FontSize = 12; break; case "4": si.FontSize = 14; break; case "5": si.FontSize = 18; break; case "6": si.FontSize = 24; break; case "7": si.FontSize = 36; break; } } catch {} // lots of user errors will cause an exception; ignore return; }
private void DoInstructions(Font f, StringFormat sf, Brush br, Single recX, Single recY, Single recWidth, Single recHeight, String Text) { Color Col = Color.Black; if (br.GetType().Name.Equals("SolidBrush")) { SolidBrush sb = (SolidBrush)br; Col = sb.Color; } PageText pt = new PageText(Text); pt.X = X + recX * SCALEFACTOR; pt.Y = Y + recY * SCALEFACTOR; pt.W = recWidth * SCALEFACTOR; pt.H = recHeight * SCALEFACTOR; StyleInfo SI = new StyleInfo(); SI.Color = Col; SI.Direction = DirectionEnum.LTR; SI.FontFamily = f.Name; SI.FontSize = f.Size * SCALEFACTOR; if (f.Italic) {SI.FontStyle = FontStyleEnum.Italic;} if (f.Bold) { SI.FontWeight = FontWeightEnum.Bold; } if (f.Underline) { SI.TextDecoration = TextDecorationEnum.Underline; } if (sf.LineAlignment == StringAlignment.Center) { SI.TextAlign = TextAlignEnum.Center; } else if (sf.LineAlignment == StringAlignment.Far) { SI.TextAlign = TextAlignEnum.Right; } if (sf.Alignment == StringAlignment.Center) { SI.VerticalAlign = VerticalAlignEnum.Middle; } else if (sf.Alignment == StringAlignment.Far) { SI.VerticalAlign = VerticalAlignEnum.Bottom; } if ((sf.FormatFlags & StringFormatFlags.DirectionVertical) == StringFormatFlags.DirectionVertical) { SI.WritingMode = WritingModeEnum.tb_rl; } else { SI.WritingMode = WritingModeEnum.lr_tb; } pt.SI = SI; items.Add(pt); //r = Math.Round((r / 255), 3); //g = Math.Round((g / 255), 3); //b = Math.Round((b / 255), 3); //string pdfFont = fonts.GetPdfFont(f.Name); ////need a graphics object... //Bitmap bm = new Bitmap(1, 1); //Graphics gr = Graphics.FromImage(bm); //Font scaleFont = new Font(f.Name, (f.Size * ScaleY) * 1.5f, f.Style, f.Unit); //SizeF TextSize = gr.MeasureString(Text.Substring(0, Text.Length), scaleFont, (int)(recWidth * ScaleX), sf); //float textwidth = TextSize.Width; //float textHeight = TextSize.Height; //float startX = X + recX * ScaleX; //float startY = Y + Height - recY * ScaleY - (scaleFont.Size); //if ((sf.FormatFlags & StringFormatFlags.DirectionVertical) != StringFormatFlags.DirectionVertical) //{ // if (sf.LineAlignment == StringAlignment.Center) // { // startX = (startX + (recWidth * ScaleX) / 2) - (textwidth / 4); // } // else if (sf.LineAlignment == StringAlignment.Far) // { // startX = (startX + recWidth * ScaleX) - (textwidth / 1.8f); // } //} //else //{ // startX += textwidth / 4; // if (sf.LineAlignment == StringAlignment.Center) // { // startY = (startY - (recHeight * ScaleY) / 2) + (textHeight / 4); // } // else if (sf.LineAlignment == StringAlignment.Far) // { // startY = (startY - recHeight * ScaleY) + (textHeight / 1.8f); // } //} //Lines.Append("\r\nq\t"); //string newtext = PdfUtility.UTF16StringQuoter(Text); //if ((sf.FormatFlags & StringFormatFlags.DirectionVertical) != StringFormatFlags.DirectionVertical) //{ // Lines.AppendFormat(System.Globalization.NumberFormatInfo.InvariantInfo, // "\r\nBT/{0} {1} Tf\t{5} {6} {7} rg\t{2} {3} Td \t({4}) Tj\tET\tQ\t", // pdfFont, scaleFont.SizeInPoints, startX, startY, newtext, r, g, b); //} //else //{ // double rads = -283.0 / 180.0; // double radsCos = Math.Cos(rads); // double radsSin = Math.Sin(rads); // Lines.AppendFormat(System.Globalization.NumberFormatInfo.InvariantInfo, // "\r\nBT/{0} {1} Tf\t{5} {6} {7} rg\t{8} {9} {10} {11} {2} {3} Tm \t({4}) Tj\tET\tQ\t", // pdfFont, scaleFont.SizeInPoints, startX, startY, newtext, r, g, b, // radsCos, radsSin, -radsSin, radsCos); //} }
private void DoInstructions(Font f, StringFormat sf, Brush br, Single recX, Single recY, Single recWidth, Single recHeight, String Text) { Color Col = Color.Black; if (br.GetType().Name.Equals("SolidBrush")) { SolidBrush sb = (SolidBrush)br; Col = sb.Color; } PageText pt = new PageText(Text); pt.X = X + recX * SCALEFACTOR; pt.Y = Y + recY * SCALEFACTOR; pt.W = recWidth * SCALEFACTOR; pt.H = recHeight * SCALEFACTOR; StyleInfo SI = new StyleInfo(); SI.Color = Col; SI.Direction = DirectionEnum.LTR; SI.FontFamily = f.Name; SI.FontSize = f.Size * SCALEFACTOR; if (f.Italic) { SI.FontStyle = FontStyleEnum.Italic; } if (f.Bold) { SI.FontWeight = FontWeightEnum.Bold; } if (f.Underline) { SI.TextDecoration = TextDecorationEnum.Underline; } if (sf.LineAlignment == StringAlignment.Center) { SI.TextAlign = TextAlignEnum.Center; } else if (sf.LineAlignment == StringAlignment.Far) { SI.TextAlign = TextAlignEnum.Right; } if (sf.Alignment == StringAlignment.Center) { SI.VerticalAlign = VerticalAlignEnum.Middle; } else if (sf.Alignment == StringAlignment.Far) { SI.VerticalAlign = VerticalAlignEnum.Bottom; } if ((sf.FormatFlags & StringFormatFlags.DirectionVertical) == StringFormatFlags.DirectionVertical) { SI.WritingMode = WritingModeEnum.tb_rl; } else { SI.WritingMode = WritingModeEnum.lr_tb; } pt.SI = SI; items.Add(pt); //r = Math.Round((r / 255), 3); //g = Math.Round((g / 255), 3); //b = Math.Round((b / 255), 3); //string pdfFont = fonts.GetPdfFont(f.Name); ////need a graphics object... //Bitmap bm = new Bitmap(1, 1); //Graphics gr = Graphics.FromImage(bm); //Font scaleFont = new Font(f.Name, (f.Size * ScaleY) * 1.5f, f.Style, f.Unit); //SizeF TextSize = gr.MeasureString(Text.Substring(0, Text.Length), scaleFont, (int)(recWidth * ScaleX), sf); //float textwidth = TextSize.Width; //float textHeight = TextSize.Height; //float startX = X + recX * ScaleX; //float startY = Y + Height - recY * ScaleY - (scaleFont.Size); //if ((sf.FormatFlags & StringFormatFlags.DirectionVertical) != StringFormatFlags.DirectionVertical) //{ // if (sf.LineAlignment == StringAlignment.Center) // { // startX = (startX + (recWidth * ScaleX) / 2) - (textwidth / 4); // } // else if (sf.LineAlignment == StringAlignment.Far) // { // startX = (startX + recWidth * ScaleX) - (textwidth / 1.8f); // } //} //else //{ // startX += textwidth / 4; // if (sf.LineAlignment == StringAlignment.Center) // { // startY = (startY - (recHeight * ScaleY) / 2) + (textHeight / 4); // } // else if (sf.LineAlignment == StringAlignment.Far) // { // startY = (startY - recHeight * ScaleY) + (textHeight / 1.8f); // } //} //Lines.Append("\r\nq\t"); //string newtext = PdfUtility.UTF16StringQuoter(Text); //if ((sf.FormatFlags & StringFormatFlags.DirectionVertical) != StringFormatFlags.DirectionVertical) //{ // Lines.AppendFormat(System.Globalization.NumberFormatInfo.InvariantInfo, // "\r\nBT/{0} {1} Tf\t{5} {6} {7} rg\t{2} {3} Td \t({4}) Tj\tET\tQ\t", // pdfFont, scaleFont.SizeInPoints, startX, startY, newtext, r, g, b); //} //else //{ // double rads = -283.0 / 180.0; // double radsCos = Math.Cos(rads); // double radsSin = Math.Sin(rads); // Lines.AppendFormat(System.Globalization.NumberFormatInfo.InvariantInfo, // "\r\nBT/{0} {1} Tf\t{5} {6} {7} rg\t{8} {9} {10} {11} {2} {3} Tm \t({4}) Tj\tET\tQ\t", // pdfFont, scaleFont.SizeInPoints, startX, startY, newtext, r, g, b, // radsCos, radsSin, -radsSin, radsCos); //} }