void RenderTextAlignment(XGraphics gfx) { gfx.TranslateTransform(15, 20); XRect rect = new XRect(0, 0, 250, 140); XFont font = new XFont("Verdana", 10); XBrush brush = XBrushes.Purple; XStringFormat format = new XStringFormat(); gfx.DrawRectangle(XPens.YellowGreen, rect); gfx.DrawLine(XPens.YellowGreen, rect.Width / 2, 0, rect.Width / 2, rect.Height); gfx.DrawLine(XPens.YellowGreen, 0, rect.Height / 2, rect.Width, rect.Height / 2); #if true gfx.DrawString("TopLeft", font, brush, rect, format); format.Alignment = XStringAlignment.Center; gfx.DrawString("TopCenter", font, brush, rect, format); format.Alignment = XStringAlignment.Far; gfx.DrawString("TopRight", font, brush, rect, format); format.LineAlignment = XLineAlignment.Center; format.Alignment = XStringAlignment.Near; gfx.DrawString("CenterLeft", font, brush, rect, format); format.Alignment = XStringAlignment.Center; gfx.DrawString("Center", font, brush, rect, format); format.Alignment = XStringAlignment.Far; gfx.DrawString("CenterRight", font, brush, rect, format); format.LineAlignment = XLineAlignment.Far; format.Alignment = XStringAlignment.Near; gfx.DrawString("BottomLeft", font, brush, rect, format); format.Alignment = XStringAlignment.Center; gfx.DrawString("BottomCenter", font, brush, rect, format); format.Alignment = XStringAlignment.Far; gfx.DrawString("BottomRight", font, brush, rect, format); #else format.Alignment = XStringAlignment.Far; gfx.DrawString("TopRight", font, brush, rect, format); #endif }
static GraphicsAdapter() { _stringFormat = new XStringFormat(); _stringFormat.Alignment = XStringAlignment.Near; _stringFormat.LineAlignment = XLineAlignment.Near; _stringFormat.FormatFlags = XStringFormatFlags.MeasureTrailingSpaces; }
/// <summary> /// Adds a text string to this path. /// </summary> public void AddString(string s, XFontFamily family, XFontStyle style, double emSize, XRect layoutRect, XStringFormat format) { if (s == null) { throw new ArgumentNullException("s"); } if (family == null) { throw new ArgumentNullException("family"); } if (format == null) { format = XStringFormats.Default(); } if (format.LineAlignment == XLineAlignment.BaseLine && layoutRect.Height != 0) { throw new InvalidOperationException( "DrawString: With XLineAlignment.BaseLine the height of the layout rectangle must be 0."); } if (s.Length == 0) { return; } XFont font = new XFont(family.Name, emSize, style); DiagnosticsHelper.HandleNotImplemented("XGraphicsPath.AddString"); }
/// <summary> /// Measure string directly from font data. /// </summary> public static XSize MeasureString(string text, XFont font, XStringFormat stringFormat_notyetused) { XSize size = new XSize(); OpenTypeDescriptor descriptor = FontDescriptorCache.GetOrCreateDescriptorFor(font) as OpenTypeDescriptor; if (descriptor != null) { // Height is the sum of ascender and descender. size.Height = (descriptor.Ascender + descriptor.Descender) * font.Size / font.UnitsPerEm; Debug.Assert(descriptor.Ascender > 0); bool symbol = descriptor.FontFace.cmap.symbol; int length = text.Length; int width = 0; for (int idx = 0; idx < length; idx++) { char ch = text[idx]; // HACK: Unclear what to do here. if (ch < 32) { continue; } if (char.IsLowSurrogate(ch)) { continue; // Don't process high surrorgate. Low will process this char } if (symbol) { // Remap ch for symbol fonts. ch = (char)(ch | (descriptor.FontFace.os2.usFirstCharIndex & 0xFF00)); // @@@ refactor // Used | instead of + because of: http://pdfsharp.codeplex.com/workitem/15954 } uint glyphIndex; if (char.IsHighSurrogate(ch)) { glyphIndex = descriptor.CharCodeToGlyphIndex(ch, text[idx + 1]); } else { glyphIndex = descriptor.CharCodeToGlyphIndex(ch); } width += descriptor.GlyphIndexToWidth(glyphIndex); } // What? size.Width = width * font.Size * (font.Italic ? 1 : 1) / descriptor.UnitsPerEm; size.Width = width * font.Size / descriptor.UnitsPerEm; // Adjust bold simulation. if ((font.GlyphTypeface.StyleSimulations & XStyleSimulations.BoldSimulation) == XStyleSimulations.BoldSimulation) { // Add 2% of the em-size for each character. // Unsure how to deal with white space. Currently count as regular character. size.Width += length * font.Size * Const.BoldEmphasis; } } Debug.Assert(descriptor != null, "No OpenTypeDescriptor."); return(size); }
// ...took a look at the source code of WPF. About 50 classes and several 10,000 lines of code // deal with that what colloquial is called 'fonts'. // So let's start simple. /// <summary> /// Simple measure string function. /// </summary> public static XSize MeasureString(string text, XFont font, XStringFormat stringFormat) { XSize size = new XSize(); OpenTypeDescriptor descriptor = FontDescriptorStock.Global.CreateDescriptor(font) as OpenTypeDescriptor; if (descriptor != null) { size.Height = (descriptor.Ascender + Math.Abs(descriptor.Descender)) * font.Size / font.unitsPerEm; Debug.Assert(descriptor.Ascender > 0); bool symbol = descriptor.fontData.cmap.symbol; int length = text.Length; int width = 0; for (int idx = 0; idx < length; idx++) { char ch = text[idx]; int glyphIndex = 0; if (symbol) { glyphIndex = ch + (descriptor.fontData.os2.usFirstCharIndex & 0xFF00); // @@@ glyphIndex = descriptor.CharCodeToGlyphIndex((char)glyphIndex); } else glyphIndex = descriptor.CharCodeToGlyphIndex(ch); //double width = descriptor.GlyphIndexToEmfWidth(glyphIndex, font.Size); //size.Width += width; width += descriptor.GlyphIndexToWidth(glyphIndex); } size.Width = width * font.Size * (font.Italic ? 1 : 1) / descriptor.UnitsPerEm; } Debug.Assert(descriptor != null, "No OpenTypeDescriptor."); return size; }
// ----- AddString ---------------------------------------------------------------------------- /// <summary> /// Adds a text string to this path. /// </summary> public void AddString(string s, XFontFamily family, XFontStyle style, double emSize, XPoint origin, XStringFormat format) { try { DiagnosticsHelper.HandleNotImplemented("XGraphicsPath.AddString"); } catch { throw; } }
public static bool Equals(XStringFormat format1, XStringFormat format2) { if ((format1 == null && format2 == null)) { return(true); } else if ((format1 != null && format2 == null) || (format2 != null && format1 == null)) { return(false); } return(format1.Alignment == format2.Alignment && format1.LineAlignment == format2.LineAlignment); }
/// <summary> /// Measure string directly from font data. /// </summary> public static XSize MeasureString(string text, XFont font, XStringFormat stringFormat) { XSize size = new XSize(); OpenTypeDescriptor descriptor = FontDescriptorCache.GetOrCreateDescriptorFor(font) as OpenTypeDescriptor; if (descriptor != null) { // Height is the sum of ascender and descender. size.Height = (descriptor.Ascender + descriptor.Descender) * font.Size / font.UnitsPerEm; Debug.Assert(descriptor.Ascender > 0); bool symbol = descriptor.FontFace.cmap.symbol; int length = text.Length; int width = 0; for (int idx = 0; idx < length; idx++) { char ch = text[idx]; // HACK: Unclear what to do here. if (ch < 32) continue; if (symbol) { // Remap ch for symbol fonts. ch = (char)(ch | (descriptor.FontFace.os2.usFirstCharIndex & 0xFF00)); // @@@ refactor // Used | instead of + because of: http://pdfsharp.codeplex.com/workitem/15954 } int glyphIndex = descriptor.CharCodeToGlyphIndex(ch); width += descriptor.GlyphIndexToWidth(glyphIndex); } // What? size.Width = width * font.Size * (font.Italic ? 1 : 1) / descriptor.UnitsPerEm; size.Width = width * font.Size / descriptor.UnitsPerEm; // Adjust bold simulation. if ((font.GlyphTypeface.StyleSimulations & XStyleSimulations.BoldSimulation) == XStyleSimulations.BoldSimulation) { // Add 2% of the em-size for each character. // Unsure how to deal with white space. Currently count as regular character. size.Width += length * font.Size * Const.BoldEmphasis; } } Debug.Assert(descriptor != null, "No OpenTypeDescriptor."); return size; }
/// <summary> /// Shows how to align text in the layout rectangle. /// </summary> void DrawTextAlignment(XGraphics gfx, int number) { BeginBox(gfx, number, "Text Alignment"); XRect rect = new XRect(0, 0, 250, 140); XFont font = new XFont("Verdana", 10); XBrush brush = XBrushes.Purple; XStringFormat format = new XStringFormat(); gfx.DrawRectangle(XPens.YellowGreen, rect); gfx.DrawLine(XPens.YellowGreen, rect.Width / 2, 0, rect.Width / 2, rect.Height); gfx.DrawLine(XPens.YellowGreen, 0, rect.Height / 2, rect.Width, rect.Height / 2); gfx.DrawString("TopLeft", font, brush, rect, format); format.Alignment = XStringAlignment.Center; gfx.DrawString("TopCenter", font, brush, rect, format); format.Alignment = XStringAlignment.Far; gfx.DrawString("TopRight", font, brush, rect, format); format.LineAlignment = XLineAlignment.Center; format.Alignment = XStringAlignment.Near; gfx.DrawString("CenterLeft", font, brush, rect, format); format.Alignment = XStringAlignment.Center; gfx.DrawString("Center", font, brush, rect, format); format.Alignment = XStringAlignment.Far; gfx.DrawString("CenterRight", font, brush, rect, format); format.LineAlignment = XLineAlignment.Far; format.Alignment = XStringAlignment.Near; gfx.DrawString("BottomLeft", font, brush, rect, format); format.Alignment = XStringAlignment.Center; gfx.DrawString("BottomCenter", font, brush, rect, format); format.Alignment = XStringAlignment.Far; gfx.DrawString("BottomRight", font, brush, rect, format); EndBox(gfx); }
/// <summary> /// Draws the page title and footer. /// </summary> public void DrawTitle(PdfPage page, XGraphics gfx, string title) { XRect rect = new XRect(new XPoint(), gfx.PageSize); rect.Inflate(-10, -15); XFont font = new XFont("Verdana", 14, XFontStyle.Bold); gfx.DrawString(title, font, XBrushes.MidnightBlue, rect, XStringFormats.TopCenter); rect.Offset(0, 5); font = new XFont("Verdana", 8, XFontStyle.Italic); XStringFormat format = new XStringFormat(); format.Alignment = XStringAlignment.Near; format.LineAlignment = XLineAlignment.Far; gfx.DrawString("Created with " + PdfSharp.ProductVersionInfo.Producer, font, XBrushes.DarkOrchid, rect, format); font = new XFont("Verdana", 8); format.Alignment = XStringAlignment.Center; gfx.DrawString(Program.s_document.PageCount.ToString(), font, XBrushes.DarkOrchid, rect, format); Program.s_document.Outlines.Add(title, page, true); }
/// <summary> /// Erstellt eine Wassserzeichen /// </summary> /// <param name="watermarkText">Text fuer das Wasserzeichen</param> /// <param name="source">Quelle PDF Stream</param> /// <param name="target">Ziel PDF Stream</param> public static void WriteWatermark(string watermarkText, MemoryStream source, MemoryStream target) { PdfDocument originalPdf = PdfSharp.Pdf.IO.PdfReader.Open(source, PdfSharp.Pdf.IO.PdfDocumentOpenMode.Modify); foreach (PdfPage page in originalPdf.Pages) { var gfx = XGraphics.FromPdfPage(page, XGraphicsPdfPageOptions.Prepend); var font = new XFont("Verdana", 120); var size = gfx.MeasureString(watermarkText, font); var brush = new XSolidBrush(XColor.FromArgb(128, 255, 0, 0)); gfx.TranslateTransform(page.Width.Value / 2, page.Height.Value / 2); gfx.RotateTransform(-Math.Atan(page.Height.Value / page.Width.Value) * 180 / Math.PI); gfx.TranslateTransform(-page.Width.Value / 2, -page.Height.Value / 2); var format = new XStringFormat(); format.Alignment = XStringAlignment.Near; format.LineAlignment = XLineAlignment.Near; gfx.DrawString(watermarkText, font, brush, new XPoint((page.Width.Value - size.Width) / 2, (page.Height.Value - size.Height) / 2), format); } originalPdf.Save(target, false); }
/// <summary> /// Draws the specified text string. /// </summary> public void DrawString(string s, XFont font, XBrush brush, XPoint point, XStringFormat format) { DrawString(s, font, brush, new XRect(point.X, point.Y, 0, 0), format); }
/// <summary> /// Draws the specified text string. /// </summary> public void DrawString(string s, XFont font, XBrush brush, double x, double y, XStringFormat format) { DrawString(s, font, brush, new XRect(x, y, 0, 0), format); }
private void RebuildCachedLayout(XGraphics graphics, Font font, ref Vector pos, ref Vector size, XStringFormat baseFormat) { // for diagnostic purposes ++s_rebuildCount; // store current settings to help us tell if we need a rebuild next time around m_requestedFormat = new XStringFormat(); m_requestedFormat.Alignment = baseFormat.Alignment; m_requestedFormat.FormatFlags = baseFormat.FormatFlags; m_requestedFormat.LineAlignment = baseFormat.LineAlignment; m_actualFormat = new XStringFormat(); m_actualFormat.Alignment = baseFormat.Alignment; m_actualFormat.FormatFlags = baseFormat.FormatFlags; m_actualFormat.LineAlignment = baseFormat.LineAlignment; m_pos = pos; m_size = size; var text = m_text; if (text.IndexOf('\n') == -1 && size.X > 0 && size.Y > 0 && graphics.MeasureString(text, font).Width > size.X) { // wrap single-line text to fit in rectangle // measure a space, countering the APIs unwillingness to measure spaces var spaceLength = (float)(graphics.MeasureString("M M", font).Width - graphics.MeasureString("M", font).Width * 2); var words = new List<Word>(); foreach (var word in text.Split(' ')) { if (words.Count != 0) { words.Add(new Word(" ", spaceLength)); } words.Add(new Word(word, (float)graphics.MeasureString(word, font).Width)); } var lineLength = 0.0f; var total = string.Empty; var line = string.Empty; foreach (var word in words) { if (word.Text != " " && word.Length > Math.Max(0, size.X - lineLength) && lineLength > 0) { if (line.Length > 0) { if (total.Length > 0) { total += "\n"; } total += line; lineLength = word.Length + spaceLength; line = word.Text; } } else { line += word.Text; lineLength += word.Length + spaceLength; } } if (line.Length > 0) { if (total.Length > 0) { total += "\n"; } total += line; } text = total; } m_lineHeight = font.GetHeight(); m_lines.Clear(); m_lines.AddRange(text.Split('\n')); switch (m_actualFormat.LineAlignment) { case XLineAlignment.Near: default: m_origin = pos; m_delta = new Vector(0, m_lineHeight); break; case XLineAlignment.Far: m_origin = new Vector(pos.X, pos.Y + size.Y - m_lineHeight); if (size.Y > 0) { var count = m_lines.Count; while (m_origin.Y - m_lineHeight >= pos.Y && --count > 0) { m_origin.Y -= m_lineHeight; } } else { m_origin.Y -= (m_lines.Count - 1) * m_lineHeight; } m_delta = new Vector(0, m_lineHeight); break; case XLineAlignment.Center: m_origin = new Vector(pos.X, pos.Y + size.Y / 2 - (m_lines.Count - 1) * m_lineHeight / 2 - m_lineHeight / 2); m_delta = new Vector(0, m_lineHeight); break; } m_actualFormat.LineAlignment = XLineAlignment.Near; switch (m_actualFormat.Alignment) { case XStringAlignment.Far: m_origin.X = pos.X + size.X; break; case XStringAlignment.Center: m_origin.X = pos.X + size.X / 2; break; } }
/// <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="text">The text to draw, which may contain line breaks.</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> /// <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 void 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(); if (size != Vector.Zero) { graphics.IntersectClip(new RectangleF(pos.X, pos.Y, size.X, size.Y)); } // 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; for (var index=0; index<m_lines.Count; ++index) { if (size.Y > 0 && size.Y < m_lineHeight) break; // not enough remaining vertical space for a whole line var line = m_lines[index]; graphics.DrawString(line, font, brush, origin.X, origin.Y, m_actualFormat); origin += m_delta; size.Y -= m_lineHeight; } graphics.SmoothingMode = smoothingMode; graphics.Restore(state); }
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); }
public XSize MeasureString(XGraphics gfx, string text, XFont font, XStringFormat stringFormat) { TextBlock textBlock = FontHelper.CreateTextBlock(text, null, font.Size, null); return new XSize(textBlock.ActualWidth, textBlock.ActualHeight); }
private static void DrawText(XGraphics gfx, string text, string font, string style, double size, string color, int width, int height, int x, int y) { XPdfFontOptions options = new XPdfFontOptions(PdfFontEncoding.Unicode, PdfFontEmbedding.Default); XFont fontStyle = null; switch (style) { case "Bold": fontStyle = new XFont(font, size, XFontStyle.Bold, options); break; case "Italic": fontStyle = new XFont(font, size, XFontStyle.Italic, options); break; case "Regular": fontStyle = new XFont(font, size, XFontStyle.Regular, options); break; case "Underline": fontStyle = new XFont(font, size, XFontStyle.Underline, options); break; case "Strikeout": fontStyle = new XFont(font, size, XFontStyle.Strikeout, options); break; case "BoldItalic": fontStyle = new XFont(font, size, XFontStyle.BoldItalic, options); break; default: break; } System.Drawing.Color fontColor = ConverterManager.HexToColorConverter(color); XBrush fontBrush = new XSolidBrush(new XColor { R = fontColor.R, G = fontColor.G, B = fontColor.B }); XRect fontRect = new XRect(x, y, width, height); XStringFormat fontFormat = new XStringFormat { Alignment = XStringAlignment.Center }; gfx.DrawString(text, fontStyle, fontBrush, fontRect, fontFormat); }
// ----- MeasureString ------------------------------------------------------------------------ /// <summary> /// Measures the specified string when drawn with the specified font. /// </summary> public XSize MeasureString(string text, XFont font, XStringFormat stringFormat) { // TODO: Here comes a lot of code in the future: kerning etc... if (text == null) throw new ArgumentNullException("text"); if (font == null) throw new ArgumentNullException("font"); if (stringFormat == null) throw new ArgumentNullException("stringFormat"); #if GDI && !WPF return XSize.FromSizeF(this.gfx.MeasureString(text, font.RealizeGdiFont(), new PointF(0, 0), stringFormat.RealizeGdiStringFormat())); #endif #if WPF && !GDI #if !SILVERLIGHT //FormattedText formattedText = new FormattedText(text, new CultureInfo("en-us"), // FlowDirection.LeftToRight, font.typeface, font.Size, System.Windows.Media.Brushes.Black); FormattedText formattedText = FontHelper.CreateFormattedText(text, font.typeface, font.Size, System.Windows.Media.Brushes.Black); return new XSize(formattedText.WidthIncludingTrailingWhitespace, formattedText.Height); #else return dc.MeasureString(this, text, font, stringFormat); #endif #endif #if WPF && GDI if (this.targetContext == XGraphicTargetContext.GDI) { XSize gdiSize = XSize.FromSizeF(this.gfx.MeasureString(text, font.RealizeGdiFont(), new PointF(0, 0), stringFormat.RealizeGdiStringFormat())); #if DEBUG Debug.WriteLine(gdiSize); #endif return gdiSize; } if (this.targetContext == XGraphicTargetContext.WPF) { //double h = font.Height; //FormattedText formattedText = new FormattedText(text, new CultureInfo("en-us"), // FlowDirection.LeftToRight, font.typeface, font.Size, System.Windows.Media.Brushes.Black); FormattedText formattedText = FontHelper.CreateFormattedText(text, font.typeface, font.Size, System.Windows.Media.Brushes.Black); XSize wpfSize = new XSize(formattedText.WidthIncludingTrailingWhitespace, formattedText.Height); #if DEBUG Debug.WriteLine(wpfSize); #endif return wpfSize; } Debug.Assert(false); return XSize.Empty; #endif }
private static void PrepareInvoiceTop(XGraphics formGfx, XGraphicsState state, string InvoiceNumber) { string Headline = "Service Invoice " + InvoiceNumber + ""; string MyName = TimeConnector.Data.Variables.SelectedContractor["CmpName"]; string Phone = TimeConnector.Data.Variables.SelectedContractorContact["ConPhone"]; string MyPhone = "Phone (" + Phone.Substring(0, 3) + ") " + Phone.Substring(4, 3) + "-" + Phone.Substring(7, 4) + ""; string MyEmail = "Email: " + TimeConnector.Data.Variables.SelectedContractorContact["ConEmail"] + ""; string MyAddress = TimeConnector.Data.Variables.SelectedContractor["CmpAddress"]; string MyCityStateZip = "" + TimeConnector.Data.Variables.SelectedContractor["CmpCity"] + ", " + TimeConnector.Data.Variables.SelectedContractor["CmpState"] + " " + TimeConnector.Data.Variables.SelectedContractor["CmpZip"] + ""; string WeekEnding = TimeConnector.Data.Variables.SelectedPaydate["WeekEnd"]; string PayDate = TimeConnector.Data.Variables.SelectedPaydate["PayDate"]; string CompanyName = TimeConnector.Data.Variables.SelectedCompany["CmpName"]; string CompanyContact = "c/o " + TimeConnector.Data.Variables.SelectedContact["ConName"] + ""; string CompanyContactPhone = "" + TimeConnector.Data.Variables.SelectedContact["ConPhone"] + ""; string CompanyContactEmail = "" + TimeConnector.Data.Variables.SelectedContact["ConEmail"] + ""; string CompanyAddress = TimeConnector.Data.Variables.SelectedCompany["CmpAddress"]; string CompanyCityStateZip = "" + TimeConnector.Data.Variables.SelectedCompany["CmpCity"] + ", " + TimeConnector.Data.Variables.SelectedCompany["CmpState"] + " " + TimeConnector.Data.Variables.SelectedCompany["CmpZip"] + ""; //----- Invoice Header XFont HeaderFont = new XFont("Imprint MT Shadow", 30, XFontStyle.Bold); string HeaderText = "I N V O I C E"; XStringFormat format = new XStringFormat(); format.Alignment = XStringAlignment.Near; format.LineAlignment = XLineAlignment.Near; XColor color = default(XColor); color = XColor.FromName("SteelBlue"); color.A = 0.5; XBrush brush = default(XBrush); brush = new XSolidBrush(color); XPoint point = new XPoint(410, 20); formGfx.DrawString(HeaderText, HeaderFont, brush, point, format); //..... My Company Icon state = formGfx.Save(); formGfx.DrawImage(XImage.FromFile("Images\\logo.png"), 20, 20, 65, 65); formGfx.Restore(state); //..... My Company Information DrawText(MyName, formGfx, new XFont(PdfFontMyInfo, 15, XFontStyle.Bold), XBrushes.SteelBlue, 95, 20); DrawText(MyAddress, formGfx, new XFont(PdfFontMyInfo, 7, XFontStyle.Regular), XBrushes.Black, 95, 45); DrawText(MyCityStateZip, formGfx, new XFont(PdfFontMyInfo, 7, XFontStyle.Regular), XBrushes.Black, 95, 55); DrawText(MyPhone, formGfx, new XFont(PdfFontMyInfo, 7, XFontStyle.Regular), XBrushes.Black, 95, 65); DrawText(MyEmail, formGfx, new XFont(PdfFontMyInfo, 7, XFontStyle.Regular), XBrushes.Black, 95, 75); XPen pen1 = new XPen(XColors.Maroon); pen1.Width = 1; //Dim pen2 As New XPen(XColors.Maroon) XPen pen2 = new XPen(XColors.SteelBlue); pen2.Width = 2; //Dim pen3 As New XPen(XColors.SteelBlue) XPen pen3 = new XPen(XColors.Maroon); pen3.Width = 1; formGfx.DrawBeziers(pen1, XPoint.ParsePoints("20,95 80,140 190,70 250,110")); DrawSignature(formGfx, 531, 696, "LightGray", 1); DrawSignature(formGfx, 530, 695, "Black", 1.5); DrawSignature(formGfx, 530, 695, "SteelBlue", 1); //formGfx.DrawBeziers(pen2, XPoint.ParsePoints("300,100 310,110 340,90 350,100")) 'Top //formGfx.DrawBeziers(pen2, XPoint.ParsePoints("312,108 322,118 332,99 342,110")) 'Top Center //formGfx.DrawBeziers(pen2, XPoint.ParsePoints("314,118 324,128 334,109 344,120")) 'Bottom Center //formGfx.DrawBeziers(pen2, XPoint.ParsePoints("310,130 315,140 330,120 335,130")) 'Bottom //formGfx.DrawBeziers(pen2, XPoint.ParsePoints("325,100 335,110 325,120 335,130")) 'Center //formGfx.DrawBeziers(pen3, XPoint.ParsePoints("300,100 310,110 340,90 350,100")) 'Top //formGfx.DrawBeziers(pen3, XPoint.ParsePoints("312,108 322,118 332,99 342,110")) 'Top Center //formGfx.DrawBeziers(pen3, XPoint.ParsePoints("314,118 324,128 334,109 344,120")) 'Bottom Center //formGfx.DrawBeziers(pen3, XPoint.ParsePoints("310,130 315,140 330,120 335,130")) 'Bottom //formGfx.DrawBeziers(pen3, XPoint.ParsePoints("325,100 335,110 325,120 335,130")) 'Center //..... ACS Company Icon DrawText("B I L L T O :", formGfx, new XFont(PdfFont, 9, XFontStyle.Bold), XBrushes.Black, 60, 95); state = formGfx.Save(); formGfx.DrawImage(XImage.FromFile("Images\\ACSIcon.jpg"), 20, 115, 65, 65); formGfx.Restore(state); //..... ACS Company Information DrawText(CompanyName, formGfx, new XFont(PdfFontMyInfo, 15, XFontStyle.Bold), XBrushes.Green, 95, 115); DrawText(CompanyContact, formGfx, new XFont(PdfFontMyInfo, 7, XFontStyle.Regular), XBrushes.Black, 95, 135); DrawText(CompanyAddress, formGfx, new XFont(PdfFontMyInfo, 7, XFontStyle.Regular), XBrushes.Black, 95, 145); DrawText(CompanyCityStateZip, formGfx, new XFont(PdfFontMyInfo, 7, XFontStyle.Regular), XBrushes.Black, 95, 155); DrawText(CompanyContactPhone, formGfx, new XFont(PdfFontMyInfo, 7, XFontStyle.Regular), XBrushes.Black, 95, 165); DrawText(CompanyContactEmail, formGfx, new XFont(PdfFontMyInfo, 7, XFontStyle.Regular), XBrushes.Black, 95, 175); //..... Invoice Information DrawLine(formGfx, 450, 590, 80, "SteelBlue", 0.5); DrawText("Invoice #:", formGfx, new XFont(PdfFont, 7, XFontStyle.Bold), XBrushes.Black, 452, 71); DrawText(InvoiceNumber, formGfx, new XFont(PdfFont, 7, XFontStyle.Bold), XBrushes.Maroon, 530, 71); DrawLine(formGfx, 450, 590, 90, "SteelBlue", 0.5); DrawText("Week Ending:", formGfx, new XFont(PdfFont, 7, XFontStyle.Bold), XBrushes.Black, 452, 81); DrawText(WeekEnding, formGfx, new XFont(PdfFont, 7, XFontStyle.Bold), XBrushes.Black, 530, 81); DrawLine(formGfx, 450, 590, 100, "SteelBlue", 0.5); DrawText("Pay Date:", formGfx, new XFont(PdfFont, 7, XFontStyle.Bold), XBrushes.Black, 452, 91); DrawText(PayDate, formGfx, new XFont(PdfFont, 7, XFontStyle.Bold), XBrushes.Black, 530, 91); DrawLine(formGfx, 450, 590, 110, "SteelBlue", 0.5); DrawText("Hours Worked:", formGfx, new XFont(PdfFont, 7, XFontStyle.Bold), XBrushes.Black, 452, 101); DrawText(TimeConnector.Data.Invoice.FinHour, formGfx, new XFont(PdfFont, 7, XFontStyle.Bold), XBrushes.Black, 530, 101); DrawLine(formGfx, 450, 590, 120, "SteelBlue", 0.5); DrawText("Balance Due:", formGfx, new XFont(PdfFont, 7, XFontStyle.Bold), XBrushes.Black, 452, 111); DrawText(TimeConnector.Data.Invoice.FinCost, formGfx, new XFont(PdfFont, 7, XFontStyle.Bold), XBrushes.Black, 530, 111); }
/// <summary> /// Draws the text. /// </summary> /// <param name="text">The text to be drawn.</param> /// <param name="font">The font.</param> /// <param name="brush">The text brush.</param> /// <param name="layoutRectangle">The layout rectangle.</param> /// <param name="format">The format. Must be <c>XStringFormat.TopLeft</c></param> public void DrawString(string text, XFont font, XBrush brush, XRect layoutRectangle, XStringFormat format) { if (text == null) throw new ArgumentNullException("text"); if (font == null) throw new ArgumentNullException("font"); if (brush == null) throw new ArgumentNullException("brush"); if (format.Alignment != XStringAlignment.Near || format.LineAlignment!= XLineAlignment.Near) throw new ArgumentException("Only TopLeft alignment is currently implemented."); Text = text; Font = font; LayoutRectangle = layoutRectangle; if (text.Length == 0) return; CreateBlocks(); CreateLayout(); double dx = layoutRectangle.Location.x; double dy = layoutRectangle.Location.y + cyAscent; int count = this.blocks.Count; for (int idx = 0; idx < count; idx++) { Block block = (Block)this.blocks[idx]; if (block.Stop) break; if (block.Type == BlockType.LineBreak) continue; gfx.DrawString(block.Text, font, brush, dx + block.Location.x, dy + block.Location.y); } }
/// <summary> /// Draws all Etaps showing their start and end in a table graph /// </summary> /// <param name="page">Current PDF page</param> /// <param name="x">Starting X coordination</param> /// <param name="y">Starting Y coordination</param> /// <param name="width">Overview width</param> /// <param name="pageHeight">Maximal height of page</param> /// <returns>Returns Y coordinate of SubSection overview end</returns> private int DrawEtapsGraph(PdfPage page, int x, int y, double width, double pageHeight) { int textHeight = 20; // Right alignment XStringFormat rightAlignment = new XStringFormat(); rightAlignment.Alignment = XStringAlignment.Far; rightAlignment.LineAlignment = XLineAlignment.Center; foreach (Etap etap in obj.Etaps) { using (XGraphics gfx = XGraphics.FromPdfPage(page)) { double xStart = 0, xWidth = 0; // Get etap color and dimensions XBrush brush = ProcessEtap(etap, page.Width.Value, out xStart, out xWidth); // Set and draw etap rect XRect rect = new XRect(xStart, y + 1, xWidth, textHeight - 2); gfx.DrawRectangle(brush, rect); gfx.DrawString( etap.Name, new XFont( this.defaultRegularFont.FontFamily.Name, 6, this.defaultRegularFont.Style, new XPdfFontOptions(PdfFontEncoding.Unicode, PdfFontEmbedding.Always) ), this.defaultBrush, rect, XStringFormats.Center ); y += textHeight; } // If it is the end of the page ... if (y > pageHeight - textHeight) { // Add new page to document page = NewPage(); // Draw header on new page y = DrawHeader(page, 0, 0, width); } } return y; }
/// <summary> /// </summary> public static XSize MeasureStringWpf(string text, XFont font, XStringFormat stringFormat) { FormattedText formattedText = FontHelper.CreateFormattedText(text, font.typeface, font.Size, System.Windows.Media.Brushes.Black); XSize wpfSize = new XSize(formattedText.WidthIncludingTrailingWhitespace, formattedText.Height); return wpfSize; }
/* * 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); }
/// <summary> /// Draws the specified text string. /// </summary> public void DrawString(string s, XFont font, XBrush brush, RectangleF layoutRectangle, XStringFormat format) { DrawString(s, font, brush, new XRect(layoutRectangle), format); }
/// <summary> /// Draws the text. /// </summary> /// <param name="p">The p.</param> /// <param name="text">The text.</param> /// <param name="fill">The fill color.</param> /// <param name="fontFamily">The font family.</param> /// <param name="fontSize">Size of the font.</param> /// <param name="fontWeight">The font weight.</param> /// <param name="rotate">The rotation angle.</param> /// <param name="halign">The horizontal alignment.</param> /// <param name="valign">The vertical alignment.</param> /// <param name="maxSize">The maximum size of the text.</param> public override void DrawText( ScreenPoint p, string text, OxyColor fill, string fontFamily, double fontSize, double fontWeight, double rotate, HorizontalAlignment halign, VerticalAlignment valign, OxySize? maxSize) { if (text == null) { return; } var fs = XFontStyle.Regular; if (fontWeight > FontWeights.Normal) { fs = XFontStyle.Bold; } var font = new XFont(fontFamily, (float)fontSize * FontsizeFactor, fs); var size = this.g.MeasureString(text, font); #if SILVERLIGHT // Correct the height, MeasureString returns 2x height size.Height *= 0.5; #endif if (maxSize != null) { if (size.Width > maxSize.Value.Width) { size.Width = Math.Max(maxSize.Value.Width, 0); } if (size.Height > maxSize.Value.Height) { size.Height = Math.Max(maxSize.Value.Height, 0); } } double dx = 0; if (halign == HorizontalAlignment.Center) { dx = -size.Width / 2; } if (halign == HorizontalAlignment.Right) { dx = -size.Width; } double dy = 0; if (valign == VerticalAlignment.Middle) { dy = -size.Height / 2; } if (valign == VerticalAlignment.Bottom) { dy = -size.Height; } var state = this.g.Save(); this.g.TranslateTransform(dx, dy); if (Math.Abs(rotate) > double.Epsilon) { this.g.RotateAtTransform((float)rotate, new XPoint((float)p.X + (float)(size.Width / 2.0), (float)p.Y)); } this.g.TranslateTransform((float)p.X, (float)p.Y); var layoutRectangle = new XRect(0, 0, size.Width, size.Height); var sf = new XStringFormat { Alignment = XStringAlignment.Near, LineAlignment = XLineAlignment.Near }; this.g.DrawString(text, font, ToBrush(fill), layoutRectangle, sf); this.g.Restore(state); }
/// <summary> /// Draws the specified text string. /// </summary> public void DrawString(string text, XFont font, XBrush brush, XRect layoutRectangle, XStringFormat format) { if (text == null) throw new ArgumentNullException("text"); if (font == null) throw new ArgumentNullException("font"); if (brush == null) throw new ArgumentNullException("brush"); if (format != null && format.LineAlignment == XLineAlignment.BaseLine && layoutRectangle.Height != 0) throw new InvalidOperationException("DrawString: With XLineAlignment.BaseLine the height of the layout rectangle must be 0."); if (text.Length == 0) return; if (format == null) format = XStringFormats.Default; if (this.drawGraphics) { #if GDI if (this.targetContext == XGraphicTargetContext.GDI) { RectangleF rect = layoutRectangle.ToRectangleF(); if (format.LineAlignment == XLineAlignment.BaseLine) { double lineSpace = font.GetHeight(this); int cellSpace = font.FontFamily.GetLineSpacing(font.Style); int cellAscent = font.FontFamily.GetCellAscent(font.Style); int cellDescent = font.FontFamily.GetCellDescent(font.Style); double cyAscent = lineSpace * cellAscent / cellSpace; cyAscent = lineSpace * font.cellAscent / font.cellSpace; rect.Offset(0, (float)-cyAscent); } this.gfx.DrawString(text, font.RealizeGdiFont(), brush.RealizeGdiBrush(), rect, format != null ? format.RealizeGdiStringFormat() : null); } #endif #if WPF if (this.targetContext == XGraphicTargetContext.WPF) { #if !SILVERLIGHT double x = layoutRectangle.X; double y = layoutRectangle.Y; double lineSpace = font.GetHeight(this); double cyAscent = lineSpace * font.cellAscent / font.cellSpace; double cyDescent = lineSpace * font.cellDescent / font.cellSpace; bool bold = (font.Style & XFontStyle.Bold) != 0; bool italic = (font.Style & XFontStyle.Italic) != 0; bool strikeout = (font.Style & XFontStyle.Strikeout) != 0; bool underline = (font.Style & XFontStyle.Underline) != 0; //FormattedText formattedText = new FormattedText(text, new CultureInfo("en-us"), // WPFHACK // FlowDirection.LeftToRight, font.typeface, font.Size, brush.RealizeWpfBrush()); FormattedText formattedText = FontHelper.CreateFormattedText(text, font.typeface, font.Size, brush.RealizeWpfBrush()); //formattedText.SetTextDecorations(TextDecorations.OverLine); switch (format.Alignment) { case XStringAlignment.Near: // nothing to do, this is the default //formattedText.TextAlignment = TextAlignment.Left; break; case XStringAlignment.Center: x += layoutRectangle.Width / 2; formattedText.TextAlignment = TextAlignment.Center; break; case XStringAlignment.Far: x += layoutRectangle.Width; formattedText.TextAlignment = TextAlignment.Right; break; } if (PageDirection == XPageDirection.Downwards) { switch (format.LineAlignment) { case XLineAlignment.Near: //y += cyAscent; break; case XLineAlignment.Center: // TODO use CapHeight. PDFlib also uses 3/4 of ascent y += -formattedText.Baseline + (cyAscent * 1 / 3) + layoutRectangle.Height / 2; //y += -formattedText.Baseline + (font.Size * font.Metrics.CapHeight / font.unitsPerEm / 2) + layoutRectangle.Height / 2; break; case XLineAlignment.Far: y += -formattedText.Baseline - cyDescent + layoutRectangle.Height; break; case XLineAlignment.BaseLine: y -= formattedText.Baseline; break; } } else { // TODOWPF: make unit test switch (format.LineAlignment) { case XLineAlignment.Near: //y += cyDescent; break; case XLineAlignment.Center: // TODO use CapHeight. PDFlib also uses 3/4 of ascent //y += -(cyAscent * 3 / 4) / 2 + rect.Height / 2; break; case XLineAlignment.Far: //y += -cyAscent + rect.Height; break; case XLineAlignment.BaseLine: // nothing to do break; } } //if (bold && !descriptor.IsBoldFace) //{ // // TODO: emulate bold by thicker outline //} //if (italic && !descriptor.IsBoldFace) //{ // // TODO: emulate italic by shearing transformation //} if (underline) { formattedText.SetTextDecorations(TextDecorations.Underline); //double underlinePosition = lineSpace * realizedFont.FontDescriptor.descriptor.UnderlinePosition / font.cellSpace; //double underlineThickness = lineSpace * realizedFont.FontDescriptor.descriptor.UnderlineThickness / font.cellSpace; //DrawRectangle(null, brush, x, y - underlinePosition, width, underlineThickness); } if (strikeout) { formattedText.SetTextDecorations(TextDecorations.Strikethrough); //double strikeoutPosition = lineSpace * realizedFont.FontDescriptor.descriptor.StrikeoutPosition / font.cellSpace; //double strikeoutSize = lineSpace * realizedFont.FontDescriptor.descriptor.StrikeoutSize / font.cellSpace; //DrawRectangle(null, brush, x, y - strikeoutPosition - strikeoutSize, width, strikeoutSize); } //this.dc.DrawText(formattedText, layoutRectangle.Location.ToPoint()); this.dc.DrawText(formattedText, new System.Windows.Point(x, y)); #else dc.DrawString(this, text, font, brush, layoutRectangle, format); #endif } #endif } if (this.renderer != null) this.renderer.DrawString(text, font, brush, layoutRectangle, format); }
public void DrawString(XGraphics gfx, string text, XFont font, XBrush brush, XRect layoutRectangle, XStringFormat format) { double x = layoutRectangle.X; double y = layoutRectangle.Y; double lineSpace = font.GetHeight(gfx); double cyAscent = lineSpace * font.cellAscent / font.cellSpace; double cyDescent = lineSpace * font.cellDescent / font.cellSpace; bool bold = (font.Style & XFontStyle.Bold) != 0; bool italic = (font.Style & XFontStyle.Italic) != 0; bool strikeout = (font.Style & XFontStyle.Strikeout) != 0; bool underline = (font.Style & XFontStyle.Underline) != 0; //FormattedText formattedText = new FormattedText(text, new CultureInfo("en-us"), // WPFHACK // FlowDirection.LeftToRight, font.typeface, font.Size, brush.RealizeWpfBrush()); TextBlock textBlock = FontHelper.CreateTextBlock(text, null, font.Size, brush.RealizeWpfBrush()); Canvas.SetLeft(textBlock, x); Canvas.SetTop(textBlock, y); //formattedText.SetTextDecorations(TextDecorations.OverLine); switch (format.Alignment) { case XStringAlignment.Near: // nothing to do, this is the default //formattedText.TextAlignment = TextAlignment.Left; break; case XStringAlignment.Center: x += layoutRectangle.Width / 2; textBlock.TextAlignment = TextAlignment.Center; break; case XStringAlignment.Far: x += layoutRectangle.Width; textBlock.TextAlignment = TextAlignment.Right; break; } if (gfx.PageDirection == XPageDirection.Downwards) { switch (format.LineAlignment) { case XLineAlignment.Near: //y += cyAscent; break; //case XLineAlignment.Center: // // TODO use CapHeight. PDFlib also uses 3/4 of ascent // y += -formattedText.Baseline + (cyAscent * 1 / 3) + layoutRectangle.Height / 2; // //y += -formattedText.Baseline + (font.Size * font.Metrics.CapHeight / font.unitsPerEm / 2) + layoutRectangle.Height / 2; // break; //case XLineAlignment.Far: // y += -formattedText.Baseline - cyDescent + layoutRectangle.Height; // break; //case XLineAlignment.BaseLine: // y -= formattedText.Baseline; // break; } } else { // TODOWPF: make unit test switch (format.LineAlignment) { case XLineAlignment.Near: //y += cyDescent; break; case XLineAlignment.Center: // TODO use CapHeight. PDFlib also uses 3/4 of ascent //y += -(cyAscent * 3 / 4) / 2 + rect.Height / 2; break; case XLineAlignment.Far: //y += -cyAscent + rect.Height; break; case XLineAlignment.BaseLine: // nothing to do break; } } //if (bold && !descriptor.IsBoldFace) //{ // // TODO: emulate bold by thicker outline //} //if (italic && !descriptor.IsBoldFace) //{ // // TODO: emulate italic by shearing transformation //} //if (underline) //{ // formattedText.FontStyle.SetTextDecorations(TextDecorations.Underline); // //double underlinePosition = lineSpace * realizedFont.FontDescriptor.descriptor.UnderlinePosition / font.cellSpace; // //double underlineThickness = lineSpace * realizedFont.FontDescriptor.descriptor.UnderlineThickness / font.cellSpace; // //DrawRectangle(null, brush, x, y - underlinePosition, width, underlineThickness); //} //if (strikeout) //{ // formattedText.SetTextDecorations(TextDecorations.Strikethrough); // //double strikeoutPosition = lineSpace * realizedFont.FontDescriptor.descriptor.StrikeoutPosition / font.cellSpace; // //double strikeoutSize = lineSpace * realizedFont.FontDescriptor.descriptor.StrikeoutSize / font.cellSpace; // //DrawRectangle(null, brush, x, y - strikeoutPosition - strikeoutSize, width, strikeoutSize); //} //formattedText _canvas.Children.Add(textBlock); }
static void Main() { const string watermark = "PDFsharp"; const int emSize = 150; // Get a fresh copy of the sample PDF file const string filename = "Portable Document Format.pdf"; File.Copy(Path.Combine("../../../../../PDFs/", filename), Path.Combine(Directory.GetCurrentDirectory(), filename), true); // Create the font for drawing the watermark XFont font = new XFont("Times New Roman", emSize, XFontStyle.BoldItalic); // Open an existing document for editing and loop through its pages PdfDocument document = PdfReader.Open(filename); // Set version to PDF 1.4 (Acrobat 5) because we use transparency. if (document.Version < 14) document.Version = 14; for (int idx = 0; idx < document.Pages.Count; idx++) { //if (idx == 1) break; PdfPage page = document.Pages[idx]; switch (idx % 3) { case 0: { // Variation 1: Draw watermark as text string // Get an XGraphics object for drawing beneath the existing content XGraphics gfx = XGraphics.FromPdfPage(page, XGraphicsPdfPageOptions.Prepend); #if true_ // Fill background with linear gradient color XRect rect = page.MediaBox.ToXRect(); XLinearGradientBrush gbrush = new XLinearGradientBrush(rect, XColors.LightSalmon, XColors.WhiteSmoke, XLinearGradientMode.Vertical); gfx.DrawRectangle(gbrush, rect); #endif // 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(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); } break; case 1: { // Variation 2: Draw watermark as outlined graphical path // 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(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 graphical path XGraphicsPath path = new XGraphicsPath(); // Add the text to the path path.AddString(watermark, font.FontFamily, XFontStyle.BoldItalic, 150, new XPoint((page.Width - size.Width) / 2, (page.Height - size.Height) / 2), XStringFormats.Default); // Create a dimmed red pen XPen pen = new XPen(XColor.FromArgb(128, 255, 0, 0), 2); // Stroke the outline of the path gfx.DrawPath(pen, path); } break; case 2: { // Variation 3: Draw watermark as transparent graphical path above text // Get an XGraphics object for drawing above the existing content XGraphics gfx = XGraphics.FromPdfPage(page, XGraphicsPdfPageOptions.Append); // 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 graphical path XGraphicsPath path = new XGraphicsPath(); // Add the text to the path path.AddString(watermark, font.FontFamily, XFontStyle.BoldItalic, 150, new XPoint((page.Width - size.Width) / 2, (page.Height - size.Height) / 2), XStringFormats.Default); // 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 gfx.DrawPath(pen, brush, path); } break; } } // Save the document... document.Save(filename); // ...and start a viewer Process.Start(filename); }
/// <summary> /// Draws Etaps and theirs MainItems /// </summary> /// <param name="page">Page to draw in</param> /// <param name="x">Starting X possition</param> /// <param name="y">Starting Y possition</param> /// <returns></returns> private int DrawItemsOfEtaps(PdfPage page, int x, int y) { Dictionary<Etap, List<MainItem>> etaps = new Dictionary<Etap, List<MainItem>>(this.obj.Etaps.Count); // For every Etap in currnt Object ... foreach (Etap etap in this.obj.Etaps) { // ... browse all current Object's Calculations ... foreach (CostsCalculation calculation in this.obj.CalculationList) { // ... their SubSections ... foreach (SubSection subSection in calculation.SubSections) { // ... their MainItems ... foreach (MainItem item in subSection.MainItemsList) { // ... for items from current etap ... if (item.EtapID == etap.ID) { if (!etaps.ContainsKey(etap)) etaps.Add(etap, new List<MainItem>()); // ... to add to the overview etaps[etap].Add(item); } } } } } int textHeight = 20; XStringFormat rightAlignment = new XStringFormat(); rightAlignment.Alignment = XStringAlignment.Far; rightAlignment.LineAlignment = XLineAlignment.Center; // Draw overview foreach (Etap etap in etaps.Keys) { // Will next line fit? if (y + textHeight > page.Height.Value) { page = NewPage(); y = 20; } // Draw Etap with total prices of all its items using (XGraphics gfx = XGraphics.FromPdfPage(page)) { XRect rect = new XRect(x, y, page.Width.Value, textHeight); gfx.DrawString(etap.Name.ToUpper(), this.defaultBoldFont, this.defaultBrush, rect, this.defaultFormat); decimal price = 0; foreach (MainItem item in etaps[etap]) { price += Utilities.StringUtils.ParsePriceFromString(item.TotalPrice, 0); } gfx.DrawString(Utilities.StringUtils.FormatDecimalAsPrice(price), this.defaultBoldFont, this.defaultBrush, rect, rightAlignment); } // New line y += textHeight; // Draw MainItems of etap foreach (MainItem item in etaps[etap]) { // Will next line fit? if (y + textHeight > page.Height.Value) { page = NewPage(); y = 20; } // Draw MainItem using (XGraphics gfx = XGraphics.FromPdfPage(page)) { XRect rect = new XRect(x + 10, y, page.Width.Value - 10, textHeight); gfx.DrawString(item.Name, this.defaultRegularFont, this.defaultBrush, rect, this.defaultFormat); gfx.DrawString(item.TotalPrice, this.defaultRegularFont, this.defaultBrush, rect, rightAlignment); } // New line y += textHeight; } // Draw separator using (XGraphics gfx = XGraphics.FromPdfPage(page)) { gfx.DrawLine(XPens.Gray, x, y, page.Width.Value, y); } } return y; }
/// <summary> /// /// </summary> /// <param name="gfx"></param> /// <param name="text"></param> /// <param name="dx"></param> /// <param name="dy"></param> /// <param name="db"></param> /// <param name="r"></param> public void Draw(object gfx, Kaliber3D.Render.XText text, double dx, double dy, ImmutableArray<Kaliber3D.Render.ShapeProperty> db, Kaliber3D.Render.Record r) { var _gfx = gfx as XGraphics; var tbind = text.BindToTextProperty(db, r); if (string.IsNullOrEmpty(tbind)) return; var options = new XPdfFontOptions(PdfFontEncoding.Unicode); var fontStyle = XFontStyle.Regular; if (text.Style.TextStyle.FontStyle.Flags.HasFlag(Kaliber3D.Render.FontStyleFlags.Bold)) { fontStyle |= XFontStyle.Bold; } if (text.Style.TextStyle.FontStyle.Flags.HasFlag(Kaliber3D.Render.FontStyleFlags.Italic)) { fontStyle |= XFontStyle.Italic; } if (text.Style.TextStyle.FontStyle.Flags.HasFlag(Kaliber3D.Render.FontStyleFlags.Underline)) { fontStyle |= XFontStyle.Underline; } if (text.Style.TextStyle.FontStyle.Flags.HasFlag(Kaliber3D.Render.FontStyleFlags.Strikeout)) { fontStyle |= XFontStyle.Strikeout; } var font = new XFont( text.Style.TextStyle.FontName, _scaleToPage(text.Style.TextStyle.FontSize), fontStyle, options); var rect = Kaliber3D.Render.Rect2.Create( text.TopLeft, text.BottomRight, dx, dy); var srect = new XRect( _scaleToPage(rect.X), _scaleToPage(rect.Y), _scaleToPage(rect.Width), _scaleToPage(rect.Height)); var format = new XStringFormat(); switch (text.Style.TextStyle.TextHAlignment) { case Kaliber3D.Render.TextHAlignment.Left: format.Alignment = XStringAlignment.Near; break; case Kaliber3D.Render.TextHAlignment.Center: format.Alignment = XStringAlignment.Center; break; case Kaliber3D.Render.TextHAlignment.Right: format.Alignment = XStringAlignment.Far; break; } switch (text.Style.TextStyle.TextVAlignment) { case Kaliber3D.Render.TextVAlignment.Top: format.LineAlignment = XLineAlignment.Near; break; case Kaliber3D.Render.TextVAlignment.Center: format.LineAlignment = XLineAlignment.Center; break; case Kaliber3D.Render.TextVAlignment.Bottom: format.LineAlignment = XLineAlignment.Far; break; } _gfx.DrawString( tbind, font, ToXSolidBrush(text.Style.Stroke), srect, format); }
/// <summary> /// initialise the fonts and pens. /// this can only happen when the Graphics and GraphicsUnit are known. /// </summary> private void InitFontsAndPens() { FXBlackPen = new XPen(XColor.FromKnownColor(XKnownColor.Black), Cm(0.05f)); XPdfFontOptions options = new XPdfFontOptions(PdfFontEncoding.Unicode, PdfFontEmbedding.Always); // the fonts need to be a little bit bigger so that they have the same size as the GfxPrinter? FXSmallPrintFont = new XFont("Arial", 0.12, XFontStyle.Regular, options); // Point(6 + XFONTSIZE) FXDefaultFont = new XFont("Arial", 0.14, XFontStyle.Regular, options); // Point(8 + XFONTSIZE) FXDefaultBoldFont = new XFont("Arial", 0.14, XFontStyle.Bold, options); // Point(8 + XFONTSIZE) FXHeadingFont = new XFont("Arial", 0.16, XFontStyle.Bold, options); // Point(10 + XFONTSIZE) // using GPL Font Code 128 from Grand Zebu http://grandzebu.net/ FXBarCodeFont = new XFont("Code 128", 0.45, XFontStyle.Regular, options); // Point(10 + XFONTSIZE) FXBiggestLastUsedFont = FXDefaultFont; FXRight = new XStringFormat(); FXRight.Alignment = XStringAlignment.Far; FXLeft = new XStringFormat(); FXLeft.Alignment = XStringAlignment.Near; FXCenter = new XStringFormat(); FXCenter.Alignment = XStringAlignment.Center; }
/// <summary> /// Draws the vertical Y axis. /// </summary> internal override void Draw() { AxisRendererInfo yari = ((ChartRendererInfo)this.rendererParms.RendererInfo).yAxisRendererInfo; double yMin = yari.MinimumScale; double yMax = yari.MaximumScale; double yMajorTick = yari.MajorTick; double yMinorTick = yari.MinorTick; XMatrix matrix = new XMatrix(); //XMatrix.Identity; matrix.TranslatePrepend(-yMin, -yari.Y); matrix.Scale(yari.InnerRect.Width / (yMax - yMin), 1, XMatrixOrder.Append); matrix.Translate(yari.X, yari.Y, XMatrixOrder.Append); // Draw axis. // First draw tick marks, second draw axis. double majorTickMarkStart = 0, majorTickMarkEnd = 0, minorTickMarkStart = 0, minorTickMarkEnd = 0; GetTickMarkPos(yari, ref majorTickMarkStart, ref majorTickMarkEnd, ref minorTickMarkStart, ref minorTickMarkEnd); XGraphics gfx = this.rendererParms.Graphics; LineFormatRenderer lineFormatRenderer = new LineFormatRenderer(gfx, yari.LineFormat); XPoint[] points = new XPoint[2]; if (yari.MinorTickMark != TickMarkType.None) { for (double y = yMin + yMinorTick; y < yMax; y += yMinorTick) { points[0].X = y; points[0].Y = minorTickMarkStart; points[1].X = y; points[1].Y = minorTickMarkEnd; matrix.TransformPoints(points); lineFormatRenderer.DrawLine(points[0], points[1]); } } XStringFormat xsf = new XStringFormat(); xsf.LineAlignment = XLineAlignment.Near; int countTickLabels = (int)((yMax - yMin) / yMajorTick) + 1; for (int i = 0; i < countTickLabels; ++i) { double y = yMin + yMajorTick * i; string str = y.ToString(yari.TickLabelsFormat); XSize labelSize = gfx.MeasureString(str, yari.TickLabelsFont); if (yari.MajorTickMark != TickMarkType.None) { labelSize.Height += 1.5f * yari.MajorTickMarkWidth; points[0].X = y; points[0].Y = majorTickMarkStart; points[1].X = y; points[1].Y = majorTickMarkEnd; matrix.TransformPoints(points); lineFormatRenderer.DrawLine(points[0], points[1]); } XPoint[] layoutText = new XPoint[1]; layoutText[0].X = y; layoutText[0].Y = yari.Y + 1.5 * yari.MajorTickMarkWidth; matrix.TransformPoints(layoutText); layoutText[0].X -= labelSize.Width / 2; // Center text vertically. gfx.DrawString(str, yari.TickLabelsFont, yari.TickLabelsBrush, layoutText[0], xsf); } if (yari.LineFormat != null) { points[0].X = yMin; points[0].Y = yari.Y; points[1].X = yMax; points[1].Y = yari.Y; matrix.TransformPoints(points); if (yari.MajorTickMark != TickMarkType.None) { // yMax is at the upper side of the axis points[0].X -= yari.LineFormat.Width / 2; points[1].X += yari.LineFormat.Width / 2; } lineFormatRenderer.DrawLine(points[0], points[1]); } // Draw axis title if (yari.axisTitleRendererInfo != null) { RendererParameters parms = new RendererParameters(); parms.Graphics = gfx; parms.RendererInfo = yari; XRect rcTitle = yari.Rect; rcTitle.Height = yari.axisTitleRendererInfo.Height; rcTitle.Y += yari.Rect.Height - rcTitle.Height; yari.axisTitleRendererInfo.Rect = rcTitle; AxisTitleRenderer atr = new AxisTitleRenderer(parms); atr.Draw(); } }
private static void RenderWord(string word, XGraphics gfx, XRect rect, int fontsize, string color = null) { XFont font = new XFont("Garamond", fontsize, XFontStyle.Regular, new XPdfFontOptions(PdfFontEncoding.Unicode)); XBrush brush; if(string.IsNullOrEmpty(color)) brush = XBrushes.Black; else { XColor xcolor = XColor.FromArgb(ColorTranslator.FromHtml("#" + color)); brush = new XSolidBrush(xcolor); } XStringFormat format = new XStringFormat(); format.Alignment = XStringAlignment.Center; format.LineAlignment = XLineAlignment.Center; gfx.DrawString(word.ToLower(), font, brush, rect, format); }