private static void EscreverVerso(PdfDocument outputDocument, XPdfForm form, UsuarioCertificadoCertame certificadoUsuario, XFont font, XStringFormat format) { if (form.PageCount > 1) { var paginaVerso = outputDocument.AddPage(); paginaVerso.Orientation = PageOrientation.Landscape; paginaVerso.Size = PageSize.A4; form.PageNumber = 2; var posicaoId = new BMPosicaoDadoCertificadoCertame().ObterPorDadoAno("id", certificadoUsuario.CertificadoCertame.Ano); if (posicaoId == null) { throw new Exception("Posição de dado obrigatório não informada no verso"); } var gfx = XGraphics.FromPdfPage(paginaVerso); gfx.DrawImage(form, new XRect(0, 0, form.PointWidth, form.PointHeight)); EscreverDado(paginaVerso, posicaoId, gfx, font, format, certificadoUsuario.Chave); } }
void AddTitleAndFooter(PdfPage page, XGraphics gfx, string title, PdfDocument document, PdfData pdfData) { Log l = new Log(); try { XRect rect = new XRect(new XPoint(), gfx.PageSize); rect.Inflate(-10, -15); XFont font = new XFont("OpenSans", 14, XFontStyle.Bold); gfx.DrawString(title, font, XBrushes.MidnightBlue, rect, XStringFormats.TopCenter); rect.Offset(0, 5); font = new XFont("OpenSans", 8, XFontStyle.Italic); XStringFormat format = new XStringFormat(); format.Alignment = XStringAlignment.Near; format.LineAlignment = XLineAlignment.Far; gfx.DrawString(pdfData.CreatedBy, font, XBrushes.Black, rect, format); font = new XFont("OpenSans", 8); format.Alignment = XStringAlignment.Center; gfx.DrawString(document.PageCount.ToString(), font, XBrushes.DarkOrchid, rect, format); document.Outlines.Add(title, page, true); } catch (Exception ex) { l.CreatedOn = System.DateTime.UtcNow; l.ShortDescription = ex.Message; l.FullDescription = ex.InnerException.ToString(); _ILog.InsertLog(l); throw ex; } }
/// <summary> /// prints into the current line, absolute x position with width and alignment /// </summary> /// <returns>true if something was printed</returns> public override Boolean PrintString(String ATxt, eFont AFont, float AXPos, float AWidth, eAlignment AAlign) { RectangleF rect = CalculatePrintStringRectangle(AXPos, CurrentYPos, AWidth, AFont); if (PrintingMode == ePrintingMode.eDoPrint) { if (FPrinterBehaviour == ePrinterBehaviour.eReport) { ATxt = GetFittedText(ATxt, AFont, rect.Width); } if ((AAlign == eAlignment.eCenter) && Environment.OSVersion.ToString().StartsWith("Unix")) { // it seems on Mono/Unix, the string aligning to the center does not work properly. so we do it manually rect = new RectangleF(rect.Left + (AWidth - GetWidthString(ATxt, AFont)) / 2.0f, rect.Top, rect.Height, rect.Width); FXGraphics.DrawString(ATxt, GetXFont(AFont), Brushes.Black, rect, GetXStringFormat(eAlignment.eLeft)); } else { XStringFormat f = GetXStringFormat(AAlign); f.FormatFlags = XStringFormatFlags.MeasureTrailingSpaces; //TLogging.Log("curr ypos " + CurrentYPos.ToString() + " " + AXPos.ToString() + " " + ATxt + AWidth.ToString()); FXGraphics.DrawString(ATxt, GetXFont(AFont), Brushes.Black, rect, f); } } return((ATxt != null) && (ATxt.Length != 0)); }
public void DrawTitle(PdfPage page, XGraphics gr, Order order, PdfDocument doc) { // build header gr.DrawRectangle(new XSolidBrush(XColors.MidnightBlue), new XRect(40, 05, page.Width - 80, 07)); // logo image XImage image = XImage.FromFile(server.MapPath("/Content/MyImages/haze.png")); gr.DrawImage(image, 40, 15, 100, 30); // transaction status XRect rect = new XRect(40, 90, page.Width - 80, 0); XFont font = new XFont("Verdana", 12, XFontStyle.Bold); gr.DrawString("Transaction receipt: " + order.RequestPaymentStatus, font, XBrushes.MidnightBlue, rect); // transaction time font = new XFont("Verdana", 10, XFontStyle.Regular); rect = new XRect(400, 90, page.Width - 80, 0); gr.DrawString(order.RequestPaymentDate, font, XBrushes.MidnightBlue, rect); // build footer XStringFormat format = new XStringFormat(); format.Alignment = XStringAlignment.Near; font = new XFont("Verdana", 8); rect = new XRect(10, page.Height - 20, page.Width - 20, 0); gr.DrawString(getCompAddress(), font, XBrushes.MidnightBlue, rect, format); }
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> /// </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); }
public static bool SetAlignmentFromCardinalOrOrdinalDirection(XStringFormat format, CompassPoint compassPoint, RoomShape?rs = null) { switch (compassPoint) { case CompassPoint.North: case CompassPoint.NorthEast: format.LineAlignment = XLineAlignment.Far; format.Alignment = XStringAlignment.Near; break; case CompassPoint.East: case CompassPoint.SouthEast: case CompassPoint.South: format.LineAlignment = XLineAlignment.Near; format.Alignment = XStringAlignment.Near; break; case CompassPoint.West: case CompassPoint.SouthWest: format.LineAlignment = XLineAlignment.Near; format.Alignment = XStringAlignment.Far; break; case CompassPoint.NorthWest: case CompassPoint.NorthNorthWest: format.LineAlignment = XLineAlignment.Far; format.Alignment = XStringAlignment.Far; break; default: return(false); } return(true); }
private static void drawShot(Shot shot, XGraphics it, int xLoc, int yLoc, int targetSize, decimal zoomFactor) { //transform shot coordinates to imagebox coordinates XPoint x = transform((float)getShotX(shot), (float)getShotY(shot), targetSize, zoomFactor, xLoc, yLoc); //draw shot on target XBrush b = new XSolidBrush(XColor.FromArgb(200, 135, 206, 250)); //semitransparent shots XPen p = new XPen(XColor.FromKnownColor(XKnownColor.Blue), 0.5); XBrush bText = new XSolidBrush(XColor.FromKnownColor(XKnownColor.Blue)); it.SmoothingMode = XSmoothingMode.AntiAlias; float peletSize = getDimension(targetSize, ISSF.pelletCaliber, zoomFactor); x.X -= peletSize / 2; x.Y -= peletSize / 2; it.DrawEllipse(b, new XRect(x, new XSize(peletSize, peletSize))); it.DrawEllipse(p, new XRect(x, new XSize(peletSize, peletSize))); XStringFormat format = new XStringFormat(); format.LineAlignment = (XLineAlignment)XStringAlignment.Center; format.Alignment = XStringAlignment.Center; Font f = new Font("Arial", peletSize / 3, GraphicsUnit.World); it.DrawString((shot.index + 1).ToString(), f, bText, new XRect(x, new XSize(peletSize, peletSize)), format); }
private static void createTableHeader(XGraphics gfx) { XPdfFontOptions options = new XPdfFontOptions(PdfFontEncoding.Unicode, PdfFontEmbedding.Always); XBrush brush = XBrushes.Black; XStringFormat format = new XStringFormat(); format.LineAlignment = XLineAlignment.Center; XPen xpen = new XPen(XColors.Black, 1.5); XBrush xbrush = XBrushes.Bisque; XRect rect; XFont font; int currX = X_START; string headerLastName = RES_MANAGER.GetString("lastname"); rect = new XRect(currX, CURR_Y, COL_WIDTH[0], 16); font = new XFont("Arial", 12, XFontStyle.Bold, options); format.Alignment = XStringAlignment.Near; //gfx.DrawRectangle(xpen, xbrush, rect); gfx.DrawString(headerLastName, font, brush, rect, format); currX += COL_WIDTH[0] + COL_GAP; string headerName = RES_MANAGER.GetString("name"); rect = new XRect(currX, CURR_Y, COL_WIDTH[1], 16); //gfx.DrawRectangle(xpen, xbrush, rect); gfx.DrawString(headerName, font, brush, rect, format); currX += COL_WIDTH[1] + COL_GAP; string headerTitle = RES_MANAGER.GetString("title"); rect = new XRect(currX, CURR_Y, COL_WIDTH[2], 16); //gfx.DrawRectangle(xpen, xbrush, rect); gfx.DrawString(headerTitle, font, brush, rect, format); currX += COL_WIDTH[2] + COL_GAP; string headerEduRank = RES_MANAGER.GetString("edurank"); rect = new XRect(currX, CURR_Y, COL_WIDTH[3], 16); //gfx.DrawRectangle(xpen, xbrush, rect); gfx.DrawString(headerEduRank, font, brush, rect, format); currX += COL_WIDTH[3] + COL_GAP; string headerExtID = RES_MANAGER.GetString("extid"); rect = new XRect(currX, CURR_Y, COL_WIDTH[4], 16); //gfx.DrawRectangle(xpen, xbrush, rect); gfx.DrawString(headerExtID, font, brush, rect, format); gfx.DrawLine(xpen, X_START - 20, CURR_Y + 18, X_START + 475, CURR_Y + 18); CURR_Y += 20; }
/// <summary> /// Resembles the MeasureString function of GDI+. /// </summary> public XSize MeasureString(XGraphics gfx, string text, XFont font, XStringFormat stringFormat) { //Debug.Assert(font.GlyphTypeface != null); TextBlock textBlock = new TextBlock(); //FontHelper.CreateTextBlock(text, font.GlyphTypeface, font.Size, null); // Looks very much like a hack, but is the recommended way documented by Microsoft. return new XSize(textBlock.ActualWidth, textBlock.ActualHeight); }
/// <summary> /// Defines page setup, headers, and footers. /// </summary> public static void SetPageNumber(PdfDocument document) { // Make a font and a brush to draw the page counter. XFont font = new XFont("Verdana", 8, XFontStyle.Regular); XBrush brush = XBrushes.Black; // Add the page counter. string pageTotalCount = document.Pages.Count.ToString(); XStringFormat pageNumberFormat = new XStringFormat { Alignment = XStringAlignment.Far, LineAlignment = XLineAlignment.Near }; for (int i = 0; i < document.Pages.Count; ++i) { PdfPage page = document.Pages[i]; // Make a layout rectangle. XRect layoutRectangle = new XRect(0 /*X*/, page.Height - font.Height /*Y*/, page.Width - 15 /*Width*/, font.Height /*Height*/); using (XGraphics gfx = XGraphics.FromPdfPage(page)) { gfx.DrawString( "Page " + (i + 1).ToString() + " of " + pageTotalCount, font, brush, layoutRectangle, pageNumberFormat); } } }
/// <summary> /// Draws the data labels of the pie chart. /// </summary> internal override void Draw() { ChartRendererInfo cri = (ChartRendererInfo)this.rendererParms.RendererInfo; if (cri.seriesRendererInfos.Length == 0) { return; } SeriesRendererInfo sri = cri.seriesRendererInfos[0]; if (sri.dataLabelRendererInfo == null) { return; } if (sri != null) { XGraphics gfx = this.rendererParms.Graphics; XFont font = sri.dataLabelRendererInfo.Font; XBrush fontColor = sri.dataLabelRendererInfo.FontColor; XStringFormat format = XStringFormats.Center; format.LineAlignment = XLineAlignment.Center; foreach (DataLabelEntryRendererInfo dataLabel in sri.dataLabelRendererInfo.Entries) { if (dataLabel.Text != null) { gfx.DrawString(dataLabel.Text, font, fontColor, dataLabel.Rect, format); } } } }
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 void DrawWaterMarkDiagonal(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) * 90 / 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, 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); }
static GraphicsAdapter() { _stringFormat = new XStringFormat(); _stringFormat.Alignment = XStringAlignment.Near; _stringFormat.LineAlignment = XLineAlignment.Near; _stringFormat.FormatFlags = XStringFormatFlags.MeasureTrailingSpaces; }
public static void CreateBarcodeAsText() { using (PdfDocument document = new PdfDocument()) { //create pdf header document.Info.Title = "My barcode"; document.Info.Author = "Me"; document.Info.Subject = "Barcode"; document.Info.Keywords = "Barcode, Ean13"; document.Info.CreationDate = DateTime.Now; //create new pdf page PdfPage page = document.AddPage(); page.Width = XUnit.FromMillimeter(210); page.Height = XUnit.FromMillimeter(297); using (XGraphics gfx = XGraphics.FromPdfPage(page)) { //make sure the font is embedded var options = new XPdfFontOptions(PdfFontEncoding.Unicode); //declare a font for drawing in the PDF XFont fontEan = new XFont("mrvcode39s", 75, XFontStyle.Regular, options); XTextFormatter tf = new XTextFormatter(gfx); var stringFormat = new XStringFormat(); stringFormat.Alignment = XStringAlignment.Center; //create the barcode from string gfx.DrawString("12234", fontEan, XBrushes.Black, new XRect(15, 40, page.Width, page.Height), stringFormat); } document.Save("BarCodeTest3.pdf"); } }
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 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; } }
static void Main(string[] args) { var filepath = new DirectoryInfo(Directory.GetCurrentDirectory()); var pdfFiles = filepath.EnumerateFiles("*.pdf").OrderBy(f => f.CreationTimeUtc).ToList(); if (pdfFiles.Count < 2) { Console.WriteLine($"Found {pdfFiles.Count} files... nothing to do."); } else { Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); var pdfResult = new PdfDocument(); var font = new XFont("Consolas", 10, XFontStyle.Bold); var format = new XStringFormat { Alignment = XStringAlignment.Center, LineAlignment = XLineAlignment.Far }; foreach (var file in pdfFiles) { using (var pdfFile = PdfReader.Open(file.FullName, PdfDocumentOpenMode.Import)) { pdfResult.Pages.Add(pdfFile.Pages[0]); var page = pdfResult.Pages[^ 1];
public static void Variant1(PdfPage page, XFont font, string watermark) { // Variation 1: Draw a watermark as a text string. // Get an XGraphics object for drawing beneath the existing content. var gfx = XGraphics.FromPdfPage(page, XGraphicsPdfPageOptions.Prepend); // Get the size (in points) of the text. var 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(-System.Math.Atan(page.Height / page.Width) * 180 / System.Math.PI); gfx.TranslateTransform(-page.Width / 2, -page.Height / 2); // Create a string format. var 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); }
internal void DrawToPDF(PdfRectangle rect, PdfPage elementPage, XFont font, XStringFormat format) { if (!rect.IsEmpty) { using (var gfx = XGraphics.FromPdfPage(elementPage)) { // Note: Page origin [0,0] is bottom left ! var text = Text; if (text.Length > 0) { var xRect = new XRect(rect.X1, elementPage.Height.Point - rect.Y2, rect.Width, rect.Height); if ((Flags & PdfAcroFieldFlags.Comb) != 0 && MaxLength > 0) { var combWidth = xRect.Width / MaxLength; format.Comb = true; format.CombWidth = combWidth; gfx.Save(); gfx.IntersectClip(xRect); gfx.DrawString(text, font, new XSolidBrush(ForeColor), xRect + new XPoint(0, 1.5), format); gfx.Restore(); } else { gfx.Save(); gfx.IntersectClip(xRect); gfx.DrawString(text, font, new XSolidBrush(ForeColor), xRect + new XPoint(2, 2), format); gfx.Restore(); } } } } }
private void DrawTextAlignment(XGraphics gfx, int number) { base.BeginBox(gfx, number, "Text Alignment"); XRect xRect = new XRect(0.0, 0.0, 250.0, 140.0); XFont font = new XFont("Verdana", 10.0); XBrush purple = XBrushes.Purple; XStringFormat xStringFormat = new XStringFormat(); gfx.DrawRectangle(XPens.YellowGreen, xRect); gfx.DrawLine(XPens.YellowGreen, xRect.Width / 2.0, 0.0, xRect.Width / 2.0, xRect.Height); gfx.DrawLine(XPens.YellowGreen, 0.0, xRect.Height / 2.0, xRect.Width, xRect.Height / 2.0); gfx.DrawString("TopLeft", font, purple, xRect, xStringFormat); xStringFormat.Alignment = XStringAlignment.Center; gfx.DrawString("TopCenter", font, purple, xRect, xStringFormat); xStringFormat.Alignment = XStringAlignment.Far; gfx.DrawString("TopRight", font, purple, xRect, xStringFormat); xStringFormat.LineAlignment = XLineAlignment.Center; xStringFormat.Alignment = XStringAlignment.Near; gfx.DrawString("CenterLeft", font, purple, xRect, xStringFormat); xStringFormat.Alignment = XStringAlignment.Center; gfx.DrawString("Center", font, purple, xRect, xStringFormat); xStringFormat.Alignment = XStringAlignment.Far; gfx.DrawString("CenterRight", font, purple, xRect, xStringFormat); xStringFormat.LineAlignment = XLineAlignment.Far; xStringFormat.Alignment = XStringAlignment.Near; gfx.DrawString("BottomLeft", font, purple, xRect, xStringFormat); xStringFormat.Alignment = XStringAlignment.Center; gfx.DrawString("BottomCenter", font, purple, xRect, xStringFormat); xStringFormat.Alignment = XStringAlignment.Far; gfx.DrawString("BottomRight", font, purple, xRect, xStringFormat); base.EndBox(gfx); }
private void DrawText(XGraphics gfx, TextItem text) { XPdfFontOptions options = new XPdfFontOptions(PdfFontEncoding.Unicode, PdfFontEmbedding.Always); XFont font = new XFont("Calibri", Y(text.Size), XFontStyle.Regular, options); XStringFormat format = new XStringFormat(); XRect rect = new XRect(X(text.X), Y(text.Y), X(text.Width), Y(text.Height)); switch (text.HAlign) { case 0: format.Alignment = XStringAlignment.Near; break; case 1: format.Alignment = XStringAlignment.Center; break; case 2: format.Alignment = XStringAlignment.Far; break; } switch (text.VAlign) { case 0: format.LineAlignment = XLineAlignment.Near; break; case 1: format.LineAlignment = XLineAlignment.Center; break; case 2: format.LineAlignment = XLineAlignment.Far; break; } //var brushBackground = new XSolidBrush(XColor.FromArgb(text.Backgroud.Alpha, text.Backgroud.Red, text.Backgroud.Green, text.Backgroud.Blue)); //gfx.DrawRectangle(brushBackground, rect); var brushForeground = new XSolidBrush(XColor.FromArgb(text.Foreground.Alpha, text.Foreground.Red, text.Foreground.Green, text.Foreground.Blue)); gfx.DrawString(text.Text, font, brushForeground, rect, format); }
public PdfBuilder DrawString(string text, XFont font, int x, int y, XStringFormat stringFormat) { _gfx.DrawString(text, font, XBrushes.Black, new XRect(x, y, _page.Width, y), stringFormat); return(this); }
public void DrawString(string s, Font font, Brush brush, RectangleF layoutRectangle, StringFormat format) { XStringFormat xFormat = StringFormatToXStringFormat(format); XFont xFont = FontToXFont(font); XBrush xBrush = BrushToXBrush(brush); if (format.FormatFlags == StringFormatFlags.NoWrap) { //Single line string line = TrimString(s, layoutRectangle.Width, xFont, format.Trimming); _graphics.DrawString(line, xFont, xBrush, layoutRectangle, xFormat); } else { //Multiline int lineHeight = xFont.Height; List <string> lines = SetText(s, layoutRectangle.Width, (int)(layoutRectangle.Height / lineHeight), xFont); for (int i = 0; i < lines.Count; i++) { RectangleF rect = new RectangleF(layoutRectangle.X, layoutRectangle.Y + i * lineHeight, layoutRectangle.Width, lineHeight); _graphics.DrawString(lines[i], xFont, xBrush, rect, xFormat); } } }
public override void PdfDraw(XGraphics g) { XStringFormat format = new XStringFormat(); format.Alignment = XStringAlignment.Near; format.LineAlignment = XLineAlignment.Center; XBrush b = new XSolidBrush(Color.Black); int line = 0; for (int i = 0; i < textSplit.Count; i++) { for (int j = 0; j < textSplit[i].Count; j++) { if (line < GridSize.Height) { g.DrawString(textSplit[i][j], Settings.xfont, b, new Point(Left + 2, Top + (int)((line + .5) * ParentPage.ParentTest.Paper.BlockSize.Height)), format); line++; } else { break; } } } base.PdfDraw(g); }
/// <summary> /// Draws the data labels of the column chart. /// </summary> internal override void Draw() { ChartRendererInfo cri = (ChartRendererInfo)_rendererParms.RendererInfo; foreach (SeriesRendererInfo sri in cri.seriesRendererInfos) { if (sri._dataLabelRendererInfo == null) { continue; } XGraphics gfx = _rendererParms.Graphics; XFont font = sri._dataLabelRendererInfo.Font; XBrush fontColor = sri._dataLabelRendererInfo.FontColor; XStringFormat format = XStringFormats.Center; format.LineAlignment = XLineAlignment.Center; foreach (DataLabelEntryRendererInfo dataLabel in sri._dataLabelRendererInfo.Entries) { if (dataLabel.Text != null) { gfx.DrawString(dataLabel.Text, font, fontColor, dataLabel.Rect, format); } } } }
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); }
private static void EscreverFrente(PdfDocument outputDocument, XPdfForm form, UsuarioCertificadoCertame certificadoUsuario, XFont font, XStringFormat format) { var paginaFrente = outputDocument.AddPage(); paginaFrente.Orientation = PageOrientation.Landscape; paginaFrente.Size = PageSize.A4; form.PageNumber = 1; var manterPosicaoDado = new BMPosicaoDadoCertificadoCertame(); var posicaoNome = manterPosicaoDado.ObterPorDadoAno("nome", certificadoUsuario.CertificadoCertame.Ano); var posicaoCpf1 = manterPosicaoDado.ObterPorDadoAno("cpf1", certificadoUsuario.CertificadoCertame.Ano); var posicaoCpf2 = manterPosicaoDado.ObterPorDadoAno("cpf2", certificadoUsuario.CertificadoCertame.Ano); if (posicaoNome == null || posicaoCpf1 == null || posicaoCpf2 == null) { throw new Exception("Posição de dado obrigatório não informada na frente"); } var gfx = XGraphics.FromPdfPage(paginaFrente); gfx.DrawImage(form, new XRect(0, 0, form.PointWidth, form.PointHeight)); EscreverDado(paginaFrente, posicaoNome, gfx, font, format, certificadoUsuario.Usuario.Nome); EscreverDado(paginaFrente, posicaoCpf1, gfx, font, format, certificadoUsuario.Usuario.CPF.Substring(0, 9).Insert(3, ".").Insert(7, ".")); EscreverDado(paginaFrente, posicaoCpf2, gfx, font, format, certificadoUsuario.Usuario.CPF.Substring(9, 2)); if (certificadoUsuario.CertificadoCertame.Data.HasValue) { var data = certificadoUsuario.CertificadoCertame.Data.Value; var dataFormatada = string.Format("{0} de {1} de {2}", data.Day.ToString().PadLeft(2, '0'), data.ObterNomeMes(), data.Year); var posicaoData = manterPosicaoDado.ObterPorDadoAno("data", certificadoUsuario.CertificadoCertame.Ano); EscreverDado(paginaFrente, posicaoData, gfx, font, format, dataFormatada); } if (!string.IsNullOrWhiteSpace(certificadoUsuario.CertificadoCertame.NomeCertificado)) { var posicaoNomeCertificado = manterPosicaoDado.ObterPorDadoAno("nomecertificado", certificadoUsuario.CertificadoCertame.Ano); // Somente nesse caso, só insere o nome no PDF caso tenha o dado, pois alguns PDFs possuem o // nome neles, mas o campo "Nome" é obrigatório em todos os certificados. if (posicaoNomeCertificado != null) { var fontNomeCertificado = new XFont("Verdana", 13, XFontStyle.Bold); EscreverDado(paginaFrente, posicaoNomeCertificado, gfx, fontNomeCertificado, format, certificadoUsuario.CertificadoCertame.NomeCertificado.ToUpper()); } } }
public static XStringFormat GetFormat(StringFormatEx stringFormat) { var format = new XStringFormat(); format.Alignment = (XStringAlignment)Enum.Parse(typeof(XStringAlignment), stringFormat.Alignment.ToString()); format.LineAlignment = (XLineAlignment)Enum.Parse(typeof(XLineAlignment), stringFormat.LineAlignment.ToString()); return(format); }
/// <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 = _blocks.Count; for (int idx = 0; idx < count; idx++) { Block block = _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); } }
public override void DrawText(string text, TextType font, Vector2D pt, HAlignment hAlignment, VAlignment vAlignment, float fAngle) { XStringFormat format = new XStringFormat(); switch (hAlignment) { case HAlignment.HA_CENTER: format.Alignment = XStringAlignment.Center; break; case HAlignment.HA_LEFT: format.Alignment = XStringAlignment.Near; break; case HAlignment.HA_RIGHT: format.Alignment = XStringAlignment.Far; break; default: break; } switch (vAlignment) { case VAlignment.VA_BOTTOM: format.LineAlignment = XLineAlignment.Far; break; case VAlignment.VA_MIDDLE: format.LineAlignment = XLineAlignment.Center; break; case VAlignment.VA_TOP: format.LineAlignment = XLineAlignment.Near; break; default: break; } this.pdfGfx.DrawString( text , ToFont(font) , LineTypeToPdfBrush(PicGraphics.LT.LT_COTATION) , new XPoint(DX(pt.X), DY(pt.Y)) , format); }
// ----- DrawString --------------------------------------------------------------------------- public void DrawString(string s, XFont font, XBrush brush, XRect rect, XStringFormat format) { double x = rect.X; double y = rect.Y; double lineSpace = font.GetHeight(); double cyAscent = lineSpace * font.CellAscent / font.CellSpace; double cyDescent = lineSpace * font.CellDescent / font.CellSpace; double width = _gfx.MeasureString(s, font).Width; //bool bold = (font.Style & XFontStyle.Bold) != 0; //bool italic = (font.Style & XFontStyle.Italic) != 0; bool italicSimulation = (font.GlyphTypeface.StyleSimulations & XStyleSimulations.ItalicSimulation) != 0; bool boldSimulation = (font.GlyphTypeface.StyleSimulations & XStyleSimulations.BoldSimulation) != 0; bool strikeout = (font.Style & XFontStyle.Strikeout) != 0; bool underline = (font.Style & XFontStyle.Underline) != 0; Realize(font, brush, boldSimulation ? 2 : 0); switch (format.Alignment) { case XStringAlignment.Near: // nothing to do break; case XStringAlignment.Center: x += (rect.Width - width) / 2; break; case XStringAlignment.Far: x += rect.Width - width; 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 += (cyAscent * 3 / 4) / 2 + rect.Height / 2; break; case XLineAlignment.Far: y += -cyDescent + rect.Height; break; case XLineAlignment.BaseLine: // Nothing to do. break; } } else { 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; } } PdfFont realizedFont = _gfxState._realizedFont; Debug.Assert(realizedFont != null); realizedFont.AddChars(s); const string format2 = Config.SignificantFigures4; OpenTypeDescriptor descriptor = realizedFont.FontDescriptor._descriptor; string text = null; if (font.Unicode) { StringBuilder sb = new StringBuilder(); bool isSymbolFont = descriptor.FontFace.cmap.symbol; for (int idx = 0; idx < s.Length; idx++) { char ch = s[idx]; if (isSymbolFont) { // Remap ch for symbol fonts. ch = (char)(ch | (descriptor.FontFace.os2.usFirstCharIndex & 0xFF00)); // @@@ refactor } int glyphID = descriptor.CharCodeToGlyphIndex(ch); sb.Append((char)glyphID); } s = sb.ToString(); byte[] bytes = PdfEncoders.RawUnicodeEncoding.GetBytes(s); bytes = PdfEncoders.FormatStringLiteral(bytes, true, false, true, null); text = PdfEncoders.RawEncoding.GetString(bytes, 0, bytes.Length); } else { byte[] bytes = PdfEncoders.WinAnsiEncoding.GetBytes(s); text = PdfEncoders.ToStringLiteral(bytes, false, null); } // Map absolute position to PDF world space. XPoint pos = new XPoint(x, y); pos = WorldToView(pos); double verticalOffset = 0; if (boldSimulation) { // Adjust baseline in case of bold simulation??? // No, because this would change the center of the glyphs. //verticalOffset = font.Size * Const.BoldEmphasis / 2; } #if ITALIC_SIMULATION if (italicSimulation) { if (_gfxState.ItalicSimulationOn) { AdjustTdOffset(ref pos, verticalOffset, true); AppendFormatArgs("{0:" + format2 + "} {1:" + format2 + "} Td\n{2} Tj\n", pos.X, pos.Y, text); } else { // Italic simulation is done by skewing characters 20° to the right. XMatrix m = new XMatrix(1, 0, Const.ItalicSkewAngleSinus, 1, pos.X, pos.Y); AppendFormatArgs("{0:" + format2 + "} {1:" + format2 + "} {2:" + format2 + "} {3:" + format2 + "} {4:" + format2 + "} {5:" + format2 + "} Tm\n{6} Tj\n", m.M11, m.M12, m.M21, m.M22, m.OffsetX, m.OffsetY, text); _gfxState.ItalicSimulationOn = true; AdjustTdOffset(ref pos, verticalOffset, false); } } else { if (_gfxState.ItalicSimulationOn) { XMatrix m = new XMatrix(1, 0, 0, 1, pos.X, pos.Y); AppendFormatArgs("{0:" + format2 + "} {1:" + format2 + "} {2:" + format2 + "} {3:" + format2 + "} {4:" + format2 + "} {5:" + format2 + "} Tm\n{6} Tj\n", m.M11, m.M12, m.M21, m.M22, m.OffsetX, m.OffsetY, text); _gfxState.ItalicSimulationOn = false; AdjustTdOffset(ref pos, verticalOffset, false); } else { AdjustTdOffset(ref pos, verticalOffset, false); AppendFormatArgs("{0:" + format2 + "} {1:" + format2 + "} Td {2} Tj\n", pos.X, pos.Y, text); } } #else AdjustTextMatrix(ref pos); AppendFormat2("{0:" + format2 + "} {1:" + format2 + "} Td {2} Tj\n", pos.X, pos.Y, text); #endif if (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); double underlineRectY = Gfx.PageDirection == XPageDirection.Downwards ? y - underlinePosition : y + underlinePosition - underlineThickness; DrawRectangle(null, brush, x, underlineRectY, width, underlineThickness); } if (strikeout) { 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); double strikeoutRectY = Gfx.PageDirection == XPageDirection.Downwards ? y - strikeoutPosition : y + strikeoutPosition - strikeoutSize; DrawRectangle(null, brush, x, strikeoutRectY, width, strikeoutSize); } }
// ----- DrawString --------------------------------------------------------------------------- public void DrawString(string s, XFont font, XBrush brush, XRect rect, XStringFormat format) { Realize(font, brush, 0); double x = rect.X; double y = rect.Y; double lineSpace = font.GetHeight(this.gfx); //int cellSpace = font.cellSpace; // font.FontFamily.GetLineSpacing(font.Style); //int cellAscent = font.cellAscent; // font.FontFamily.GetCellAscent(font.Style); //int cellDescent = font.cellDescent; // font.FontFamily.GetCellDescent(font.Style); //double cyAscent = lineSpace * cellAscent / cellSpace; //double cyDescent = lineSpace * cellDescent / cellSpace; double cyAscent = lineSpace * font.cellAscent / font.cellSpace; double cyDescent = lineSpace * font.cellDescent / font.cellSpace; double width = this.gfx.MeasureString(s, font).Width; 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; switch (format.Alignment) { case XStringAlignment.Near: // nothing to do break; case XStringAlignment.Center: x += (rect.Width - width) / 2; break; case XStringAlignment.Far: x += rect.Width - width; 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 += (cyAscent * 3 / 4) / 2 + rect.Height / 2; break; case XLineAlignment.Far: y += -cyDescent + rect.Height; break; case XLineAlignment.BaseLine: // nothing to do break; } } else { 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; } } PdfFont realizedFont = this.gfxState.realizedFont; Debug.Assert(realizedFont != null); realizedFont.AddChars(s); OpenTypeDescriptor descriptor = realizedFont.FontDescriptor.descriptor; if (bold && !descriptor.IsBoldFace) { // TODO: emulate bold by thicker outline } if (italic && !descriptor.IsBoldFace) { // TODO: emulate italic by shearing transformation } if (font.Unicode) { string s2 = ""; for (int idx = 0; idx < s.Length; idx++) { char ch = s[idx]; int glyphID = 0; if (descriptor.fontData.cmap.symbol) { glyphID = (int)ch + (descriptor.fontData.os2.usFirstCharIndex & 0xFF00); glyphID = descriptor.CharCodeToGlyphIndex((char)glyphID); } else glyphID = descriptor.CharCodeToGlyphIndex(ch); s2 += (char)glyphID; } s = s2; byte[] bytes = PdfEncoders.RawUnicodeEncoding.GetBytes(s); bytes = PdfEncoders.FormatStringLiteral(bytes, true, false, true, null); string text = PdfEncoders.RawEncoding.GetString(bytes, 0, bytes.Length); XPoint pos = new XPoint(x, y); AdjustTextMatrix(ref pos); AppendFormat( "{0:0.####} {1:0.####} Td {2} Tj\n", pos.x, pos.y, text); //PdfEncoders.ToStringLiteral(s, PdfStringEncoding.RawEncoding, null)); } else { byte[] bytes = PdfEncoders.WinAnsiEncoding.GetBytes(s); XPoint pos = new XPoint(x, y); AdjustTextMatrix(ref pos); AppendFormat( "{0:0.####} {1:0.####} Td {2} Tj\n", pos.x, pos.y, PdfEncoders.ToStringLiteral(bytes, false, null)); } if (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) { 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); } }