private double PrintServicesListSummary(XGraphics printer, double totalCost, double summaryStartY, bool includeVat) { double summaryRowHeight = 0; double subTotal = totalCost * 0.8f; double vatValue = totalCost * 0.2f; XPen strokePen = new XPen(XColor.FromArgb(100, 100, 100)); XFont font = new XFont("Times", 12, XFontStyle.Bold); string sDecimalFormat = "###,###.00"; XSize size = XSize.Empty; if (includeVat) { // /* Print Subtotal */ printer.DrawRectangle(strokePen, new XRect(COL2_START_X, summaryStartY, COL2_WIDTH, summaryRowHeight)); size = printer.MeasureString("Sub Total : ", font); printer.DrawString("Sub Total : ", font, brush, new XPoint(COL2_START_X - size.Width, summaryStartY + summaryRowHeight * 1 / 4), XStringFormats.CenterLeft); printer.DrawString("$ " + subTotal.ToString(sDecimalFormat), font, brush, new XPoint(COL2_START_X + 10, summaryStartY + summaryRowHeight * 1 / 4), XStringFormats.CenterLeft); summaryStartY += summaryRowHeight; // /* End Print Subtotal */ // /* Print VAT */ //contents.addRect(firstRectEndX, summaryStartY, secondRectEndX, summaryRowHeight); //contents.stroke(); //summaryPrinter.putTextToTheRight(summaryLabelRightX, summaryStartY + summaryRowHeight * 1 / 4, "Vat : "); //summaryPrinter.putTextToTheRight(docEndX - 10, summaryStartY + summaryRowHeight * 1 / 4, "$ " + vatValue.ToString(sDecimalFormat)); summaryStartY += summaryRowHeight; // /* End Print VAT */ } /* Print Total */ size = printer.MeasureString("Sub Total : ", font); summaryRowHeight = size.Height * 3; printer.DrawRectangle(strokePen, new XRect(COL2_START_X, summaryStartY - summaryRowHeight * 1 / 4, COL2_WIDTH, summaryRowHeight)); printer.DrawString("Total : ", font, brush, new XPoint(COL2_START_X - size.Width, summaryStartY + summaryRowHeight * 1 / 4), XStringFormats.CenterLeft); printer.DrawString("$ " + totalCost.ToString(sDecimalFormat), font, brush, new XPoint(COL2_START_X + 10, summaryStartY + summaryRowHeight * 1 / 4), XStringFormats.CenterLeft); summaryStartY += summaryRowHeight; /* End Print Total */ return(summaryStartY); }
private void DrawItemOvertime(XGraphics g, double curX, TimeSpan duration, TimeSpan allowedDuration) { if (_stdTimeFont == null) { throw new InvalidOperationException(nameof(_stdTimeFont)); } var overtime = allowedDuration - duration; var inTheRed = (int)overtime.TotalSeconds < 0; var inTheGreen = (int)overtime.TotalSeconds >= 0; var spotOn = (int)overtime.TotalSeconds == 0; var prefix = string.Empty; if (!spotOn) { prefix = inTheGreen ? "-" : "+"; } var s = $"{prefix} {Math.Abs(overtime.Minutes):D2}:{Math.Abs(overtime.Seconds):D2}"; var sz = g.MeasureString(s, _durationFont); var startX = _rightXIndent - sz.Width; var dotsStartX = curX + _stdTimeFont.Height; var dotsLength = startX - _stdTimeFont.Height - dotsStartX; var sb = new StringBuilder("."); var dotsSz = g.MeasureString(sb.ToString(), _smallTimeFont); while (dotsSz.Width < dotsLength) { sb.Append('.'); dotsSz = g.MeasureString(sb.ToString(), _smallTimeFont); } dotsStartX = startX - _stdTimeFont.Height - dotsSz.Width; g.DrawString(sb.ToString(), _smallTimeFont, XBrushes.LightGray, new XPoint(dotsStartX, _currentY)); var inTheRedBrush = inTheRed ? _redBrush : _blackBrush; var brush = inTheGreen ? _greenBrush : inTheRedBrush; g.DrawString(s, _durationFont, brush, new XPoint(startX, _currentY)); }
private List <string> ParseaCampo(string Parrafo, XFont font, double dRango, XGraphics graph) { List <string> retvalue = new List <string>(); var size = graph.MeasureString(Parrafo, font); int a = 1; int rango = 100; if (size.Width > dRango) { int contador = 1; int lastspace = 0; double auxSize; while (a < rango) { if (Parrafo.Substring(contador, 1) == " ") { lastspace = contador; } var size1 = graph.MeasureString(Parrafo.Substring(0, contador), font); auxSize = size1.Width; contador++; a = (int)(auxSize); } retvalue.Add(Parrafo.Substring(0, lastspace)); a = 1; contador = 1; string subparrafo = Parrafo.Substring(lastspace).TrimStart(); int maxlenght = subparrafo.Length; lastspace = 0; while ((a < rango) && (contador < maxlenght)) { var size1 = graph.MeasureString(subparrafo.Substring(0, contador), font); auxSize = size1.Width; contador++; a = (int)(auxSize); } retvalue.Add(subparrafo.Substring(0, contador)); } else { retvalue.Add(Parrafo); } return(retvalue); }
private double PrintTermsAndConditions(XGraphics printer, double startY, Invoice invoice) { string termsAndConditions = "Quotation Valid for 21 Days. Quotation Valid for 21 Days. Quotation Valid for 21 Days. Quotation Valid for 21 Days. Quotation Valid for 21 Days. Quotation Valid for 21 Days. Quotation Valid for 21 Days. "; XBrush brush = XBrushes.Black; XFont termsAndConditionsHeaderFont = new XFont("Times", 10, XFontStyle.Bold); XFont termsAndConditionsValueFont = new XFont("Times", 9, XFontStyle.Regular); string sStr = "Terms & Conditions"; startY += printer.MeasureString(sStr, termsAndConditionsHeaderFont).Height * 2; printer.DrawString(sStr, termsAndConditionsHeaderFont, brush, new XPoint(DOCUMENT_LEFT_MARGIN, startY)); //startY += printer.MeasureString(sStr, termsAndConditionsHeaderFont).Height * 2.2; List <string> footerLines = new List <string>(); List <string> breaks = (termsAndConditions.Split("\n")).ToList(); foreach (string br in breaks) { StringBuilder sb = new StringBuilder(); foreach (string s in br.Split(" ")) { XSize size = printer.MeasureString(sb.ToString() + s + " ", termsAndConditionsValueFont); if (size.Width > DOCUMENT_PRINTABLE_WIDTH) { footerLines.Add(sb.ToString()); sb = new StringBuilder(); sb.Append(" "); } sb.Append(s).Append(" "); } if (sb.Length >= 1) { footerLines.Add(sb.ToString()); } } // double yPos = startY - rowHeight + rowHeight * 2 / 5; foreach (string line in footerLines) { startY += printer.MeasureString(line, termsAndConditionsValueFont).Height * 1.1; printer.DrawString(line, termsAndConditionsValueFont, brush, new XPoint(DOCUMENT_LEFT_MARGIN, startY)); } return(startY); }
public override void Process(iPDF owner, ref PdfDocument Document, ref PdfPage Page, ref XGraphics Graphics) { if (!string.IsNullOrEmpty(Data)) { var watermark = Data; XSize size = Graphics.MeasureString(watermark, owner.Font); // Define a rotation transformation at the center of the page Graphics.TranslateTransform(Page.Width / 2, Page.Height / 2); Graphics.RotateTransform(-Math.Atan(Page.Height / Page.Width) * 180 / Math.PI); Graphics.TranslateTransform(-Page.Width / 2, -Page.Height / 2); // Create a graphical path XGraphicsPath path = new XGraphicsPath(); // Add the text to the path path.AddString(watermark, owner.Font.FontFamily, XFontStyle.BoldItalic, 150, new XPoint(0, (Page.Height / 2) - 80), XStringFormats.TopLeft); // Create a dimmed red pen and brush XPen pen = new XPen(XColor.FromArgb(50, 75, 0, 130), 3); XBrush brush = new XSolidBrush(XColor.FromArgb(50, 106, 90, 205)); // Stroke the outline of the path Graphics.DrawPath(pen, brush, path); } }
private static void DrawTextRectangle(XGraphics g, XStringFormat rectFormat, string str, XRect rcf, XFont f) { int startL = 0; int startP = 0; int endP = 0; int lastEndP = 0; XPoint point = rcf.Location; XSize textSize; str = str.Trim(); while (endP < str.Length - 1) { endP = FindNextSpaceFit(g, str, rcf, f, startP); if (endP <= startP) { return; } string subs = str.Substring(startP, endP - startP); textSize = g.MeasureString(subs, f); g.DrawString(subs, f, Brushes.Black, point.X, point.Y + textSize.Height); point.Y += textSize.Height * 1.2; startP = endP + 1; } }
private void PrintHeader(XGraphics printer, Invoice invoice) { XFont textFont = new XFont("Times", 12, XFontStyle.Regular); XSize size = printer.MeasureString(invoice.Number, textFont); printer.DrawString(invoice.Number, textFont, XBrushes.DarkSlateGray, new XPoint(DOCUMENT_WIDTH - size.Width - DOCUMENT_RIGHT_MARGIN, DOCUMENT_TOP_MARGIN - size.Height * 2)); }
private void DrawCounselItem(XGraphics g, TimeSpan counselDuration) { if (_itemFont == null) { throw new InvalidOperationException(nameof(_itemFont)); } if (_itemTitleFont == null) { throw new InvalidOperationException(nameof(_itemTitleFont)); } _currentY -= 2 * (double)_itemFont.Height / 5; var title = Resources.COUNSEL; var sz = g.MeasureString(title, _itemFont); var x = _leftIndent + (2 * _itemTitleFont.Height); g.DrawString(title, _itemFont, _grayBrush, new XPoint(x, _currentY)); counselDuration = NormaliseCounselDuration(counselDuration); DrawItemOvertime(g, x + sz.Width, counselDuration, TimeSpan.FromSeconds(60)); _currentY += (3 * (double)_itemTitleFont.Height) / 2; }
/// <summary> /// Enhanced measure string function for PdfSharp Xgraphics /// wich take to account lineBreaks to calculate the real string /// height in a rectagle /// </summary> /// <param name="gfx"></param> /// <param name="text">Text to measure</param> /// <param name="maxWitdh">Maximum allowed width</param> /// <returns></returns> public static XSize MeasureStringExact(this XGraphics gfx, string content, XFont font, double maxWidth) { //Split by hard line break var contents = content.Split(new List <string> { "\n", "\r\n" }.ToArray(), StringSplitOptions.None); Func <string, XFont, XSize> measPdfSharp = (ct, ft) => { var size = gfx.MeasureString(ct, ft); var lineSpace = font.GetHeight(); var cellSpace = font.FontFamily.GetLineSpacing(ft.Style); var cellLeading = cellSpace - font.FontFamily.GetCellAscent(ft.Style) - font.FontFamily.GetCellDescent(ft.Style); var leading = lineSpace * cellLeading / cellSpace; size.Height += leading; if (size.Width > maxWidth) { var nbLine = gfx.GetSplittedLineCount(ct, ft, maxWidth); size.Height = (nbLine * lineSpace) + leading; size.Width = maxWidth; } return(size); }; var sizes = contents.Select(c => measPdfSharp(c, font)); return(new XSize(sizes.Max(w => w.Width), sizes.Sum(h => h.Height))); }
public static void DrawMultilineString(XGraphics gfx, string text, XFont font, XRect rect, Alignment alignment) { var size = gfx.MeasureString(text, font, XStringFormats.Center); rect = new XRect(rect.X, rect.Y + (rect.Height - size.Height) / 2, rect.Width, 0); var parts = text.Split('\n'); var height = gfx.MeasureString(parts[0], font, XStringFormats.Center).Height; rect.Height = height; for (int i = 0; i < parts.Length; ++i) { DrawString(gfx, parts[i], font, rect, alignment); rect = new XRect(rect.X, rect.Y + height, rect.Width, rect.Height); } }
private void GenerateAttachmentPage(XGraphics gfx, Image image, int index) { index = index + 1; //======================================================================================================================================// //Add attachment header var font = new XFont("Calibri", 15.0, XFontStyle.Bold); var stringSize = gfx.MeasureString("Attachment " + index.ToString(), font); var rect = new XRect(Margin, Margin, PageWidthLandscape - Margin * 2, font.GetHeight()); CreateTextFormatter(gfx, XParagraphAlignment.Left).DrawString("Attachment " + index.ToString(), font, TextBrush, rect, XStringFormats.TopLeft); //======================================================================================================================================// //Add attachment image XImage ximg = XImage.FromGdiPlusImage(image); //double width, height; if (gfx.PageSize.Width > gfx.PageSize.Height) { //Landscape gfx.DrawImage(ximg, PageWidthLandscape / 2 - ximg.PointWidth / 2, PageWidth / 2 - ximg.PointHeight / 2); } else { //Portrait gfx.DrawImage(ximg, PageWidth / 2 - ximg.PointWidth / 2, PageWidthLandscape / 2 - ximg.PointHeight / 2); } }
private static void DesenharCelula(XGraphics gfx, int inicioCelula, double topoTabela, int larguraCelula, double alturaLinha, XPen pen, string texto, bool titulo = false, bool tituloCentralizado = false) { var baseCelula = topoTabela + alturaLinha; gfx.DrawLine(pen, inicioCelula, topoTabela, larguraCelula, topoTabela); gfx.DrawLine(pen, inicioCelula, topoTabela, inicioCelula, baseCelula); gfx.DrawLine(pen, inicioCelula, baseCelula, larguraCelula, baseCelula); gfx.DrawLine(pen, larguraCelula, topoTabela, larguraCelula, baseCelula); if (string.IsNullOrWhiteSpace(texto) == false) { var font = new XFont("Verdana", 12, (titulo ? XFontStyle.Bold : XFontStyle.Regular)); var format = new XStringFormat { Alignment = (tituloCentralizado ? XStringAlignment.Center : XStringAlignment.Near), LineAlignment = XLineAlignment.BaseLine }; var tx = new XTextFormatter(gfx); if (tituloCentralizado) { var textMeasure = gfx.MeasureString(texto, font); gfx.DrawString(texto, font, XBrushes.Black, ((double)larguraCelula / 2), topoTabela + textMeasure.Height, format); } else { tx.DrawString(texto, font, XBrushes.Black, new XRect(new XPoint(inicioCelula + 5, topoTabela + 5), new XPoint(larguraCelula, baseCelula))); } } }
private static void DesenharTabela(XGraphics gfx, UsuarioCertificadoCertame certificadoUsuario, PdfPage pagina) { var pen = new XPen(XColor.FromName("black")); double topoTabela = 250; DesenharCelula(gfx, 10, topoTabela, 220, 20, pen, "Área", true); DesenharCelula(gfx, 220, topoTabela, 440, 20, pen, "Situação de Comparecimento", true); DesenharCelula(gfx, 440, topoTabela, 500, 20, pen, "Nota", true); DesenharCelula(gfx, 500, topoTabela, 585, 20, pen, "Situação", true); topoTabela += 20; DesenharCelula(gfx, 10, topoTabela, 220, 20, pen, certificadoUsuario.CertificadoCertame.NomeCertificado); DesenharCelula(gfx, 220, topoTabela, 440, 20, pen, certificadoUsuario.Situacao?.GetDescription()); DesenharCelula(gfx, 440, topoTabela, 500, 20, pen, certificadoUsuario.Nota?.ToString("0.00") ?? "0.00"); DesenharCelula(gfx, 500, topoTabela, 585, 20, pen, $"{certificadoUsuario.Status.GetDescription()}"); var medidaJustificativa = gfx.MeasureString(certificadoUsuario.Justificativa ?? " ", new XFont("Verdana", 12)); var alturaJustificativa = medidaJustificativa.Height * Math.Ceiling(medidaJustificativa.Width / 585); topoTabela = pagina.Height - 50 - alturaJustificativa; DesenharCelula(gfx, 10, topoTabela, 585, 20, pen, "Resultado da apresentação de justificativa à ausência no dia da prova", true, true); topoTabela += 20; DesenharCelula(gfx, 10, topoTabela, 585, alturaJustificativa, pen, certificadoUsuario.Justificativa); }
public void MeasureText(XGraphics gfx, int number) { const XFontStyle style = XFontStyle.Regular; XFont font = new XFont("Times New Roman", 95, style); const string text = "Hallo"; const double x = 20, y = 100; XSize size = gfx.MeasureString(text, font); double lineSpace = font.GetHeight(gfx); int cellSpace = font.FontFamily.GetLineSpacing(style); int cellAscent = font.FontFamily.GetCellAscent(style); int cellDescent = font.FontFamily.GetCellDescent(style); int cellLeading = cellSpace - cellAscent - cellDescent; // Get effective ascent double ascent = lineSpace * cellAscent / cellSpace; gfx.DrawRectangle(XBrushes.Bisque, x, y - ascent, size.Width, ascent); // Get effective descent double descent = lineSpace * cellDescent / cellSpace; gfx.DrawRectangle(XBrushes.LightGreen, x, y, size.Width, descent); // Get effective leading double leading = lineSpace * cellLeading / cellSpace; gfx.DrawRectangle(XBrushes.Yellow, x, y + descent, size.Width, leading); // Draw text half transparent XColor color = XColors.DarkSlateBlue; color.A = 0.6; gfx.DrawString(text, font, new XSolidBrush(color), x, y); }
/* * Draws the text and returns a new rect with reduced height that fits under the text and within the rect. */ public static XRect DrawString(XGraphics gfx, string text, XFont font, XRect rect, XStringFormat format, double maxWidth = 0) { if (text == null) { text = string.Empty; } if (maxWidth == 0) { maxWidth = rect.Width; } var lines = text.Split(new char[] { ' ' }, 2); XSize size = gfx.MeasureString(text, font, format); if (size.Width > maxWidth && lines.Count() > 1 && format != XStringFormats.Center) { foreach (var line in lines) { rect = DrawString(gfx, line, font, rect, format); } return(rect); } gfx.DrawString(text, font, XBrushes.Black, rect, format); return(new XRect(rect.Left, rect.Top + size.Height, rect.Width, rect.Height - size.Height)); }
private void MeasureText(XGraphics gfx, int number) { base.BeginBox(gfx, number, "Measure Text"); XFont xFont = new XFont("Times New Roman", 95.0, XFontStyle.Regular); XSize xSize = gfx.MeasureString("Hallo", xFont); double height = xFont.GetHeight(gfx); int lineSpacing = xFont.FontFamily.GetLineSpacing(XFontStyle.Regular); int cellAscent = xFont.FontFamily.GetCellAscent(XFontStyle.Regular); int cellDescent = xFont.FontFamily.GetCellDescent(XFontStyle.Regular); int num = lineSpacing - cellAscent - cellDescent; double num2 = height * (double)cellAscent / (double)lineSpacing; gfx.DrawRectangle(XBrushes.Bisque, 20.0, 100.0 - num2, xSize.Width, num2); double num3 = height * (double)cellDescent / (double)lineSpacing; gfx.DrawRectangle(XBrushes.LightGreen, 20.0, 100.0, xSize.Width, num3); double height2 = height * (double)num / (double)lineSpacing; gfx.DrawRectangle(XBrushes.Yellow, 20.0, 100.0 + num3, xSize.Width, height2); XColor darkSlateBlue = XColors.DarkSlateBlue; darkSlateBlue.A = 0.6; gfx.DrawString("Hallo", xFont, new XSolidBrush(darkSlateBlue), 20.0, 100.0); base.EndBox(gfx); }
public void PostaviWathermark(string nazivKompanije, PdfPage strana) { XGraphics gfx = XGraphics.FromPdfPage(strana, XGraphicsPdfPageOptions.Prepend); XFont font = new XFont("Times New Roman", 26, XFontStyle.Bold); XTextFormatter textFormatter = new XTextFormatter(gfx); var size = gfx.MeasureString("PDFSharp", font); gfx.TranslateTransform(strana.Width / 2, strana.Height / 2); gfx.RotateTransform(-Math.Atan(strana.Height / strana.Width) * 180 / Math.PI); gfx.TranslateTransform(-strana.Width / 2, -strana.Height / 2); var format = new XStringFormat(); format.Alignment = XStringAlignment.Near; format.LineAlignment = XLineAlignment.Near; XBrush brush = new XSolidBrush(XColor.FromArgb(128, 141, 184, 224)); gfx.DrawString(nazivKompanije.ToUpper(), font, brush, new XPoint((strana.Width - size.Width) / 2, (strana.Height - size.Height) / 2), format); gfx.Dispose(); }
private static void FixTableSize(Table table) { XGraphics graphics = XGraphics.CreateMeasureContext(new XSize(2000, 2000), XGraphicsUnit.Point, XPageDirection.Downwards); var fontSize = table.Document.Styles["Table"].Font.Size.Value; var gdiFont = new PdfSharp.Drawing.XFont("Arial", fontSize); for (int j = 0; j < table.Columns.Count; j++) { double columnWidth = 0; for (int i = 0; i < table.Rows.Count; i++) { foreach (Paragraph paragraph in table[i, j].Elements.OfType <Paragraph>()) { string contents = string.Empty; foreach (DocumentObject paragraphElement in paragraph.Elements) { if (paragraphElement is MigraDoc.DocumentObjectModel.Text) { contents += (paragraphElement as MigraDoc.DocumentObjectModel.Text).Content; } else if (paragraphElement is MigraDoc.DocumentObjectModel.Hyperlink) { contents += (paragraphElement as MigraDoc.DocumentObjectModel.Hyperlink).Name; } } XSize size = graphics.MeasureString(contents, gdiFont); columnWidth = Math.Max(columnWidth, size.Width); } } table.Columns[j].Width = Unit.FromPoint(columnWidth) + 5; } }
public static void DrawLabel(XGraphics g, string text, PointF labelPos, XFont font, XBrush brush, LabelStyle labelStyle) { using (RenderUtil.SaveState(g)) { XTextFormatter tf = new XTextFormatter(g); tf.Alignment = XParagraphAlignment.Center; XMatrix matrix = new XMatrix(); matrix.TranslatePrepend(labelPos.X, labelPos.Y); matrix.ScalePrepend(1.0f / Astrometrics.ParsecScaleX, 1.0f / Astrometrics.ParsecScaleY); if (labelStyle.Uppercase) { text = text.ToUpper(); } if (labelStyle.Wrap) { text = text.Replace(' ', '\n'); } matrix.TranslatePrepend(labelStyle.Translation.X, labelStyle.Translation.Y); matrix.RotatePrepend(labelStyle.Rotation); matrix.ScalePrepend(labelStyle.Scale.Width, labelStyle.Scale.Height); g.MultiplyTransform(matrix, XMatrixOrder.Prepend); XSize size = g.MeasureString(text, font); size.Width *= 2; // prevent cut-off e.g. when rotated XRect bounds = new XRect(-size.Width / 2, -size.Height / 2, size.Width, size.Height); tf.DrawString(text, font, brush, bounds); } }
PdfPage CreateWaterMark(PdfPage page, string watermark) { // Variation 1: Draw watermark as text string Gfx.Dispose(); // Get an XGraphics object for drawing beneath the existing content XGraphics gfx = XGraphics.FromPdfPage(page, XGraphicsPdfPageOptions.Prepend); // Get the size (in point) of the text XSize size = gfx.MeasureString(watermark, font); // Define a rotation transformation at the center of the page gfx.TranslateTransform(10, -400); // Create a string format XStringFormat format = new XStringFormat(); format.Alignment = XStringAlignment.Near; format.LineAlignment = XLineAlignment.Near; // Create a dimmed red brush XBrush brush = new XSolidBrush(XColor.FromArgb(128, 255, 0, 0)); // Draw the string gfx.DrawString(watermark, font, brush, new XPoint((page.Width - size.Width) / 2, (page.Height - size.Height) / 2), format); gfx.Dispose(); Gfx = XGraphics.FromPdfPage(Page); return(page); }
/// <summary> /// Calculates the space used for the axis title. /// </summary> internal override void Format() { XGraphics gfx = this.rendererParms.Graphics; AxisTitleRendererInfo atri = ((AxisRendererInfo)this.rendererParms.RendererInfo).axisTitleRendererInfo; if (atri.AxisTitleText != "") { XSize size = gfx.MeasureString(atri.AxisTitleText, atri.AxisTitleFont); if (atri.AxisTitleOrientation != 0) { XPoint[] points = new XPoint[2]; points[0].X = 0; points[0].Y = 0; points[1].X = size.Width; points[1].Y = size.Height; XMatrix matrix = new XMatrix(); //XMatrix.Identity; matrix.RotatePrepend(-atri.AxisTitleOrientation); matrix.TransformPoints(points); size.Width = Math.Abs(points[1].X - points[0].X); size.Height = Math.Abs(points[1].Y - points[0].Y); } atri.X = 0; atri.Y = 0; atri.Height = size.Height; atri.Width = size.Width; } }
/// <summary> /// Calculates the space used by the legend entry. /// </summary> internal override void Format() { XGraphics gfx = _rendererParms.Graphics; LegendEntryRendererInfo leri = (LegendEntryRendererInfo)_rendererParms.RendererInfo; // Initialize leri.MarkerArea.Width = MaxLegendMarkerWidth; leri.MarkerArea.Height = MaxLegendMarkerHeight; leri.MarkerSize = new XSize(); leri.MarkerSize.Width = leri.MarkerArea.Width; leri.MarkerSize.Height = leri.MarkerArea.Height; if (leri._seriesRendererInfo._series._chartType == ChartType.Line) { leri.MarkerArea.Width *= 3; } leri.Width = leri.MarkerArea.Width; leri.Height = leri.MarkerArea.Height; if (leri.EntryText != "") { leri.TextSize = gfx.MeasureString(leri.EntryText, leri._legendRendererInfo.Font); if (leri._seriesRendererInfo._series._chartType == ChartType.Line) { leri.MarkerSize.Width = leri._seriesRendererInfo._markerRendererInfo.MarkerSize.Value; leri.MarkerArea.Width = Math.Max(3 * leri.MarkerSize.Width, leri.MarkerArea.Width); } leri.MarkerArea.Height = Math.Min(leri.MarkerArea.Height, leri.TextSize.Height); leri.MarkerSize.Height = Math.Min(leri.MarkerSize.Height, leri.TextSize.Height); leri.Width = leri.TextSize.Width + leri.MarkerArea.Width + SpacingBetweenMarkerAndText; leri.Height = leri.TextSize.Height; } }
static void watermarkprint(XGraphics gfx, PdfPage page, XFont font) { string watermark = "TestME"; // Get the size (in point) of the text XSize size = gfx.MeasureString(watermark, font); // Define a rotation transformation at the center of the page gfx.TranslateTransform(page.Width / 2, page.Height / 2); gfx.RotateTransform(-Math.Atan(page.Height / page.Width) * 180 / Math.PI); gfx.TranslateTransform(-page.Width / 2, -page.Height / 2); // Create a string format XStringFormat format = new XStringFormat(); format.Alignment = XStringAlignment.Near; format.LineAlignment = XLineAlignment.Near; // Create a dimmed red brush XBrush brush = new XSolidBrush(XColor.FromArgb(60, 128, 125, 123)); // Draw the string gfx.DrawString(watermark, font, brush, new XPoint((page.Width - size.Width) / 2, (page.Height - size.Height) / 2), format); }
/// <summary> /// Calculates the space used by the data labels. /// </summary> internal override void Format() { ChartRendererInfo cri = (ChartRendererInfo)this.rendererParms.RendererInfo; foreach (SeriesRendererInfo sri in cri.seriesRendererInfos) { if (sri.dataLabelRendererInfo == null) continue; XGraphics gfx = this.rendererParms.Graphics; sri.dataLabelRendererInfo.Entries = new DataLabelEntryRendererInfo[sri.pointRendererInfos.Length]; int index = 0; foreach (ColumnRendererInfo column in sri.pointRendererInfos) { DataLabelEntryRendererInfo dleri = new DataLabelEntryRendererInfo(); if (sri.dataLabelRendererInfo.Type != DataLabelType.None) { if (sri.dataLabelRendererInfo.Type == DataLabelType.Value) dleri.Text = column.point.value.ToString(sri.dataLabelRendererInfo.Format); else if (sri.dataLabelRendererInfo.Type == DataLabelType.Percent) throw new InvalidOperationException(PSCSR.PercentNotSupportedByColumnDataLabel); if (dleri.Text.Length > 0) dleri.Size = gfx.MeasureString(dleri.Text, sri.dataLabelRendererInfo.Font); } sri.dataLabelRendererInfo.Entries[index++] = dleri; } } CalcPositions(); }
public void DrawRightAlign(string yourString, XFont font, XBrush brush, double HigheshHorizontalPos, double verticalPos) { XSize textSize = gfx.MeasureString(yourString, font); long pixLength = Convert.ToInt64(textSize.Width); gfx.DrawString(yourString, font, brush, HigheshHorizontalPos - pixLength, verticalPos); }
private void RenderTextInBox(XFont font, XGraphics gfx, TemplateBox box, double fx, double fy, string str, XRect space, XStringFormat align) { var boxLeft = box.Left * fx; var boxWidth = box.Width * fx; var boxHeight = box.Height * fy; var size = gfx.MeasureString(str, font); if (box.ShrinkToFit && box.WrapText && (size.Width > boxWidth || size.Height > boxHeight)) // try to change the string to match box aspect { var altFont = ShrinkFontAndWrapStringToFit(str, boxWidth, boxHeight, gfx, font, out var lines); RenderWrappedLines(altFont, gfx, box, fy, align, lines, boxLeft, boxWidth); } else if (box.WrapText && size.Width > boxWidth) { WrapStringToFit(SplitByWhitespace(str), boxWidth, gfx, font, out var lines); RenderWrappedLines(font, gfx, box, fy, align, lines, boxLeft, boxWidth); } else if (box.ShrinkToFit && (size.Width > boxWidth || size.Height > boxHeight)) { var altFont = ShrinkFontToFit(str, boxWidth, boxHeight, gfx, font, size); gfx.DrawString(str, altFont, XBrushes.Black, space, align); } else { gfx.DrawString(str, font, XBrushes.Black, space, align); } }
private static int CalculateFontSize(string text, XRect adjustedBounds, XGraphics gfx) { int fontSizeGuess = Math.Max(1, (int)(adjustedBounds.Height)); var measuredBoundsForGuess = gfx.MeasureString(text, new XFont("Times New Roman", fontSizeGuess, XFontStyle.Regular)); double adjustmentFactor = adjustedBounds.Width / measuredBoundsForGuess.Width; int adjustedFontSize = Math.Max(1, (int)Math.Round(fontSizeGuess * adjustmentFactor)); return adjustedFontSize; }
private XSize DrawDurationString(XGraphics g, TimeSpan duration, double curX, XBrush textBrush) { var durStr = $"{(int)duration.TotalMinutes:D2}:{duration.Seconds:D2}"; var szDur = g.MeasureString(durStr, _durationFont); g.DrawString(durStr, _durationFont, textBrush, new XPoint(curX, _currentY)); return(szDur); }
/// <summary> /// Draw a multi-line string as it would be drawn by GDI+. /// Compensates for issues and draw-vs-PDF differences in PDFsharp. /// </summary> /// <param name="graphics">The graphics with which to draw.</param> /// <param name="font">The font with which to draw.</param> /// <param name="brush">The brush with which to draw.</param> /// <param name="pos">The position at which to draw.</param> /// <param name="size">The size to which to limit the drawn text; or Vector.Zero for no limit.</param> /// <param name="format">The string format to use.</param> /// <param name="maxObjects"></param> /// <param name="text">The text to draw, which may contain line breaks.</param> /// <remarks> /// PDFsharp cannot currently render multi-line text to PDF files; it comes out as single line. /// This method simulates standard Graphics.DrawString() over PDFsharp. /// It always has the effect of StringFormatFlags.LineLimit (which PDFsharp does not support). /// </remarks> public Rect Draw(XGraphics graphics, Font font, Brush brush, Vector pos, Vector size, XStringFormat format) { // do a quick test to see if text is going to get drawn at the same size as last time; // if so, assume we don't need to recompute our layout for that reason. var sizeChecker = graphics.MeasureString("M q", font); if (sizeChecker != m_sizeChecker || pos != m_pos || m_size != size || m_requestedFormat.Alignment != format.Alignment || m_requestedFormat.LineAlignment != format.LineAlignment || m_requestedFormat.FormatFlags != format.FormatFlags) { m_invalidLayout = true; } m_sizeChecker = sizeChecker; if (m_invalidLayout) { // something vital has changed; rebuild our cached layout data RebuildCachedLayout(graphics, font, ref pos, ref size, format); m_invalidLayout = false; } var state = graphics.Save(); var textRect = new RectangleF(pos.X, pos.Y, size.X, size.Y); if (size != Vector.Zero) { graphics.IntersectClip(textRect); } // disable smoothing whilst rendering text; // visually this is no different, but is faster var smoothingMode = graphics.SmoothingMode; graphics.SmoothingMode = XSmoothingMode.HighSpeed; var origin = m_origin; foreach (string t in m_lines) { if (size.Y > 0 && size.Y < m_lineHeight) { break; // not enough remaining vertical space for a whole line } var line = t; graphics.SmoothingMode = XSmoothingMode.HighQuality; graphics.DrawString(line, font, brush, origin.X, origin.Y, m_actualFormat); origin += m_delta; size.Y -= m_lineHeight; } graphics.SmoothingMode = smoothingMode; graphics.Restore(state); var actualTextRect = new Rect(pos.X, m_origin.Y, size.X, m_lineHeight * m_lines.Count); return(actualTextRect); }
private void DrawWaterMark(int wx, int wy, string wText, XFont wFont, Color wColor) { XSize sf = gfx.MeasureString(wText, wFont); gfx.TranslateTransform(wx / 2, wy / 2); //double Agle = -Math.Atan(wy / wx) * 180 / Math.PI; //gfx.RotateTransform((float)Agle); //gfx.TranslateTransform(-wx / 2, -wy / 2); XStringFormat wformat = new XStringFormat(); wformat.Alignment = XStringAlignment.Near; wformat.LineAlignment = XLineAlignment.Near; // XBrush wbrush = new XSolidBrush(Color.FromArgb(20, Color.Black)); XBrush wbrush = new XSolidBrush(Color.FromArgb(20, wColor)); wx = (int)(wx - sf.Width) / 2; wy = (int)(wy - sf.Height) / 2; XPoint Point_xy = new XPoint(wx, wy); //gfx.DrawString(wText, wFont, wbrush, Point_xy, wformat); // OUTLINED METHOD // System.Drawing.Drawing2D.GraphicsPath path = new System.Drawing.Drawing2D.GraphicsPath(); // StringFormat wformat2 = new StringFormat(); // wformat2.Alignment = StringAlignment.Near; // wformat2.LineAlignment = StringAlignment.Near; Point Point_xy2 = new Point(wx, wy); // path.AddString(wText, new FontFamily("Arial"), (int)FontStyle.Italic, 120, Point_xy2, wformat2); // Pen pen = new Pen(Color.FromArgb(64,Color.Black), 3); //gfx.Graphics.DrawPath(pen, path); XGraphicsPath path = new XGraphicsPath(); path.AddString(wText, wFont.FontFamily, XFontStyle.Italic, 103, Point_xy2, wformat); Pen pen = new Pen(Color.FromArgb(64, wColor), 3); //e.Graphics.DrawPath(pen, path); gfx.DrawPath(pen, path); }