/// <summary> /// Renders the matrix code. /// </summary> protected internal override void Render(XGraphics gfx, XBrush brush, XPoint position) { XGraphicsState state = gfx.Save(); switch (Direction) { case CodeDirection.RightToLeft: gfx.RotateAtTransform(180, position); break; case CodeDirection.TopToBottom: gfx.RotateAtTransform(90, position); break; case CodeDirection.BottomToTop: gfx.RotateAtTransform(-90, position); break; } XPoint pos = position + CalcDistance(Anchor, AnchorType.TopLeft, Size); if (MatrixImage == null) MatrixImage = DataMatrixImage.GenerateMatrixImage(Text, Encoding, Rows, Columns); if (QuietZone > 0) { XSize sizeWithZone = new XSize(Size.Width, Size.Height); sizeWithZone.Width = sizeWithZone.Width / (Columns + 2 * QuietZone) * Columns; sizeWithZone.Height = sizeWithZone.Height / (Rows + 2 * QuietZone) * Rows; XPoint posWithZone = new XPoint(pos.X, pos.Y); posWithZone.X += Size.Width / (Columns + 2 * QuietZone) * QuietZone; posWithZone.Y += Size.Height / (Rows + 2 * QuietZone) * QuietZone; gfx.DrawRectangle(XBrushes.White, pos.X, pos.Y, Size.Width, Size.Height); gfx.DrawImage(MatrixImage, posWithZone.X, posWithZone.Y, sizeWithZone.Width, sizeWithZone.Height); } else gfx.DrawImage(MatrixImage, pos.X, pos.Y, Size.Width, Size.Height); gfx.Restore(state); }
public BarCodeRenderInfo(XGraphics gfx, XBrush brush, XFont font, XPoint position) { Gfx = gfx; Brush = brush; Font = font; Position = position; }
public XGraphicsPdfRenderer(XForm form, XGraphics gfx) { this.form = form; this.colorMode = form.Owner.Options.ColorMode; this.gfx = gfx; this.content = new StringBuilder(); form.pdfRenderer = this; this.gfxState = new PdfGraphicsState(this); }
public XGraphicsPdfRenderer(PdfPage page, XGraphics gfx, XGraphicsPdfPageOptions options) { _page = page; _colorMode = page._document.Options.ColorMode; _options = options; _gfx = gfx; _content = new StringBuilder(); page.RenderContent._pdfRenderer = this; _gfxState = new PdfGraphicsState(this); }
public XGraphicsPdfRenderer(PdfPage page, XGraphics gfx, XGraphicsPdfPageOptions options) { this.page = page; this.colorMode = page.document.Options.ColorMode; this.options = options; #if MIGRADOC this.options = options & ~XGraphicsPdfPageOptions.PDFlibHack; pdflibHack = (options & XGraphicsPdfPageOptions.PDFlibHack) != 0; #endif this.gfx = gfx; this.content = new StringBuilder(); page.RenderContent.pdfRenderer = this; this.gfxState = new PdfGraphicsState(this); }
/// <summary> /// Renders the OMR code. /// </summary> protected internal override void Render(XGraphics gfx, XBrush brush, XFont font, XPoint position) { XGraphicsState state = gfx.Save(); switch (Direction) { case CodeDirection.RightToLeft: gfx.RotateAtTransform(180, position); break; case CodeDirection.TopToBottom: gfx.RotateAtTransform(90, position); break; case CodeDirection.BottomToTop: gfx.RotateAtTransform(-90, position); break; } //XPoint pt = center - size / 2; XPoint pt = position - CodeBase.CalcDistance(AnchorType.TopLeft, Anchor, Size); uint value; uint.TryParse(Text, out value); #if true // HACK: Project Wallenwein: set LK value |= 1; _synchronizeCode = true; #endif if (_synchronizeCode) { XRect rect = new XRect(pt.X, pt.Y, _makerThickness, Size.Height); gfx.DrawRectangle(brush, rect); pt.X += 2 * _makerDistance; } for (int idx = 0; idx < 32; idx++) { if ((value & 1) == 1) { XRect rect = new XRect(pt.X + idx * _makerDistance, pt.Y, _makerThickness, Size.Height); gfx.DrawRectangle(brush, rect); } value = value >> 1; } gfx.Restore(state); }
public GraphicsStateStack(XGraphics gfx) { current = new InternalGraphicsState(gfx); }
public override void Initialize() { // instantiate document pdfDocument = new PdfDocument(); pdfDocument.Info.Title = title; pdfDocument.Info.Author = author; // add a page PdfPage page = pdfDocument.AddPage(); page.Orientation = PageOrientation.Portrait; // set page size page.Width = XUnit.FromMillimeter(bbox.Width); page.Height = XUnit.FromMillimeter(bbox.Height); // get graphics this.pdfGfx = XGraphics.FromPdfPage(page); // draw a bounding box XRect rect = new XRect(0.5, 0.5, page.Width - 1, page.Height - 1); this.pdfGfx.DrawRectangle(XBrushes.White, rect); // initialize cotation PicCotation._globalCotationProperties._arrowLength = XUnit.FromMillimeter(bbox.Height) / 50.0; }
private PdfDocument GetDocuments(IEnumerable <XElement> elements, IXmlNamespaceResolver resolver) { if (this.XSLT != null) { elements = elements.Select(e => { var transformer = new XslCompiledTransform(); using (var reader = XmlReader.Create(this.XSLT.Value.GetValue(e, resolver))) transformer.Load(reader); //transformer.XmlResolver = resolver; var builder = new StringBuilder(); using (var writer = XmlWriter.Create(builder)) { transformer.Transform(e.CreateNavigator(), writer); return(XDocument.Parse(builder.ToString()).Root); } }).ToArray(); } var document = new PdfDocument { PageLayout = PdfPageLayout.SinglePage }; foreach (var context in elements) { var page = document.AddPage(); page.Width = this.Width; page.Height = this.Height; if (this.MediatBox.HasValue) { page.MediaBox = new PdfRectangle(this.MediatBox.Value); } if (this.CroptBox.HasValue) { page.CropBox = new PdfRectangle(this.CroptBox.Value); } if (this.BleedtBox.HasValue) { page.BleedBox = new PdfRectangle(this.BleedtBox.Value); } if (this.TrimtBox.HasValue) { page.TrimBox = new PdfRectangle(this.TrimtBox.Value); } if (this.ArtBox.HasValue) { page.ArtBox = new PdfRectangle(this.ArtBox.Value); } // Get an XGraphics object for drawing using (var gfx = XGraphics.FromPdfPage(page)) { // Create a font foreach (var item in this.Elements.Reverse().OrderBy(x => x.ZIndex.GetValue(context, resolver))) { if (!item.IsVisible.GetValue(context, resolver)) { continue; } using (gfx.RotateTransform(item, context, resolver)) { var frame = item.Position.GetValue(context, resolver); gfx.IntersectClip(frame); if (item is TextElement textElement) { this.HandleTextElement(resolver, context, gfx, textElement); } else if (item is ImageElement imageElement) { var position = imageElement.Position.GetValue(context, resolver); using (var stream = imageElement.ImagePath.GetValue(context, resolver)) using (var image = XImage.FromStream(stream)) gfx.DrawImage(image, position); } else if (item is RectElement rectElement) { var position = rectElement.Position.GetValue(context, resolver); gfx.DrawRectangle(rectElement.BorderColor, rectElement.FillColor, rectElement.Position.GetValue(context, resolver)); } else { throw new NotSupportedException($"Element of Type {item?.GetType()} is not supported."); } } } //// Draw the text //gfx.DrawString("Hello, World!", font, XBrushes.Black, // new XRect(0, 0, page.Width, page.Height), // XStringFormats.Center); } } return(document); }
private List <(XLineAlignment horizontalAlignment, List <List <(string textToPrint, XFont font, XBrush brush, XPoint printPosition, XLineAlignment alignment, XSize size)> > lines)> SimulatePrint(IXmlNamespaceResolver resolver, XElement context, XGraphics gfx, TextElement textElement, double emScale) { var frame = textElement.Position.GetValue(context, resolver); var startPosition = frame.Location; var currentPosition = startPosition; var paragraphs = textElement.Paragraphs.SelectMany(x => TransformParapgraps(x, resolver, context)); var paragraphsToDraw = new List <(XLineAlignment horizontalAlignment, List <List <(string textToPrint, XFont font, XBrush brush, XPoint printPosition, XLineAlignment alignment, XSize size)> > lines)>(); foreach (var paragraph in paragraphs) { if (!paragraph.IsVisible.GetValue(context, resolver)) { continue; } var lines = new List <List <(string textToPrint, XFont font, XBrush brush, XPoint printPosition, XLineAlignment alignment, XSize size)> >(); paragraphsToDraw.Add((paragraph.Alignment.GetValue(context, resolver), lines)); var currentLine = new List <(string textToPrint, XFont font, XBrush brush, XPoint printPosition, XLineAlignment alignment, XSize size)>(); currentPosition = new XPoint(currentPosition.X, currentPosition.Y + paragraph.BeforeParagraph.GetValue(context, resolver) * emScale); foreach (var run in paragraph.Runs) { if (!this.ExpandRuns(run, paragraph, gfx, frame, startPosition, ref currentPosition, lines, currentLine, resolver, context, emScale)) { break; } } currentPosition = new XPoint(startPosition.X, currentPosition.Y + lines.Where(x => x.Count > 0).LastOrDefault()?.Max(x => x.size.Height) ?? 0 + paragraph.AfterParagraph.GetValue(context, resolver) * emScale); } return(paragraphsToDraw); }
internal BordersRenderer(Borders borders, XGraphics gfx) { Debug.Assert(borders.Document != null); _gfx = gfx; _borders = borders; }
private void CheckBtn_OnClick(object sender, RoutedEventArgs e) { var titleLines = new List <string> { $"Check №{_currentSale.CheckNumber,33}", $"Employee:{_currentSale.FullName,31}", $"Date:{_currentSale.Date,35}", "----------------------------------------" }; var goodsList = new List <string>(); foreach (var universalBasketDto in UniversalBasketDtos) { goodsList.Add("----------------------------------------"); goodsList.Add($"{universalBasketDto.Producer}"); goodsList.Add($"{universalBasketDto.Title,10}"); goodsList.Add($"{universalBasketDto.Amount,20}{universalBasketDto.Price,20}"); } var totalList = new List <string> { "----------------------------------------", "----------------------------------------" }; if (_currentSale.AccountNumber != null && _currentSale.AccountNumber != "") { totalList.Add($"{"Discount:",30}{"5%",10}"); } totalList.Add($"{"Total:",30}{_currentSale.Total,10}"); if (File.Exists($"Check{_currentSale.CheckNumber}.pdf")) { File.Delete($"Check{_currentSale.CheckNumber}.pdf"); } var pdf = new PdfDocument(); var pdfPage = pdf.Pages.Add(); var graph = XGraphics.FromPdfPage(pdfPage); var titleFont = new XFont("Consolas", 8, XFontStyle.Bold); var font = new XFont("Consolas", 8, XFontStyle.Regular); var tf = new XTextFormatter(graph); var yPoint = 0; foreach (var titleLine in titleLines) { tf.Alignment = XParagraphAlignment.Left; tf.DrawString(titleLine, titleFont, XBrushes.Black, new XRect(8, yPoint, pdfPage.Width, pdfPage.Height), XStringFormats.TopLeft); yPoint += 8; } foreach (var good in goodsList) { tf.Alignment = XParagraphAlignment.Left; tf.DrawString(good, font, XBrushes.Black, new XRect(8, yPoint, pdfPage.Width, pdfPage.Height), XStringFormats.TopLeft); yPoint += 8; } foreach (var total in totalList) { tf.Alignment = XParagraphAlignment.Left; tf.DrawString(total, titleFont, XBrushes.Black, new XRect(8, yPoint, pdfPage.Width, pdfPage.Height), XStringFormats.TopLeft); yPoint += 8; } var pdfFilename = $"Check{_currentSale.CheckNumber}.pdf"; pdf.Save(pdfFilename); Process.Start("C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe", Path.GetFullPath(pdfFilename)); }
/// <summary> /// This method will Generate the invoice as a pdf file. /// </summary> /// <param name="dtBody">this datatable will contain all article information in the invoice</param> /// <param name="dtHead">this datatable will contain all information related to this invoice</param> /// <param name="dtVat">this datatable will contain all types of VAT summary exist in the invoice</param> /// <param name="invoiceId">Supplied invoiceid</param> private void ReportGenerator(DataTable dtBody, DataTable dtHead, DataTable dtVat, string invoiceId, DataTable dtPrice) { Double totalShippingCost = 0.00; Double totalVat = 0.00; Double subTotal = 0.00; Double invoiceTotal = 0.00; for (int i = 0; i < dtBody.Rows.Count; i++) { subTotal += Double.Parse(dtBody.Rows[i][5].ToString());// +Double.Parse(dtBody.Rows[i][8].ToString()); totalVat += Double.Parse(dtBody.Rows[i][8].ToString()); } string sql = "select sum(o.shippingcost) as total from orders o" + " where o.orderid in(select orderid from invoiceline where invoiceid='" + invoiceId + "')"; DataTable dtShipCost = dbHandler.GetDataTable(sql); totalShippingCost = Double.Parse(dtShipCost.Rows[0]["total"].ToString()); if (!dtHead.Rows[0]["customerbtwnr"].ToString().Equals("")) { invoiceTotal = subTotal;// +totalShippingCost; //invoiceTotal = subTotal + totalShippingCost; } else { invoiceTotal = subTotal + totalVat; } //Print Invoice XForm form = new XForm(report.document, XUnit.FromMillimeter(1000), XUnit.FromMillimeter(400)); XGraphics graphics = XGraphics.FromForm(form); double xInit = 0, yInit = 0; graphics.DrawString(CulturalValues[0], report._largeFontBold, XBrushes.Black, xInit, yInit, XStringFormat.TopLeft); report.gfx.DrawImage(form, 390, 40); // Print Customer Address dthead1 = dtHead; form = new XForm(report.document, XUnit.FromMillimeter(1000), XUnit.FromMillimeter(400)); graphics = XGraphics.FromForm(form); xInit = 95; yInit = 20; //graphics.DrawRectangle(report._borderPen, 0, 0, 300, 100); graphics.DrawString(dtHead.Rows[0]["companyname"].ToString().Trim(), report._normalFont, XBrushes.Black, xInit, yInit - report._lineGap, XStringFormat.TopLeft); graphics.DrawString(dtHead.Rows[0]["customer"].ToString().Trim(), report._normalFont, XBrushes.Black, xInit, yInit, XStringFormat.TopLeft); graphics.DrawString(dtHead.Rows[0]["address"].ToString() + " " + dtHead.Rows[0]["housenr"].ToString(), report._normalFont, XBrushes.Black, xInit, yInit + report._lineGap, XStringFormat.TopLeft); graphics.DrawString(dtHead.Rows[0]["postcode"].ToString() + " " + dtHead.Rows[0]["residence"].ToString(), report._normalFont, XBrushes.Black, xInit, yInit + report._lineGap * 2, XStringFormat.TopLeft); graphics.DrawString(dtHead.Rows[0]["country"].ToString(), report._normalFont, XBrushes.Black, xInit, yInit + report._lineGap * 3, XStringFormat.TopLeft); report.gfx.DrawImage(form, 245, 130); // Print Our VAT No + Bankaccount details form = new XForm(report.document, XUnit.FromMillimeter(1000), XUnit.FromMillimeter(400)); graphics = XGraphics.FromForm(form); xInit = 5; yInit = 5; graphics.DrawRectangle(XBrushes.Gray, 0, 0, 300, 20); graphics.DrawString(CulturalValues[1], report._smallFont, XBrushes.White, xInit, yInit, XStringFormat.TopLeft); graphics.DrawString(CulturalValues[2], report._smallFont, XBrushes.White, xInit + 120, yInit, XStringFormat.TopLeft); graphics.DrawRectangle(new XSolidBrush(XColor.FromArgb(120, 204, 204, 204)), 0, 20, xInit + 115, 60); graphics.DrawString("NL006012152B01", report._smallFontBold, XBrushes.Black, 5, yInit + 25, XStringFormat.TopLeft); graphics.DrawRectangle(new XSolidBrush(XColor.FromArgb(80, 204, 204, 204)), xInit + 115, 20, 180, 60); graphics.DrawString("ABNAMRO:", report._smallFont, XBrushes.Black, xInit + 120, yInit + 25, XStringFormat.TopLeft); graphics.DrawString("61 26 26 032", report._smallFontBold, XBrushes.Black, xInit + 200, yInit + 25, XStringFormat.TopLeft); graphics.DrawString("IBAN:", report._smallFont, XBrushes.Black, xInit + 120, yInit + 25 + report._lineGap, XStringFormat.TopLeft); graphics.DrawString("NL08ABNA0612626032", report._smallFontBold, XBrushes.Black, xInit + 200, yInit + 25 + report._lineGap, XStringFormat.TopLeft); graphics.DrawString("BIC:", report._smallFont, XBrushes.Black, xInit + 120, yInit + 25 + report._lineGap * 2, XStringFormat.TopLeft); graphics.DrawString("ABNANL2A", report._smallFontBold, XBrushes.Black, xInit + 200, yInit + 25 + report._lineGap * 2, XStringFormat.TopLeft); report.gfx.DrawImage(form, 28, 260); //print For payment please quote iid = invoiceId; form = new XForm(report.document, XUnit.FromMillimeter(1000), XUnit.FromMillimeter(400)); graphics = XGraphics.FromForm(form); xInit = 5; yInit = 5; graphics.DrawRectangle(XBrushes.Gray, 0, 0, 230, 20); graphics.DrawString(CulturalValues[3], report._smallFont, XBrushes.White, xInit, yInit, XStringFormat.TopLeft); graphics.DrawRectangle(new XSolidBrush(XColor.FromArgb(120, 204, 204, 204)), 0, 20, 230, 60); graphics.DrawString(CulturalValues[4], report._smallFont, XBrushes.Black, 5, yInit + 25, XStringFormat.TopLeft); graphics.DrawString(dtHead.Rows[0]["customerid"].ToString().Trim(), report._smallFontBold, XBrushes.Black, xInit + 100, yInit + 25, XStringFormat.TopLeft); graphics.DrawString(CulturalValues[5], report._smallFont, XBrushes.Black, 5, yInit + 25 + report._lineGap, XStringFormat.TopLeft); graphics.DrawString(invoiceId, report._smallFontBold, XBrushes.Black, xInit + 100, yInit + 25 + report._lineGap, XStringFormat.TopLeft); graphics.DrawString(CulturalValues[6], report._smallFont, XBrushes.Black, 5, yInit + 25 + report._lineGap * 2, XStringFormat.TopLeft); string s = dtHead.Rows[0]["invoicedate"].ToString(); graphics.DrawString(s, report._smallFontBold, XBrushes.Black, xInit + 100, yInit + 25 + report._lineGap * 2, XStringFormat.TopLeft); graphics.DrawRectangle(report._borderPen, 0, 0, 230, 80); report.gfx.DrawImage(form, 333, 260); //VAT basis + VAT amount form = new XForm(report.document, XUnit.FromMillimeter(1000), XUnit.FromMillimeter(400)); graphics = XGraphics.FromForm(form); xInit = 5; yInit = 5; double seg_width = 70; XTextFormatter tf = new XTextFormatter(graphics); graphics.DrawRectangle(XBrushes.Gray, 0, 0, 230, 20); graphics.DrawString(CulturalValues[7], report._smallFont, XBrushes.White, 98, yInit, XStringFormat.TopLeft); graphics.DrawString(CulturalValues[8], report._smallFont, XBrushes.White, 180, yInit, XStringFormat.TopLeft); graphics.DrawRectangle(new XSolidBrush(XColor.FromArgb(120, 204, 204, 204)), 0, 20, seg_width, 60); graphics.DrawRectangle(new XSolidBrush(XColor.FromArgb(80, 204, 204, 204)), seg_width, 20, seg_width, 60); graphics.DrawRectangle(new XSolidBrush(XColor.FromArgb(120, 204, 204, 204)), seg_width * 2, 20, 90, 60); graphics.DrawString(CulturalValues[9], report._smallFont, XBrushes.Black, 5, yInit + 25, XStringFormat.TopLeft); XRect rec = new XRect(seg_width, yInit + 25, 65, 20); tf.Alignment = XParagraphAlignment.Right; if (!dtHead.Rows[0]["customerbtwnr"].ToString().Equals("")) { Double vatBasis = double.Parse(dtPrice.Rows[0]["price0"].ToString()) + double.Parse(dtPrice.Rows[0]["price6"].ToString()) + double.Parse(dtPrice.Rows[0]["price19"].ToString()); tf.DrawString("€".PadRight(25), report._smallFont, XBrushes.Black, rec); tf.DrawString(vatBasis.ToString("N2"), report._smallFont, XBrushes.Black, rec); rec = new XRect(seg_width * 2, yInit + 25, 85, 20); tf.DrawString("€".PadRight(25), report._smallFont, XBrushes.Black, rec); tf.DrawString("0.00", report._smallFont, XBrushes.Black, rec); graphics.DrawString(CulturalValues[10], report._smallFont, XBrushes.Black, 5, yInit + 25 + report._lineGap, XStringFormat.TopLeft); rec = new XRect(seg_width, yInit + 25 + report._lineGap, 65, 20); tf.DrawString("€".PadRight(25), report._smallFont, XBrushes.Black, rec); tf.DrawString("0.00", report._smallFont, XBrushes.Black, rec); rec = new XRect(seg_width * 2, yInit + 25 + report._lineGap, 85, 20); tf.DrawString("€".PadRight(25), report._smallFont, XBrushes.Black, rec); tf.DrawString("0.00", report._smallFont, XBrushes.Black, rec); graphics.DrawString(CulturalValues[11], report._smallFont, XBrushes.Black, 5, yInit + 25 + report._lineGap * 2, XStringFormat.TopLeft); rec = new XRect(seg_width, yInit + 25 + report._lineGap * 2, 65, 20); tf.DrawString("€".PadRight(25), report._smallFont, XBrushes.Black, rec); tf.DrawString("0.00", report._smallFont, XBrushes.Black, rec); rec = new XRect(seg_width * 2, yInit + 25 + report._lineGap * 2, 85, 20); tf.DrawString("€".PadRight(25), report._smallFont, XBrushes.Black, rec); tf.DrawString("0.00", report._smallFont, XBrushes.Black, rec); graphics.DrawString(CulturalValues[12], report._smallFont, XBrushes.Black, 5, yInit + 25 + report._lineGap * 4, XStringFormat.TopLeft); graphics.DrawString(dtHead.Rows[0]["customerbtwnr"].ToString(), report._smallFont, XBrushes.Black, 100, yInit + 25 + report._lineGap * 4, XStringFormat.TopLeft); } else { tf.DrawString("€".PadRight(25), report._smallFont, XBrushes.Black, rec); tf.DrawString(double.Parse(dtPrice.Rows[0]["price0"].ToString()).ToString("N2"), report._smallFont, XBrushes.Black, rec); rec = new XRect(seg_width * 2, yInit + 25, 85, 20); tf.DrawString("€".PadRight(25), report._smallFont, XBrushes.Black, rec); tf.DrawString(double.Parse(dtVat.Rows[0]["vat0"].ToString()).ToString("N2"), report._smallFont, XBrushes.Black, rec); graphics.DrawString(CulturalValues[10], report._smallFont, XBrushes.Black, 5, yInit + 25 + report._lineGap, XStringFormat.TopLeft); rec = new XRect(seg_width, yInit + 25 + report._lineGap, 65, 20); tf.DrawString("€".PadRight(25), report._smallFont, XBrushes.Black, rec); tf.DrawString(double.Parse(dtPrice.Rows[0]["price6"].ToString()).ToString("N2"), report._smallFont, XBrushes.Black, rec); rec = new XRect(seg_width * 2, yInit + 25 + report._lineGap, 85, 20); tf.DrawString("€".PadRight(25), report._smallFont, XBrushes.Black, rec); tf.DrawString(double.Parse(dtVat.Rows[0]["vat6"].ToString()).ToString("N2"), report._smallFont, XBrushes.Black, rec); graphics.DrawString(CulturalValues[11], report._smallFont, XBrushes.Black, 5, yInit + 25 + report._lineGap * 2, XStringFormat.TopLeft); rec = new XRect(seg_width, yInit + 25 + report._lineGap * 2, 65, 20); tf.DrawString("€".PadRight(25), report._smallFont, XBrushes.Black, rec); tf.DrawString(double.Parse(dtPrice.Rows[0]["price19"].ToString()).ToString("N2"), report._smallFont, XBrushes.Black, rec); rec = new XRect(seg_width * 2, yInit + 25 + report._lineGap * 2, 85, 20); tf.DrawString("€".PadRight(25), report._smallFont, XBrushes.Black, rec); tf.DrawString(double.Parse(dtVat.Rows[0]["vat19"].ToString()).ToString("N2"), report._smallFont, XBrushes.Black, rec); //graphics.DrawString(CulturalValues[12], report._smallFont, XBrushes.Black, 5, yInit + 25 + report._lineGap * 4, XStringFormat.TopLeft); //graphics.DrawString(dtHead.Rows[0]["customerbtwnr"].ToString(), report._smallFont, XBrushes.Black, 100, yInit + 25 + report._lineGap * 4, XStringFormat.TopLeft); } //report.gfx.DrawImage(form, 28, 720); //Page Number //string Show_page = "Page "+ s +" of "+seg_width +"."; totalpage = dtPage.Rows[0]["page"].ToString(); if (Convert.ToInt32(totalpage) >= 1) { pagenumber = 1; } string Show_page = "Page " + pagenumber + " of " + totalpage + " (" + invoiceId + ")."; pagenumber += 1; //graphics.DrawString(Show_page, report._smallFont, XBrushes.Black, 5, yInit + 25 + report._lineGap * 4, XStringFormat.TopLeft); graphics.DrawString(Show_page, report._smallFont, XBrushes.Black, 5, yInit + 90, XStringFormat.TopLeft); report.gfx.DrawImage(form, 28, 710); //if (dtHead.Rows[0]["customerbtwnr"].ToString().Equals("")) //Sub Total form = new XForm(report.document, XUnit.FromMillimeter(1000), XUnit.FromMillimeter(400)); graphics = XGraphics.FromForm(form); tf = new XTextFormatter(graphics); tf.Alignment = XParagraphAlignment.Right; xInit = 5; yInit = 5; graphics.DrawRectangle(XBrushes.Gray, 0, 0, 230, 20); graphics.DrawString(CulturalValues[13], report._smallFont, XBrushes.White, xInit, yInit, XStringFormat.TopLeft); graphics.DrawRectangle(new XSolidBrush(XColor.FromArgb(80, 204, 204, 204)), 100, 20, 130, 60); graphics.DrawString(CulturalValues[14], report._smallFont, XBrushes.Black, 5, yInit + 25, XStringFormat.TopLeft); graphics.DrawString(CulturalValues[26], report._smallFont, XBrushes.Black, 5, yInit + 25 + report._lineGap, XStringFormat.TopLeft); //graphics.DrawString("VAT: ", report._smallFontBold, XBrushes.Black, 5, yInit + 25 + report._lineGap, XStringFormat.TopLeft); graphics.DrawString(CulturalValues[16], report._smallFontBold, XBrushes.Black, 5, yInit + 25 + report._lineGap * 2, XStringFormat.TopLeft); rec = new XRect(100, yInit + 25, 100, 20); tf.DrawString("€".PadRight(25), report._smallFont, XBrushes.Black, rec); tf.DrawString(subTotal.ToString("N2"), report._smallFont, XBrushes.Black, rec); rec = new XRect(100, yInit + 25 + report._lineGap, 100, 20); tf.DrawString("€".PadRight(25), report._smallFont, XBrushes.Black, rec); if (!dtHead.Rows[0]["customerbtwnr"].ToString().Equals("")) { tf.DrawString("0.00", report._smallFont, XBrushes.Black, rec); } else { tf.DrawString(totalVat.ToString("N2"), report._smallFont, XBrushes.Black, rec); } rec = new XRect(100, yInit + 25 + report._lineGap * 2, 100, 20); tf.DrawString("€".PadRight(25), report._smallFontBold, XBrushes.Black, rec); tf.DrawString(invoiceTotal.ToString("N2"), report._smallFontBold, XBrushes.Black, rec); graphics.DrawString(CulturalValues[17], report._verySmallFont, XBrushes.Black, 115, yInit + 25 + report._lineGap * 3, XStringFormat.TopLeft); graphics.DrawString(CulturalValues[18], report._smallFont, XBrushes.Black, 5, yInit + 25 + report._lineGap * 4, XStringFormat.TopLeft); System.Globalization.CultureInfo enUS = new System.Globalization.CultureInfo("en-US", true); System.Globalization.DateTimeFormatInfo dtfi = new System.Globalization.DateTimeFormatInfo(); dtfi.ShortDatePattern = "dd-MM-yyyy"; dtfi.DateSeparator = "-"; DateTime dtIn = Convert.ToDateTime(s, dtfi); dtIn = dtIn.AddDays(14); graphics.DrawString(dtIn.ToString("dd-MM-yyyy"), report._smallFont, XBrushes.Black, 115, yInit + 25 + report._lineGap * 4, XStringFormat.TopLeft); graphics.DrawRectangle(report._borderPen, 0, 0, 230, 80); report.gfx.DrawImage(form, 333, 710); //Populate Article Details double[] colWidth = { 50, 220, 40, 60, 55, 60, 50 }; //string[] colName = {"Article ID", "Description", "Quantity", "Retail Price", "Discount", "Net Price", "VAT" }; form = new XForm(report.document, XUnit.FromMillimeter(1000), XUnit.FromMillimeter(400)); graphics = XGraphics.FromForm(form); PrintArticleDetail(colWidth, ref form, dtBody); report.gfx.DrawImage(form, 28, 350); }
public static bool ToPdf(this Document document, IEnumerable <ElementId> viewElementIds, string path, PdfSharp.PageSize pageSize = PdfSharp.PageSize.A4, ImageResolution imageResolution = ImageResolution.DPI_600) { if (document == null || viewElementIds == null || string.IsNullOrWhiteSpace(path)) { return(false); } if (!System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(path))) { return(false); } //Creating directory for temporary images string directory = System.IO.Path.Combine(System.IO.Path.GetTempPath(), System.Guid.NewGuid().ToString()); System.IO.Directory.CreateDirectory(directory); string name = string.IsNullOrEmpty(document.Title) ? "???" : document.Title; //Adjusting image pixel size int pixelSize = 512; switch (pageSize) { case PdfSharp.PageSize.A0: pixelSize = 14043; break; case PdfSharp.PageSize.A1: pixelSize = 9933; break; case PdfSharp.PageSize.A2: pixelSize = 7016; break; case PdfSharp.PageSize.A3: pixelSize = 4961; break; case PdfSharp.PageSize.A4: pixelSize = 3508; break; case PdfSharp.PageSize.A5: pixelSize = 2480; break; } //Adjusting image resolution switch (imageResolution) { case ImageResolution.DPI_600: pixelSize = pixelSize * 2; break; case ImageResolution.DPI_300: pixelSize = pixelSize * 1; break; case ImageResolution.DPI_150: pixelSize = System.Convert.ToInt32(pixelSize * 0.5); break; case ImageResolution.DPI_72: pixelSize = System.Convert.ToInt32(pixelSize * 0.25); break; } //Creating Revit Export Options for View Image ImageExportOptions imageExportOptions = new ImageExportOptions() { FilePath = System.IO.Path.Combine(directory, name), FitDirection = FitDirectionType.Horizontal, ZoomType = ZoomFitType.FitToPage, ImageResolution = imageResolution, HLRandWFViewsFileType = ImageFileType.PNG, ShadowViewsFileType = ImageFileType.PNG, PixelSize = pixelSize, ExportRange = ExportRange.SetOfViews }; //Exporting temporary images from Views. Necessary to do it one by one to keep view order List <string> imagePaths = new List <string>(); foreach (ElementId elementId in viewElementIds) { if (elementId == null) { continue; } View view = document.GetElement(elementId) as View; if (view == null) { continue; } imageExportOptions.SetViewsAndSheets(new List <ElementId>() { elementId }); document.ExportImage(imageExportOptions); foreach (string imagePath in System.IO.Directory.GetFiles(directory)) { if (!imagePaths.Contains(imagePath)) { imagePaths.Add(imagePath); break; } } } //Creating pdf Document from view images using (PdfDocument pdfDocument = new PdfDocument()) { foreach (string imagePath in imagePaths) { PdfPage pdfPage = pdfDocument.AddPage(); pdfPage.Size = pageSize; byte[] bytes = System.IO.File.ReadAllBytes(imagePath); using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(bytes, false)) { double widthFactor = 1; double heightFactor = 1; XImage xImage = XImage.FromStream(memoryStream); if (xImage.PointHeight > xImage.PointWidth) { pdfPage.Orientation = PdfSharp.PageOrientation.Portrait; widthFactor = xImage.PointWidth / pdfPage.Width.Point; } else { pdfPage.Orientation = PdfSharp.PageOrientation.Landscape; heightFactor = xImage.PointHeight / pdfPage.Height.Point; } XGraphics xGraphics = XGraphics.FromPdfPage(pdfPage); xGraphics.DrawImage(xImage, 0, 0, pdfPage.Width.Point * widthFactor, pdfPage.Height.Point * heightFactor); } } pdfDocument.Save(path); } //Removing temporary image files -> Not necessary foreach (string imagePath in imagePaths) { if (System.IO.File.Exists(imagePath)) { System.IO.File.Delete(imagePath); } } //Recursive removing whole temporary directory where view images were saved System.IO.Directory.Delete(directory, true); return(System.IO.File.Exists(path)); }
/// <summary>Creates the table.</summary> /// <param name="section">The section.</param> /// <param name="tableObj">The table to convert to html.</param> private void CreateTable(Section section, AutoDocumentation.Table tableObj) { var table = section.AddTable(); table.Style = tableObj.Style; table.Borders.Color = Colors.Blue; table.Borders.Width = 0.25; table.Borders.Left.Width = 0.5; table.Borders.Right.Width = 0.5; table.Rows.LeftIndent = 0; var fontSize = section.Document.Styles[tableObj.Style].Font.Size.Value; var gdiFont = new XFont("Arial", fontSize); XGraphics graphics = XGraphics.CreateMeasureContext(new XSize(2000, 2000), XGraphicsUnit.Point, XPageDirection.Downwards); // Add the required columns to the table. foreach (DataColumn column in tableObj.data.Table.Columns) { var column1 = table.AddColumn(); column1.Format.Alignment = ParagraphAlignment.Right; } // Add a heading row. var headingRow = table.AddRow(); headingRow.HeadingFormat = true; headingRow.Format.Font.Bold = true; headingRow.Shading.Color = Colors.LightBlue; for (int columnIndex = 0; columnIndex < tableObj.data.Table.Columns.Count; columnIndex++) { // Get column heading string heading = tableObj.data.Table.Columns[columnIndex].ColumnName; headingRow.Cells[columnIndex].AddParagraph(heading); // Get the width of the column double maxSize = graphics.MeasureString(heading, gdiFont).Width; for (int rowIndex = 0; rowIndex < tableObj.data.Count; rowIndex++) { // Add a row to our table if processing first column. Row row; if (columnIndex == 0) { table.AddRow(); } // Get the row to process. row = table.Rows[rowIndex + 1]; // Convert potential HTML to the cell in our row. HtmlToMigraDoc.Convert(tableObj.data[rowIndex][columnIndex].ToString(), row.Cells[columnIndex], WorkingDirectory, RelativePath); // Update the maximum size of the column with the value from the current row. foreach (var element in row.Cells[columnIndex].Elements) { if (element is Paragraph) { var paragraph = element as Paragraph; var contents = string.Empty; foreach (var paragraphElement in paragraph.Elements) { if (paragraphElement is Text) { contents += (paragraphElement as Text).Content; } else if (paragraphElement is Hyperlink) { contents += (paragraphElement as Hyperlink).Name; } } var size = graphics.MeasureString(contents, gdiFont); maxSize = Math.Max(maxSize, size.Width); } } } // Increase maxSize by a 'padding' value to allow for padding between the table cell // contents and the table borders. maxSize += 20; // maxWidth is the maximum allowed width of the column. E.g. if tableObj.ColumnWidth // is 50, then maxWidth is the amount of space taken up by 50 characters. // maxSize, on the other hand, is the length of the longest string in the column. // The actual column width is whichever of these two values is smaller. // MigraDoc will automatically wrap text to ensure the column respects this width. double maxWidth = graphics.MeasureString(new string('m', tableObj.ColumnWidth), gdiFont).Width; table.Columns[columnIndex].Width = Unit.FromPoint(Math.Min(maxWidth, maxSize) + 0); } section.AddParagraph(); }
public void EndBox(XGraphics gfx) { gfx.Restore(this.state); }
public static (PdfDocument document, (string crisisType, int startIndex)[]) CreateDocument(IEnumerable <CardData> cards, DateTime fileChanged, int currentInstance) { var pageWdith = XUnit.FromInch(2.5); var pageHeight = XUnit.FromInch(3.5); PdfDocument document = new PdfDocument(); document.Info.Title = "Forschungs Karten"; document.Info.Subject = "Die Forschungskarten des spiels"; document.Info.Author = "Arbeitstitel Karthago"; document.Info.Keywords = "Karten, Forschung, Karthago"; //var maxOccurenceOfCard = cards.Max(x => x.Metadata.Times); int counter = 0; var total = cards.Sum(x => x.Metadata.Times); string currentCardType = null; var resultList = new List <(string crisisType, int startIndex)>(); foreach (var card in cards) { if (card.Metadata.Type != null && currentCardType != null) { // Create new Back CrateBack(pageWdith, pageHeight, document, currentCardType); } if (card.Metadata.Type != null) { resultList.Add((card.Metadata.Type, document.PageCount)); } currentCardType = card.Metadata.Type ?? currentCardType; if (currentCardType is null) { Console.WriteLine($"{currentInstance}: Did not found card metadata. SKIP"); continue; } var header = card.Content.FirstOrDefault(x => x is HeaderBlock); Console.WriteLine($"{currentInstance}: Working on <{header?.ToString() ?? "UNKNOWN TITLE"}> with {card.Metadata.Times} instances."); for (int i = 0; i < card.Metadata.Times; i++) { Console.Write($"{i + 1}..."); counter++; PdfPage page = document.AddPage(); page.Width = new XUnit(pageWdith.Millimeter, XGraphicsUnit.Millimeter); page.Height = new XUnit(pageHeight.Millimeter, XGraphicsUnit.Millimeter); XGraphics gfx = XGraphics.FromPdfPage(page); // HACK² gfx.MUH = PdfFontEncoding.Unicode; //gfx.MFEH = PdfFontEmbedding.Default; XFont font = new XFont("Verdana", 13, XFontStyle.Regular); var costSize = new XSize(new XUnit(23, XGraphicsUnit.Millimeter), font.Height); var costMarginRight = new XUnit(5, XGraphicsUnit.Millimeter); var actionRect = new XRect(costMarginRight, new XUnit(5, XGraphicsUnit.Millimeter), pageHeight * 2, costSize.Height * 2); var actionTextRect = actionRect; actionTextRect.Height = costSize.Height; actionTextRect.Offset(new XUnit(3, XGraphicsUnit.Millimeter), 0); gfx.TranslateTransform(new XUnit(3, XGraphicsUnit.Millimeter), 0); gfx.RotateAtTransform(90, actionRect.TopLeft); gfx.DrawRoundedRectangle(XPens.MidnightBlue, XBrushes.DarkSlateBlue, actionRect, new XSize(10, 10)); gfx.DrawString(currentCardType, font, XBrushes.White, actionTextRect, XStringFormats.CenterLeft); gfx.RotateAtTransform(-90, actionRect.TopLeft); gfx.TranslateTransform(new XUnit(-3, XGraphicsUnit.Millimeter), 0); var circle = new XRect(new XUnit(-3, XGraphicsUnit.Millimeter), pageHeight - new XUnit(10, XGraphicsUnit.Millimeter), new XUnit(13, XGraphicsUnit.Millimeter), new XUnit(13, XGraphicsUnit.Millimeter)); gfx.DrawEllipse(XPens.MidnightBlue, XBrushes.White, circle); gfx.DrawString($"{card.Metadata.Duration:n0}", font, XBrushes.Black, circle, XStringFormats.Center); var dateRec = new XRect(new XUnit(13, XGraphicsUnit.Millimeter), pageHeight - new XUnit(2.5, XGraphicsUnit.Millimeter), new XUnit(13, XGraphicsUnit.Millimeter), new XUnit(3, XGraphicsUnit.Millimeter)); var dateFont = new XFont("Verdana", 7, XFontStyle.Regular); gfx.DrawString(fileChanged.ToString(), dateFont, XBrushes.Gray, dateRec.TopLeft); gfx.DrawString($"{counter}/{total}", dateFont, XBrushes.Gray, new XRect(0, 0, pageWdith - new XUnit(3, XGraphicsUnit.Millimeter), pageHeight - new XUnit(2.5, XGraphicsUnit.Millimeter)), XStringFormats.BottomRight); // Create a new MigraDoc document var doc = new Document(); doc.Info.Title = "Krisen Karten"; doc.Info.Subject = "Die Krisenkarten des spiels"; doc.Info.Author = "Arbeitstitel Karthago"; doc.DefaultPageSetup.PageWidth = new Unit(pageWdith.Inch, UnitType.Inch); doc.DefaultPageSetup.PageHeight = new Unit(pageHeight.Inch, UnitType.Inch); doc.DefaultPageSetup.LeftMargin = new Unit(13, UnitType.Millimeter); doc.DefaultPageSetup.RightMargin = new Unit(5, UnitType.Millimeter); doc.DefaultPageSetup.BottomMargin = new Unit(10, UnitType.Millimeter); doc.DefaultPageSetup.TopMargin = new Unit(6, UnitType.Millimeter); doc.DefineStyles(); //Cover.DefineCover(document); //DefineTableOfContents(document); DefineContentSection(doc); card.Content.HandleBlocks(doc); // Create a renderer and prepare (=layout) the document MigraDoc.Rendering.DocumentRenderer docRenderer = new DocumentRenderer(doc); docRenderer.PrepareDocument(); //XRect rect = new XRect(new XPoint(Unit.FromCentimeter(1).Value, Unit.FromCentimeter(3).Value), new XSize((pageWdith.Value - Unit.FromCentimeter(2).Value), (pageHeight.Value - Unit.FromCentimeter(4).Value))); // Use BeginContainer / EndContainer for simplicity only. You can naturaly use you own transformations. //XGraphicsContainer container = gfx.BeginContainer(rect, A4Rect, XGraphicsUnit.Point); // Draw page border for better visual representation //gfx.DrawRectangle(XPens.LightGray, A4Rect); // Render the page. Note that page numbers start with 1. docRenderer.RenderPage(gfx, 1); // Note: The outline and the hyperlinks (table of content) does not work in the produced PDF document. // Pop the previous graphical state //gfx.EndContainer(container); } Console.WriteLine(" Finished card."); } CrateBack(pageWdith, pageHeight, document, currentCardType); //DefineParagraphs(document); //DefineTables(document); //DefineCharts(document); return(document, resultList.ToArray()); }
public static void createPdfDocument(ArrayList pdfReportDataTablesList) { int tableStartX = Settings.TTREP_MTS_X; int tableStartY = Settings.TTREP_MTS_Y; int rowHeight = Settings.TTREP_MTRH; int columnWidth = Settings.TTREP_MTCW; int headerTableRowHeight = Settings.TTREP_HTRH; int termsTableColumnWidth = Settings.TTREP_TPTCW; string fileName = "OCTTReportTimetable" + ".pdf"; PDFDOCUMENT = new PdfDocument(); PDFDOCUMENT.Info.Title = "OCTT Timetable Report"; PDFDOCUMENT.Info.Author = "Open Course Timetabler"; PDFDOCUMENT.Info.Subject = "Generated by Open Course Timetabler"; foreach (Object[] reportGroupAndTable in pdfReportDataTablesList) { PdfPage newPage = PDFDOCUMENT.AddPage(); //newPage.Size = PageSize.A4; Type ps = typeof(PageSize); newPage.Size = (PageSize)getValueForEnumeration(ps, Settings.TTREP_PAPER_SIZE); //Console.WriteLine(newPage.Width + "," + newPage.Height); //newPage.Orientation = PdfSharp.PageOrientation.Landscape; Type po = typeof(PageOrientation); newPage.Orientation = (PageOrientation)getValueForEnumeration(po, Settings.TTREP_PAPER_ORIENTATION); XGraphics gfx = XGraphics.FromPdfPage(newPage); XPen pen = new XPen(XColors.Black, 0.3); int rowCount = AppForm.CURR_OCTT_DOC.IncludedTerms.Count; int columnCount = AppForm.CURR_OCTT_DOC.getNumberOfDays(); string groupTitle = (string)reportGroupAndTable[0]; XRect rect = new XRect(tableStartX + termsTableColumnWidth, tableStartY - 25, columnCount * columnWidth, 20); XPdfFontOptions options = new XPdfFontOptions(PdfFontEncoding.Unicode, PdfFontEmbedding.Always); // /*char[] separator = new char[1]; * separator[0] = ','; * string[] ss = Settings.TTREP_FONT_PAGE_TITLE.Split(separator, 3); * string fontFamily = ss[0]; * string fontStyle = ss[1]; * int fontSize = System.Convert.ToInt32(ss[2]); * // * Type fs = typeof(XFontStyle); * XFontStyle xfs=(XFontStyle)getValueForEnumeration(fs, fontStyle); * * XFont font = new XFont(fontFamily, fontSize, xfs, options);*/ //XFont font = new XFont("Times", 16, XFontStyle.Bold, options); XFont font = getMyFont(Settings.TTREP_FONT_PAGE_TITLE, options); XBrush brush = XBrushes.Black; XStringFormat format = new XStringFormat(); //gfx.DrawRectangle(XPens.Black, XBrushes.Bisque, rect); format.LineAlignment = XLineAlignment.Center; format.Alignment = XStringAlignment.Center; gfx.DrawString(groupTitle, font, brush, rect, format); DataTable groupTable = (DataTable)reportGroupAndTable[1]; drawHeaderTable(newPage, gfx, pen, tableStartX + termsTableColumnWidth, tableStartY, columnWidth, headerTableRowHeight); drawTermsTable(newPage, gfx, pen, tableStartX, tableStartY + headerTableRowHeight, termsTableColumnWidth, rowHeight); drawMainTable(newPage, gfx, pen, tableStartX + termsTableColumnWidth, tableStartY + headerTableRowHeight, columnWidth, rowHeight, groupTable); string docPropertiesString = AppForm.CURR_OCTT_DOC.EduInstitutionName + " " + AppForm.CURR_OCTT_DOC.SchoolYear; string lastChangeString; if (AppForm.CURR_OCTT_DOC.FullPath != null) { FileInfo fi = new FileInfo(AppForm.CURR_OCTT_DOC.FullPath); lastChangeString = RES_MANAGER.GetString("lastchangedate.text") + " " + fi.LastWriteTime.ToShortDateString() + " " + fi.LastWriteTime.ToLongTimeString(); } else { lastChangeString = ""; } rect = new XRect(tableStartX, tableStartY + headerTableRowHeight + rowHeight * rowCount + 5, 250, 10); //font = new XFont("Times", 8, XFontStyle.Regular, options); font = getMyFont(Settings.TTREP_FONT_FOOTER, options); //gfx.DrawRectangle(XPens.Black, XBrushes.Bisque, rect); format.LineAlignment = XLineAlignment.Center; format.Alignment = XStringAlignment.Near; gfx.DrawString(docPropertiesString, font, brush, rect, format); rect = new XRect(tableStartX + termsTableColumnWidth + columnWidth * columnCount - 200, tableStartY + headerTableRowHeight + rowHeight * rowCount + 5, 200, 10); //font = new XFont("Times", 8, XFontStyle.Regular, options); //gfx.DrawRectangle(XPens.Black, XBrushes.Bisque, rect); format.LineAlignment = XLineAlignment.Center; format.Alignment = XStringAlignment.Far; gfx.DrawString(lastChangeString, font, brush, rect, format); rect = new XRect(tableStartX, tableStartY + headerTableRowHeight + rowHeight * rowCount + 5, tableStartX + termsTableColumnWidth + columnWidth * columnCount, 10); //font = new XFont("Times", 8, XFontStyle.Regular, options); //gfx.DrawRectangle(XPens.Black, XBrushes.Bisque, rect); format.LineAlignment = XLineAlignment.Center; format.Alignment = XStringAlignment.Center; gfx.DrawString("Generated by Open Course Timetabler (www.openctt.org)", font, brush, rect, format); } try { PDFDOCUMENT.Save(fileName); Process.Start(Settings.PDF_READER_APPLICATION, fileName); } catch (Exception e) { try { Process.Start(fileName); } catch (Exception e2) { MessageBox.Show(e2.Message); } } }
public LineFormatRenderer(LineFormat lineFormat, XGraphics gfx) { _lineFormat = lineFormat; _gfx = gfx; }
/// <summary> /// Initializes a new instance of the XForm class such that it can be drawn on the specified graphics /// object. /// </summary> /// <param name="gfx">The graphics object that later is used to draw this form.</param> /// <param name="width">The width of the form.</param> /// <param name="height">The height of the form.</param> public XForm(XGraphics gfx, XUnit width, XUnit height) : this(gfx, new XSize(width, height)) { }
/// <summary> /// Generate a new PDF report /// </summary> /// <returns>Filepath to new PDF</returns> public string Generate(string savePath) { if (savePath != null) { using (var document = new PdfDocument()) { //======================================================================================================================================// //Add page: Front page var firstPage = document.AddPage(); firstPage.Size = PageSize; var firstPage_gfx = XGraphics.FromPdfPage(firstPage); GenerateFirstPage(firstPage_gfx); GenerateFooter(firstPage_gfx, PageOrientation.Portrait); //======================================================================================================================================// //Add page: Freetext if (reportTab.rpData.tb_FreeText_Text != "" && reportTab.rpData.tb_FreeText_Text != null) { var freeTextPage = document.AddPage(); freeTextPage.Size = PageSize; var freeTextPage_gfx = XGraphics.FromPdfPage(freeTextPage); GenerateFreeTextPage(freeTextPage_gfx); GenerateFooter(freeTextPage_gfx, PageOrientation.Portrait); } //======================================================================================================================================// //Add page: Summary if (reportTab.rpData.chk_Summary_Checked) { var summaryPage = document.AddPage(); summaryPage.Size = PageSize; var summaryPage_gfx = XGraphics.FromPdfPage(summaryPage); GenerateSummaryPage(summaryPage_gfx, 0); GenerateFooter(summaryPage_gfx, PageOrientation.Portrait); PdfPage summaryPage2 = new PdfPage(); PdfPage summaryPage3 = new PdfPage(); if (parent.mySummary.Count > maxSummaryEntrysPerPage) { GenerateContinuesLabel(summaryPage_gfx); summaryPage2 = document.AddPage(); summaryPage2.Size = PageSize; var summaryPage2_gfx = XGraphics.FromPdfPage(summaryPage2); GenerateSummaryPage(summaryPage2_gfx, maxSummaryEntrysPerPage); GenerateFooter(summaryPage2_gfx, PageOrientation.Portrait); if (parent.mySummary.Count > maxSummaryEntrysPerPage * 2) { GenerateContinuesLabel(summaryPage2_gfx); summaryPage3 = document.AddPage(); summaryPage3.Size = PageSize; var summaryPage3_gfx = XGraphics.FromPdfPage(summaryPage3); GenerateSummaryPage(summaryPage3_gfx, maxSummaryEntrysPerPage * 2); GenerateFooter(summaryPage3_gfx, PageOrientation.Portrait); } } } //======================================================================================================================================// //Add page: Row chart if (rowChart != null && reportTab.rpData.chk_RowChart_Checked) { var rowChartPage = document.AddPage(); rowChartPage.Size = PageSize; rowChartPage.Orientation = PageOrientation.Landscape; var rowChartPage_gfx = XGraphics.FromPdfPage(rowChartPage); GenerateChartPage(rowChartPage_gfx, rowChart); GenerateFooter(rowChartPage_gfx, PageOrientation.Landscape); } //======================================================================================================================================// //Add page: Pie chart if (pieChart != null && reportTab.rpData.chk_PieChart_Checked) { var pieChartPage = document.AddPage(); pieChartPage.Size = PageSize; pieChartPage.Orientation = PageOrientation.Landscape; var pieChartPage_gfx = XGraphics.FromPdfPage(pieChartPage); GenerateChartPage(pieChartPage_gfx, pieChart); GenerateFooter(pieChartPage_gfx, PageOrientation.Landscape); } //======================================================================================================================================// //Add page: Attachments if (attachments != null) { foreach (AttachmentImages i in attachments) { var attachtmentPage = document.AddPage(); attachtmentPage.Size = PageSize; if (i.orientation) { attachtmentPage.Orientation = PageOrientation.Portrait; } else { attachtmentPage.Orientation = PageOrientation.Landscape; } var attachtmentPage_gfx = XGraphics.FromPdfPage(attachtmentPage); GenerateAttachmentPage(attachtmentPage_gfx, i.img, attachments.IndexOf(i)); if (i.orientation) { GenerateFooter(attachtmentPage_gfx, PageOrientation.Portrait); } else { GenerateFooter(attachtmentPage_gfx, PageOrientation.Landscape); } } } try { document.Save(savePath); } catch (IOException) { MessageBox.Show("File is being used by another process. Close it and try again."); } return(savePath); } } return(null); }
private void DoWork() { try { if (action == PdfAction.Split) { using (var stream = new MemoryStream(pdfs[1])) { outputDocument = PdfReader.Open(stream, PdfDocumentOpenMode.Import); modifyOutputDocument = PdfReader.Open(stream, PdfDocumentOpenMode.Modify); } } else { var pagecount = 0; for (int i = 1; i <= order; i++) { var keyExists = images.ContainsKey(i); if (keyExists) { //Adds Images to the new pdf var image = images.First(x => x.Key == i); var page = outputDocument.AddPage(); pagecount++; BitmapSource source; source = (BitmapSource) new ImageSourceConverter().ConvertFrom(image.Value); using (var ms = new MemoryStream(image.Value)) { var im = System.Drawing.Image.FromStream(ms); using (var pdfImage = XImage.FromGdiPlusImage(im)) { using (var gfx = XGraphics.FromPdfPage(page)) { var height = heightForImage[i]; if (height > 0) { gfx.DrawImage(pdfImage, 25, 25, page.Width - 50, height); } else { gfx.DrawImage(pdfImage, 25, 25, page.Width - 50, page.Height - 50); } if (showPageNumbers) { var box = page.MediaBox.ToXRect(); box.Inflate(0, -10); var font = new XFont("Verdana", 10, XFontStyle.Bold); var format = new XStringFormat(); format.Alignment = XStringAlignment.Center; format.LineAlignment = XLineAlignment.Far; gfx.DrawString("Page " + pagecount, font, XBrushes.Black, box, format); } } } } } keyExists = pdfs.ContainsKey(i); if (keyExists) { //adds pdfs to the new pdf var pdf = pdfs.First(x => x.Key == i); using (var stream = new MemoryStream(pdf.Value)) { var inputDocument = PdfReader.Open(stream, PdfDocumentOpenMode.Import); foreach (PdfPage page in inputDocument.Pages) { pagecount++; if (angle != null) { page.Rotate = Convert.ToInt32(angle.Value); } var newPage = outputDocument.AddPage(page); if (showPageNumbers) { using (var gfx = XGraphics.FromPdfPage(newPage)) { var box = page.MediaBox.ToXRect(); box.Inflate(0, -10); var format = new XStringFormat(); format.Alignment = XStringAlignment.Center; format.LineAlignment = XLineAlignment.Far; var font = new XFont("Verdana", 10, XFontStyle.Bold); gfx.DrawString("Page " + pagecount, font, XBrushes.Black, box, format); } } } inputDocument.Dispose(); } } } } } catch (Exception ex) { throw ex; } }
/// <summary> /// This method will print the Article detail table with appropriate /// column header according to the template /// </summary> /// <param name="colwidth">different column width</param> /// <param name="form">Supplied XForm</param> /// <param name="dtArticle">supplied datatable containing article information</param> private void PrintArticleDetail(double[] colwidth, ref XForm form, DataTable dtArticle) { XGraphics graphics = XGraphics.FromForm(form); XTextFormatter tf = new XTextFormatter(graphics); XTextFormatter tf1 = new XTextFormatter(graphics); XRect rec; int pagecounter = 0; double left = 0, top = 0; // Print header for (int index = 0; index < colwidth.Length; index++) { rec = new XRect(left, top, colwidth[index], 19); /*if (index % 2 == 0) * { * graphics.DrawRectangle(new XSolidBrush(XColor.FromArgb(120, 204, 204, 204)), rec); * } * else * {*/ graphics.DrawRectangle(XBrushes.Gray, rec); //} string header = dtArticle.Columns[index].ColumnName; int count = header.Length; if (dtArticle.Columns[index].DataType.FullName.Equals("System.String")) { tf.Alignment = XParagraphAlignment.Left; tf.DrawString(header.PadLeft(count + 3), report._smallFontBold, XBrushes.White, rec); } else { tf.Alignment = XParagraphAlignment.Center; tf.DrawString(header.PadRight(count + 3), report._smallFontBold, XBrushes.White, rec); } left += colwidth[index]; } //print Articles foreach (DataRow row in dtArticle.Rows) { pagecounter++; top += 20; left = 0; if (pagecounter % 15 == 0) { //top = -500; //report.document.AddPage(); report.gfx.DrawImage(form, 28, 350); top = 0; PdfPage page = new PdfPage(); page = report.document.Pages.Add(); report.gfx = XGraphics.FromPdfPage(page); form = new XForm(report.document, XUnit.FromMillimeter(1000), XUnit.FromMillimeter(400)); graphics = XGraphics.FromForm(form); tf = new XTextFormatter(graphics); tf1 = new XTextFormatter(graphics); //Print Invoice XForm form1 = new XForm(report.document, XUnit.FromMillimeter(1000), XUnit.FromMillimeter(400)); XGraphics graphics1 = XGraphics.FromForm(form1); double xInit = 0, yInit = 0; graphics1.DrawString(CulturalValues[0], report._largeFontBold, XBrushes.Black, xInit, yInit, XStringFormat.TopLeft); report.gfx.DrawImage(form1, 450, 40); // Print Customer Address form1 = new XForm(report.document, XUnit.FromMillimeter(1000), XUnit.FromMillimeter(400)); graphics1 = XGraphics.FromForm(form1); xInit = 95; yInit = 20; //graphics.DrawRectangle(report._borderPen, 0, 0, 300, 100); graphics1.DrawString(dthead1.Rows[0]["companyname"].ToString().Trim(), report._normalFont, XBrushes.Black, xInit, yInit - report._lineGap, XStringFormat.TopLeft); graphics1.DrawString(dthead1.Rows[0]["customer"].ToString().Trim(), report._normalFont, XBrushes.Black, xInit, yInit, XStringFormat.TopLeft); graphics1.DrawString(dthead1.Rows[0]["address"].ToString() + " " + dthead1.Rows[0]["housenr"].ToString(), report._normalFont, XBrushes.Black, xInit, yInit + report._lineGap, XStringFormat.TopLeft); graphics1.DrawString(dthead1.Rows[0]["postcode"].ToString() + " " + dthead1.Rows[0]["residence"].ToString(), report._normalFont, XBrushes.Black, xInit, yInit + report._lineGap * 2, XStringFormat.TopLeft); graphics1.DrawString(dthead1.Rows[0]["country"].ToString(), report._normalFont, XBrushes.Black, xInit, yInit + report._lineGap * 3, XStringFormat.TopLeft); report.gfx.DrawImage(form1, 245, 130); // Print Our VAT No + Bankaccount details form1 = new XForm(report.document, XUnit.FromMillimeter(1000), XUnit.FromMillimeter(400)); graphics1 = XGraphics.FromForm(form1); xInit = 5; yInit = 5; graphics1.DrawRectangle(XBrushes.Gray, 0, 0, 300, 20); graphics1.DrawString(CulturalValues[1], report._smallFont, XBrushes.White, xInit, yInit, XStringFormat.TopLeft); graphics1.DrawString(CulturalValues[2], report._smallFont, XBrushes.White, xInit + 120, yInit, XStringFormat.TopLeft); graphics1.DrawRectangle(new XSolidBrush(XColor.FromArgb(120, 204, 204, 204)), 0, 20, xInit + 115, 60); graphics1.DrawString("NL006012152B01", report._smallFontBold, XBrushes.Black, 5, yInit + 25, XStringFormat.TopLeft); graphics1.DrawRectangle(new XSolidBrush(XColor.FromArgb(80, 204, 204, 204)), xInit + 115, 20, 180, 60); graphics1.DrawString("ABNAMRO:", report._smallFont, XBrushes.Black, xInit + 120, yInit + 25, XStringFormat.TopLeft); graphics1.DrawString("61 26 26 032", report._smallFontBold, XBrushes.Black, xInit + 200, yInit + 25, XStringFormat.TopLeft); graphics1.DrawString("IBAN:", report._smallFont, XBrushes.Black, xInit + 120, yInit + 25 + report._lineGap, XStringFormat.TopLeft); graphics1.DrawString("NL08ABNA0612626032", report._smallFontBold, XBrushes.Black, xInit + 200, yInit + 25 + report._lineGap, XStringFormat.TopLeft); graphics1.DrawString("BIC:", report._smallFont, XBrushes.Black, xInit + 120, yInit + 25 + report._lineGap * 2, XStringFormat.TopLeft); graphics1.DrawString("ABNANL2A", report._smallFontBold, XBrushes.Black, xInit + 200, yInit + 25 + report._lineGap * 2, XStringFormat.TopLeft); report.gfx.DrawImage(form1, 28, 260); //print For payment please quote form1 = new XForm(report.document, XUnit.FromMillimeter(1000), XUnit.FromMillimeter(400)); graphics1 = XGraphics.FromForm(form1); xInit = 5; yInit = 5; graphics1.DrawRectangle(XBrushes.Gray, 0, 0, 230, 20); graphics1.DrawString(CulturalValues[3], report._smallFont, XBrushes.White, xInit, yInit, XStringFormat.TopLeft); graphics1.DrawRectangle(new XSolidBrush(XColor.FromArgb(120, 204, 204, 204)), 0, 20, 230, 60); graphics1.DrawString(CulturalValues[4], report._smallFont, XBrushes.Black, 5, yInit + 25, XStringFormat.TopLeft); graphics1.DrawString(dthead1.Rows[0]["customerid"].ToString().Trim(), report._smallFontBold, XBrushes.Black, xInit + 100, yInit + 25, XStringFormat.TopLeft); graphics1.DrawString(CulturalValues[5], report._smallFont, XBrushes.Black, 5, yInit + 25 + report._lineGap, XStringFormat.TopLeft); graphics1.DrawString(iid, report._smallFontBold, XBrushes.Black, xInit + 100, yInit + 25 + report._lineGap, XStringFormat.TopLeft); graphics1.DrawString(CulturalValues[6], report._smallFont, XBrushes.Black, 5, yInit + 25 + report._lineGap * 2, XStringFormat.TopLeft); string s = dthead1.Rows[0]["invoicedate"].ToString(); graphics1.DrawString(s, report._smallFontBold, XBrushes.Black, xInit + 100, yInit + 25 + report._lineGap * 2, XStringFormat.TopLeft); graphics1.DrawRectangle(report._borderPen, 0, 0, 230, 80); report.gfx.DrawImage(form1, 333, 260); form1 = new XForm(report.document, XUnit.FromMillimeter(1000), XUnit.FromMillimeter(400)); graphics1 = XGraphics.FromForm(form1); string Show_page = "Page " + pagenumber + " of " + totalpage + " (" + iid + ")."; pagenumber += 1; //graphics.DrawString(Show_page, report._smallFont, XBrushes.Black, 5, yInit + 25 + report._lineGap * 4, XStringFormat.TopLeft); graphics1.DrawString(Show_page, report._smallFont, XBrushes.Black, 5, yInit + 90, XStringFormat.TopLeft); report.gfx.DrawImage(form1, 28, 710); for (int index = 0; index < colwidth.Length; index++) { rec = new XRect(left, top, colwidth[index], 19); /*if (index % 2 == 0) * { * graphics.DrawRectangle(new XSolidBrush(XColor.FromArgb(120, 204, 204, 204)), rec); * } * else * {*/ graphics.DrawRectangle(XBrushes.Gray, rec); //} string header = dtArticle.Columns[index].ColumnName; int count = header.Length; if (dtArticle.Columns[index].DataType.FullName.Equals("System.String")) { tf.Alignment = XParagraphAlignment.Left; tf.DrawString(header.PadLeft(count + 3), report._smallFontBold, XBrushes.White, rec); } else { tf.Alignment = XParagraphAlignment.Center; tf.DrawString(header.PadRight(count + 3), report._smallFontBold, XBrushes.White, rec); } left += colwidth[index]; } left = 0; top += 20; //rec; //report.document.AddPage(page); //report.gfx = XGraphics.FromPdfPage(page, XGraphicsPdfPageOptions.Append); } for (int index = 0; index < colwidth.Length; index++) { //tf.Alignment = (dtArticle.Columns[index].DataType.FullName.Equals("System.String")) ? XParagraphAlignment.Left : XParagraphAlignment.Right; rec = new XRect(left, top, colwidth[index], 20); XRect rec1 = new XRect(left + 5, top, colwidth[index], 20); if (index % 2 == 0) { graphics.DrawRectangle(new XSolidBrush(XColor.FromArgb(120, 204, 204, 204)), rec); } else { graphics.DrawRectangle(new XSolidBrush(XColor.FromArgb(60, 204, 204, 204)), rec); } int count = row[index].ToString().Length; if (dtArticle.Columns[index].DataType.FullName.Equals("System.String")) { tf.Alignment = XParagraphAlignment.Left; //tf1.Alignment = XParagraphAlignment.Right; if (dtArticle.Columns[index].ToString().Equals(CulturalValues[19])) { tf.DrawString(row[index].ToString().PadLeft(count + 3), report._smallFont, XBrushes.Black, rec); } if (dtArticle.Columns[index].ToString().Equals(CulturalValues[20])) { if (row[index].ToString().Trim().Equals("Shipping and handling")) { if (CulturalValues[27] == "nl-NL") { tf.DrawString("Verzendkosten".ToString(), report._smallFont, XBrushes.Black, rec1); } else { tf.DrawString("Shipping and handling".ToString(), report._smallFont, XBrushes.Black, rec1); } } else { tf.DrawString(row[index].ToString() + " - " + row["Composer"].ToString(), report._smallFont, XBrushes.Black, rec1); } } } else { tf.Alignment = XParagraphAlignment.Right; tf.DrawString(row[index].ToString().PadRight(count + 3), report._smallFont, XBrushes.Black, rec); if (dtArticle.Columns[index].ToString().Equals(CulturalValues[22]) || dtArticle.Columns[index].ToString().Equals(CulturalValues[24])) { tf.DrawString("€".PadRight(22), report._smallFont, XBrushes.Black, rec); } } //tf.DrawString(row[index].ToString(), report._smallFont, XBrushes.Black, rec); left += colwidth[index]; } } }
//Método Criado para o PDF public FileResult GerarRelatorio() { using (var doc = new PdfSharpCore.Pdf.PdfDocument()) { var page = doc.AddPage(); page.Size = PdfSharpCore.PageSize.A4; page.Orientation = PdfSharpCore.PageOrientation.Portrait; var graphics = PdfSharpCore.Drawing.XGraphics.FromPdfPage(page); var corFonte = PdfSharpCore.Drawing.XBrushes.Black; var textFormatter = new PdfSharpCore.Drawing.Layout.XTextFormatter(graphics); var fonteOrganzacao = new PdfSharpCore.Drawing.XFont("Arial", 10); var fonteDescricao = new PdfSharpCore.Drawing.XFont("Arial", 8, PdfSharpCore.Drawing.XFontStyle.BoldItalic); var titulodetalhes = new PdfSharpCore.Drawing.XFont("Arial", 14, PdfSharpCore.Drawing.XFontStyle.Bold); var fonteDetalhesDescricao = new PdfSharpCore.Drawing.XFont("Arial", 7); var webRoot = _environment.WebRootPath; var logo = string.Concat(webRoot, "/imagens/logo.jpg"); var qtdPaginas = doc.PageCount; textFormatter.DrawString(qtdPaginas.ToString(), new PdfSharpCore.Drawing.XFont("Arial", 10), corFonte, new PdfSharpCore.Drawing.XRect(578, 825, page.Width, page.Height)); // Impressão do LogoTipo XImage imagem = XImage.FromFile(logo); graphics.DrawImage(imagem, 20, 5, 300, 50); // Titulo Exibição textFormatter.DrawString("Nome :", fonteDescricao, corFonte, new PdfSharpCore.Drawing.XRect(20, 75, page.Width, page.Height)); textFormatter.DrawString("Valdir Ferreira ", fonteOrganzacao, corFonte, new PdfSharpCore.Drawing.XRect(80, 75, page.Width, page.Height)); textFormatter.DrawString("Profissão :", fonteDescricao, corFonte, new PdfSharpCore.Drawing.XRect(20, 95, page.Width, page.Height)); textFormatter.DrawString("Programador", fonteOrganzacao, corFonte, new PdfSharpCore.Drawing.XRect(80, 95, page.Width, page.Height)); textFormatter.DrawString("Tempo :", fonteDescricao, corFonte, new PdfSharpCore.Drawing.XRect(20, 115, page.Width, page.Height)); textFormatter.DrawString("10 anos", fonteOrganzacao, corFonte, new PdfSharpCore.Drawing.XRect(80, 115, page.Width, page.Height)); // Titulo maior var tituloDetalhes = new PdfSharpCore.Drawing.Layout.XTextFormatter(graphics); tituloDetalhes.Alignment = PdfSharpCore.Drawing.Layout.XParagraphAlignment.Center; tituloDetalhes.DrawString("Detalhes ", titulodetalhes, corFonte, new PdfSharpCore.Drawing.XRect(0, 120, page.Width, page.Height)); // titulo das colunas var alturaTituloDetalhesY = 140; var detalhes = new PdfSharpCore.Drawing.Layout.XTextFormatter(graphics); detalhes.DrawString("Descrição", fonteDescricao, corFonte, new PdfSharpCore.Drawing.XRect(20, alturaTituloDetalhesY, page.Width, page.Height)); detalhes.DrawString("Atendimento", fonteDescricao, corFonte, new PdfSharpCore.Drawing.XRect(144, alturaTituloDetalhesY, page.Width, page.Height)); detalhes.DrawString("Operação", fonteDescricao, corFonte, new PdfSharpCore.Drawing.XRect(220, alturaTituloDetalhesY, page.Width, page.Height)); detalhes.DrawString("Quantidade", fonteDescricao, corFonte, new PdfSharpCore.Drawing.XRect(290, alturaTituloDetalhesY, page.Width, page.Height)); detalhes.DrawString("Status", fonteDescricao, corFonte, new PdfSharpCore.Drawing.XRect(337, alturaTituloDetalhesY, page.Width, page.Height)); detalhes.DrawString("Data", fonteDescricao, corFonte, new PdfSharpCore.Drawing.XRect(400, alturaTituloDetalhesY, page.Width, page.Height)); //dados do relatório var alturaDetalhesItens = 160; for (int i = 1; i < 30; i++) { textFormatter.DrawString("Descrição" + " : " + i.ToString(), fonteDetalhesDescricao, corFonte, new PdfSharpCore.Drawing.XRect(21, alturaDetalhesItens, page.Width, page.Height)); textFormatter.DrawString("Atendimento" + " : " + i.ToString(), fonteDetalhesDescricao, corFonte, new PdfSharpCore.Drawing.XRect(145, alturaDetalhesItens, page.Width, page.Height)); textFormatter.DrawString("Operação" + " : " + i.ToString(), fonteDetalhesDescricao, corFonte, new PdfSharpCore.Drawing.XRect(215, alturaDetalhesItens, page.Width, page.Height)); textFormatter.DrawString("Quantidade" + " : " + i.ToString(), fonteDetalhesDescricao, corFonte, new PdfSharpCore.Drawing.XRect(290, alturaDetalhesItens, page.Width, page.Height)); textFormatter.DrawString("Status" + " : " + i.ToString(), fonteDetalhesDescricao, corFonte, new PdfSharpCore.Drawing.XRect(332, alturaDetalhesItens, page.Width, page.Height)); textFormatter.DrawString(DateTime.Now.ToString(), fonteDetalhesDescricao, corFonte, new PdfSharpCore.Drawing.XRect(400, alturaDetalhesItens, page.Width, page.Height)); alturaDetalhesItens += 20; } #region //ADICIONAR NOVA PAGINA page = doc.AddPage(); page.Size = PdfSharpCore.PageSize.A4; page.Orientation = PdfSharpCore.PageOrientation.Portrait; graphics = XGraphics.FromPdfPage(page); corFonte = XBrushes.Black; fonteOrganzacao = new PdfSharpCore.Drawing.XFont("Arial", 10); fonteDescricao = new PdfSharpCore.Drawing.XFont("Arial", 8, PdfSharpCore.Drawing.XFontStyle.BoldItalic); titulodetalhes = new PdfSharpCore.Drawing.XFont("Arial", 14, PdfSharpCore.Drawing.XFontStyle.Bold); fonteDetalhesDescricao = new PdfSharpCore.Drawing.XFont("Arial", 7); detalhes = new PdfSharpCore.Drawing.Layout.XTextFormatter(graphics); logo = string.Concat(webRoot, "/imagens/logo.jpg"); qtdPaginas = doc.PageCount; detalhes.DrawString(qtdPaginas.ToString(), new PdfSharpCore.Drawing.XFont("Arial", 10), corFonte, new PdfSharpCore.Drawing.XRect(578, 825, page.Width, page.Height)); // Impressão do LogoTipo imagem = XImage.FromFile(logo); graphics.DrawImage(imagem, 20, 5, 300, 50); var alturaDetalhesItensPageNew = 160; for (int i = 1; i < 30; i++) { detalhes.DrawString("Descrição" + " : " + i.ToString(), fonteDetalhesDescricao, corFonte, new PdfSharpCore.Drawing.XRect(21, alturaDetalhesItensPageNew, page.Width, page.Height)); detalhes.DrawString("Atendimento" + " : " + i.ToString(), fonteDetalhesDescricao, corFonte, new PdfSharpCore.Drawing.XRect(145, alturaDetalhesItensPageNew, page.Width, page.Height)); detalhes.DrawString("Operação" + " : " + i.ToString(), fonteDetalhesDescricao, corFonte, new PdfSharpCore.Drawing.XRect(215, alturaDetalhesItensPageNew, page.Width, page.Height)); detalhes.DrawString("Quantidade" + " : " + i.ToString(), fonteDetalhesDescricao, corFonte, new PdfSharpCore.Drawing.XRect(290, alturaDetalhesItensPageNew, page.Width, page.Height)); detalhes.DrawString("Status" + " : " + i.ToString(), fonteDetalhesDescricao, corFonte, new PdfSharpCore.Drawing.XRect(332, alturaDetalhesItensPageNew, page.Width, page.Height)); detalhes.DrawString(DateTime.Now.ToString(), fonteDetalhesDescricao, corFonte, new PdfSharpCore.Drawing.XRect(400, alturaDetalhesItensPageNew, page.Width, page.Height)); alturaDetalhesItensPageNew += 20; } #endregion using (MemoryStream stream = new MemoryStream()) { var contantType = "application/pdf"; doc.Save(stream, false); var nomeArquivo = "RelPDF.pdf"; //return File(stream.ToArray(), contantType, nomeArquivo); FileContentResult result = new FileContentResult(stream.ToArray(), "application/pdf"); return(result); } } //return View(); }
/// <summary> /// Generar un PDF para un comprobante facturable. /// </summary> public PdfDocument GenerarFactura() { var Res = new PdfDocument(); switch (this.Variante) { case Variantes.RojoYNegro: this.Color1 = XColor.FromArgb(242, 46, 46); this.Color2 = XColor.FromArgb(220, 200, 135); this.Color3 = XColor.FromArgb(220, 200, 135); break; default: case Variantes.AzulYVerde: this.Color1 = XColor.FromArgb(48, 113, 242); this.Color2 = XColor.FromArgb(194, 243, 31); this.Color3 = XColors.Orange; break; } Res.Options.CompressContentStreams = true; Res.Language = "es_AR"; Res.Info.Title = Comprob.ToString(); Res.Info.Author = Lbl.Sys.Config.Empresa.RazonSocial; Res.Info.Creator = "Lázaro Gestión; http://www.lazarogestion.com"; Res.Info.Subject = "Factura electrónica autorizada por AFIP, CAE " + Comprob.CaeNumero; var Pagina = new PdfPage(Res) { Size = PageSize.A4 }; var Gfx = XGraphics.FromPdfPage(Pagina); var FuentePredeterminada = new XFont(FuenteSans, 11); var FuenteResaltada = new XFont(FuenteSans, 11, XFontStyle.Bold); var FuentePequena = new XFont(FuenteSans, 9); var FuenteArticulos = new XFont(FuenteSans, 10); var AreaUsable = new XRect(Margenes.Izquierda, Margenes.Arriba, Pagina.Width - Margenes.Derecha - Margenes.Izquierda, Pagina.Height - Margenes.Arriba - Margenes.Abajo); var Tf = new XTextFormatter(Gfx) { Font = FuentePredeterminada }; var LineaFina = new XPen(this.Color1, .3); var CuadroEncab = new XRect(AreaUsable.Left, AreaUsable.Top, AreaUsable.Width, 30 * mm); //Gfx.DrawRectangle(new XPen(Azul), XBrushes.Transparent, new XRect(-10, AreaUsable.Top, AreaUsable.Right + 10, 30 * mm)); Gfx.DrawRectangle(XPens.Transparent, new XSolidBrush(this.Color3), new XRect(AreaUsable.Left + AreaUsable.Width / 2 - 12 * mm, -10, 24 * mm, AreaUsable.Top + 10 + 16 * mm)); Gfx.DrawString(Comprob.Tipo.LetraONomenclatura, new XFont(FuenteSans, 24, XFontStyle.Bold), XBrushes.Black, new XRect(AreaUsable.Left + AreaUsable.Width / 2 - 12 * mm, AreaUsable.Top + 1 * mm, 24 * mm, 10 * mm), XStringFormats.Center); Gfx.DrawString("Cód. " + Afip.Ws.FacturaElectronica.Tablas.CodigoDeComprobantePorLetra(Comprob.Tipo.Nomenclatura).ToString().PadLeft(2, '0'), FuentePequena, XBrushes.Black, new XRect(AreaUsable.Left + AreaUsable.Width / 2 - 12 * mm, AreaUsable.Top + 10 * mm, 24 * mm, 6 * mm), XStringFormats.Center); var EncabIzquierdo = new XRect(AreaUsable.Left + 2 * mm, AreaUsable.Top + 2 * mm, AreaUsable.Width / 2 - 16 * mm, 26 * mm); var EncabDerecho = new XRect(AreaUsable.Left + AreaUsable.Width / 2 + 14 * mm, AreaUsable.Top + 2 * mm, AreaUsable.Width / 2 - 16 * mm, 26 * mm); Tf.Alignment = XParagraphAlignment.Right; Tf.DrawString(Comprob.PV.ToString().PadLeft(4, '0') + "-" + Comprob.Numero.ToString().PadLeft(8, '0') + "\n" + Comprob.Tipo.Nombre + "\n\n" + Lfx.Types.Formatting.FormatDate(Comprob.Fecha), FuenteResaltada, XBrushes.Black, EncabDerecho); Tf.Alignment = XParagraphAlignment.Left; var TextoEncab = ""; TextoEncab += Lbl.Sys.Config.Empresa.RazonSocial + "\n"; if (Lbl.Sys.Config.Empresa.SituacionTributaria > 0) { var EmpresaSituacion = new Lbl.Impuestos.SituacionTributaria(Comprob.Connection, Lbl.Sys.Config.Empresa.SituacionTributaria); if (EmpresaSituacion.Existe) { TextoEncab += EmpresaSituacion.Nombre + "\n"; } } if (Lbl.Sys.Config.Empresa.SucursalActual != null && string.IsNullOrWhiteSpace(Lbl.Sys.Config.Empresa.SucursalActual.Direccion) == false) { TextoEncab += Lbl.Sys.Config.Empresa.SucursalActual.Direccion + "\n"; } if (Lbl.Sys.Config.Empresa.ClaveTributaria != null) { TextoEncab += Lbl.Sys.Config.Empresa.ClaveTributaria.Nombre + ": " + Lbl.Sys.Config.Empresa.ClaveTributaria.ToString() + "\n"; } if (string.IsNullOrWhiteSpace(Lbl.Sys.Config.Empresa.NumeroIngresosBrutos) == false) { TextoEncab += "II.BB.: " + Lbl.Sys.Config.Empresa.NumeroIngresosBrutos + "\n"; } if (Lbl.Sys.Config.Empresa.InicioDeActividades != null) { TextoEncab += "Inicio act.: " + Lfx.Types.Formatting.FormatDate(Lbl.Sys.Config.Empresa.InicioDeActividades) + "\n"; } Tf.DrawString(TextoEncab, FuentePequena, XBrushes.Black, EncabDerecho); var Logo = new Lbl.Sys.Blob(this.Comprob.Connection, 1); if (Logo.Existe && Logo.Imagen != null) { // Poner el logotipo, centrado en el espacio de logo var XImagenLogo = XImage.FromGdiPlusImage(Logo.Imagen); var RatioX = (double)EncabIzquierdo.Width / XImagenLogo.PointWidth; var RatioY = (double)EncabDerecho.Height / XImagenLogo.PointHeight; var RatioFinal = Math.Min(RatioX, RatioY); var LogoTamanio = new XSize(XImagenLogo.PointWidth * RatioFinal, XImagenLogo.PointHeight * RatioFinal); var LogoRect = new XRect(EncabIzquierdo.Left + (EncabIzquierdo.Width - LogoTamanio.Width) / 2, EncabIzquierdo.Top + (EncabIzquierdo.Height - LogoTamanio.Height) / 2, LogoTamanio.Width, LogoTamanio.Height); Gfx.DrawImage(XImagenLogo, LogoRect); } else { // Poner el nombre de la empresa Tf.Alignment = XParagraphAlignment.Center; Tf.DrawString(Lbl.Sys.Config.Empresa.Nombre, new XFont(FuenteSans, 16, XFontStyle.Bold), new XSolidBrush(this.Color1), EncabIzquierdo); } var CuadroCliente = new XRect(AreaUsable.Left, CuadroEncab.Bottom + 4 * mm, AreaUsable.Width, 14 * mm); //Gfx.DrawLine(LineaFinaGris, CuadroCliente.Left, CuadroCliente.Bottom, CuadroCliente.Right, CuadroCliente.Bottom); Tf.Alignment = XParagraphAlignment.Left; Tf.DrawString("Cliente\nDomicilio\nCUIT", FuentePredeterminada, XBrushes.Black, CuadroCliente); string DatosCliente1 = Comprob.Cliente.ToString() + "\n" + Comprob.Cliente.Domicilio + "\n"; if (Comprob.Cliente.ClaveTributaria != null) { DatosCliente1 += Comprob.Cliente.ClaveTributaria.ToString(); } Tf.DrawString(DatosCliente1, FuenteResaltada, XBrushes.Black, new XRect(CuadroCliente.Left + 20 * mm, CuadroCliente.Top, CuadroCliente.Width, CuadroCliente.Width)); Tf.DrawString("Condición\nSituación\nCiudad", FuentePredeterminada, XBrushes.Black, new XRect(CuadroCliente.Left + 100 * mm, CuadroCliente.Top, CuadroCliente.Width, CuadroCliente.Width)); string DatosCliente2 = Comprob.FormaDePago.ToString() + "\n" + Comprob.Cliente.SituacionTributaria.ToString() + "\n"; if (Comprob.Cliente.Localidad != null) { DatosCliente2 += Comprob.Cliente.Localidad.ToString(); } Tf.DrawString(DatosCliente2, FuenteResaltada, XBrushes.Black, new XRect(CuadroCliente.Left + 120 * mm, CuadroCliente.Top, CuadroCliente.Width, CuadroCliente.Width)); // *** Artículos y detalles var CuadroArticulos = new XRect(AreaUsable.Left, CuadroCliente.Bottom + 4 * mm, AreaUsable.Width, 140 * mm); //Gfx.DrawRectangle(LineaFinaGris, CuadroArticulos); Gfx.DrawLine(LineaFina, CuadroArticulos.Left, CuadroArticulos.Top, CuadroArticulos.Right, CuadroArticulos.Top); var ColAnchos = new int[] { 24, 92, 14, 22, 22 }; var CuadroArticulosCodigos = new XRect(CuadroArticulos.Left, CuadroArticulos.Top, ColAnchos[0] * mm, CuadroArticulos.Height); var CuadroArticulosDetalles = new XRect(CuadroArticulosCodigos.Right, CuadroArticulos.Top, ColAnchos[1] * mm, CuadroArticulos.Height); var CuadroArticulosCantidades = new XRect(CuadroArticulosDetalles.Right, CuadroArticulos.Top, ColAnchos[2] * mm, CuadroArticulos.Height); var CuadroArticulosUnitarios = new XRect(CuadroArticulosCantidades.Right, CuadroArticulos.Top, ColAnchos[3] * mm, CuadroArticulos.Height); var CuadroArticulosSubtotales = new XRect(CuadroArticulosUnitarios.Right, CuadroArticulos.Top, ColAnchos[4] * mm, CuadroArticulos.Height); Gfx.DrawLine(LineaFina, CuadroArticulos.Left, CuadroArticulos.Top + 7 * mm, CuadroArticulos.Right, CuadroArticulos.Top + 7 * mm); CuadroArticulosCodigos.Offset(0, 1 * mm); CuadroArticulosDetalles.Offset(0, 1 * mm); CuadroArticulosCantidades.Offset(0, 1 * mm); CuadroArticulosUnitarios.Offset(0, 1 * mm); CuadroArticulosSubtotales.Offset(0, 1 * mm); Tf.Alignment = XParagraphAlignment.Left; Tf.DrawString("Código", FuenteResaltada, XBrushes.Black, CuadroArticulosCodigos); Tf.DrawString("Detalle", FuenteResaltada, XBrushes.Black, CuadroArticulosDetalles); Tf.Alignment = XParagraphAlignment.Right; Tf.DrawString("Cantidad", FuenteResaltada, XBrushes.Black, CuadroArticulosCantidades); Tf.DrawString("P. unitario", FuenteResaltada, XBrushes.Black, CuadroArticulosUnitarios); Tf.DrawString("Subtotal", FuenteResaltada, XBrushes.Black, CuadroArticulosSubtotales); CuadroArticulosCodigos.Offset(0, 7 * mm); CuadroArticulosDetalles.Offset(0, 7 * mm); CuadroArticulosCantidades.Offset(0, 7 * mm); CuadroArticulosUnitarios.Offset(0, 7 * mm); CuadroArticulosSubtotales.Offset(0, 7 * mm); Tf.Alignment = XParagraphAlignment.Left; // Generar un listado de códigos, detalles, cantidades, etc. string Codigos = "", Detalles = "", Cantidades = "", Unitarios = "", Importes = ""; foreach (var Det in Comprob.Articulos) { string CodigoImprimir, DetalleImprimir; if (Det.Articulo == null) { CodigoImprimir = ""; DetalleImprimir = Det.Nombre; } else { CodigoImprimir = Det.Articulo.Id.ToString(); DetalleImprimir = Det.Articulo.ToString(); } Codigos += CodigoImprimir + "\n"; Detalles += DetalleImprimir + "\n"; Cantidades += Lfx.Types.Formatting.FormatNumberForPrint(Det.Cantidad, Lbl.Sys.Config.Articulos.Decimales) + "\n"; Unitarios += Lfx.Types.Formatting.FormatCurrencyForPrint(Det.ImporteUnitarioFinalAImprimir, Lfx.Workspace.Master.CurrentConfig.Moneda.DecimalesFinal) + "\n"; Importes += Lfx.Types.Formatting.FormatCurrencyForPrint(Det.ImporteAImprimir, Lfx.Workspace.Master.CurrentConfig.Moneda.DecimalesFinal) + "\n"; } Tf.DrawString(Codigos, FuenteArticulos, XBrushes.Black, CuadroArticulosCodigos); Tf.DrawString(Detalles, FuenteArticulos, XBrushes.Black, CuadroArticulosDetalles); Tf.Alignment = XParagraphAlignment.Right; Tf.DrawString(Cantidades, FuenteArticulos, XBrushes.Black, CuadroArticulosCantidades); Tf.DrawString(Unitarios, FuenteArticulos, XBrushes.Black, CuadroArticulosUnitarios); Tf.DrawString(Importes, FuenteArticulos, XBrushes.Black, CuadroArticulosSubtotales); // *** Observaciones var CuadroObs = new XRect(AreaUsable.Left, CuadroArticulos.Bottom + 4 * mm, AreaUsable.Width, 26 * mm); Tf.Alignment = XParagraphAlignment.Left; if (Comprob.Obs != null && Comprob.Obs.Length > 0) { Tf.DrawString(Comprob.Obs, Comprob.Obs.Length > 400 ? FuentePequena : FuentePredeterminada, XBrushes.Black, CuadroObs); } Gfx.DrawLine(LineaFina, CuadroObs.Left, CuadroObs.Bottom, CuadroObs.Right, CuadroObs.Bottom); // *** Subtotal, IVA, descuento y total var CuadroTotales = new XRect(AreaUsable.Left, CuadroObs.Bottom + 4 * mm, 50 * mm, 14 * mm); Tf.Alignment = XParagraphAlignment.Left; Tf.DrawString("Subtotal\nIVA\nDescuento / recargo", FuentePredeterminada, XBrushes.Black, CuadroTotales); Tf.Alignment = XParagraphAlignment.Right; Tf.DrawString(string.Concat( Lfx.Types.Formatting.FormatCurrency(Comprob.SubtotalSinIvaFinal), "\n", Lfx.Types.Formatting.FormatCurrency(Comprob.ImporteIvaDiscriminadoFinal), "\n", Lfx.Types.Formatting.FormatNumber(Comprob.Descuento, 2) + "%" ), FuenteResaltada, XBrushes.Black, CuadroTotales); //Tf.DrawString("\nSon ciento veintitresmil cuatrocientos cincuenta y seis pesos con 00/100.", FuentePequena, XBrushes.Black, CuadroTotales); var CuadroTotal = new XRect(AreaUsable.Right - 50 * mm, CuadroTotales.Top, 50 * mm, CuadroTotales.Height); var CuadroFondoTotal = new XRect(AreaUsable.Right - 45 * mm, CuadroTotales.Top, 90 * mm, CuadroTotales.Height); Gfx.DrawRectangle(new XSolidBrush(this.Color2), CuadroFondoTotal); //Gfx.DrawRectangle(XBrushes.Silver, CuadroTotal); CuadroTotal.Offset(0, 3 * mm); Gfx.DrawString("TOTAL", new XFont(FuenteSans, 8), XBrushes.Black, CuadroFondoTotal.Left + 1 * mm, CuadroFondoTotal.Top + 3 * mm); Tf.Alignment = XParagraphAlignment.Right; Tf.DrawString("$ " + Lfx.Types.Formatting.FormatCurrency(Comprob.Total), new XFont(FuenteSans, 18, XFontStyle.Bold), XBrushes.Black, CuadroTotal); // *** Pie con información de AFIP y código de barras var CuadroPie = new XRect(AreaUsable.Left, AreaUsable.Bottom - 20 * mm, AreaUsable.Width, 20 * mm); Gfx.DrawLine(LineaFina, CuadroPie.Left, CuadroPie.Top, CuadroPie.Right, CuadroPie.Top); CuadroPie.Offset(0, 1 * mm); Tf.Alignment = XParagraphAlignment.Left; Tf.DrawString("Comprobante electrónico\nCAE Nº " + Comprob.CaeNumero + "\nCAE Vence " + Lfx.Types.Formatting.FormatDate(Comprob.CaeVencimiento), FuentePredeterminada, XBrushes.Black, new XRect(CuadroPie.Left + 110 * mm, CuadroPie.Top, CuadroPie.Width, CuadroPie.Height)); string TextoCodigoBarras = this.GenerarTextoCodigoDeBarras(); var CodBarras = new BarcodeLib.Barcode(); var ImagenCodBarras = CodBarras.Encode(BarcodeLib.TYPE.Interleaved2of5, TextoCodigoBarras, 1000, 120); var XImagenCodBarras = XImage.FromGdiPlusImage(ImagenCodBarras); Gfx.DrawImage(XImagenCodBarras, new XRect(CuadroPie.Left, CuadroPie.Bottom - 20 * mm, 100 * mm, 12 * mm)); Tf.Alignment = XParagraphAlignment.Center; Tf.DrawString(TextoCodigoBarras, FuentePredeterminada, XBrushes.Black, new XRect(CuadroPie.Left, CuadroPie.Bottom - 7 * mm, 100 * mm, 7 * mm)); Res.AddPage(Pagina); return(Res); }
public double GetHeight(XGraphics graphics) => #if true throw new InvalidOperationException("Honestly: Use GetHeight() without parameter!");
private void HandleTextElement(IXmlNamespaceResolver resolver, XElement context, XGraphics gfx, TextElement textElement) { var maxScale = textElement.MaxEmSizeScale.GetValue(context, resolver); var minScale = textElement.MinEmSizeScale.GetValue(context, resolver); const double MIN_CHANGE = 0.01; double emScale = 1; double? lastScale = null; var frame = textElement.Position.GetValue(context, resolver); var lastValidParagraphs = this.SimulatePrint(resolver, context, gfx, textElement, emScale); bool isLastValidToBig = true; if (!lastValidParagraphs.SelectMany(x => x.lines).Any()) { return; // if thre is nothing to print we are finished. } XRect CalculateDimensions(List <(XLineAlignment horizontalAlignment, List <List <(string textToPrint, XFont font, XBrush brush, XPoint printPosition, XLineAlignment alignment, XSize size)> > lines)> input) { var left = input.SelectMany(x => x.lines).SelectMany(x => x).Min(x => x.printPosition.X); var right = input.SelectMany(x => x.lines).SelectMany(x => x).Max(x => x.printPosition.X + x.size.Width); var top = input.SelectMany(x => x.lines).SelectMany(x => x).Min(x => x.printPosition.Y); var bottom = input.SelectMany(x => x.lines).SelectMany(x => x).Max(x => x.printPosition.Y + x.size.Height); return(new XRect(left, top, right - left, bottom - top)); } do { var p = this.SimulatePrint(resolver, context, gfx, textElement, emScale); var dimensions = CalculateDimensions(p); double scaleChange; if (dimensions.Bottom > frame.Bottom && emScale > minScale) { if (isLastValidToBig) { lastValidParagraphs = p; } if ((lastScale ?? double.MaxValue) > emScale) { scaleChange = (minScale - emScale) / 2; } else { scaleChange = (emScale - lastScale.Value) / 2; } } else if (dimensions.Bottom < frame.Bottom && emScale < maxScale) { isLastValidToBig = false; lastValidParagraphs = p; if ((lastScale ?? double.MinValue) < emScale) { scaleChange = (maxScale - emScale) / 2; } else { scaleChange = (emScale - lastScale.Value) / 2; } } else { break; } if (Math.Abs(scaleChange) < MIN_CHANGE) { break; } lastScale = emScale; emScale += scaleChange; } while (true); var paragraphs = lastValidParagraphs; var maximumWidth = textElement.Position.GetValue(context, resolver).Width; var maximumHeight = textElement.Position.GetValue(context, resolver).Height; var printRect = CalculateDimensions(paragraphs); double verticalOffset; var verticalAlignment = textElement.VerticalAlignment.GetValue(context, resolver); switch (verticalAlignment) { case XLineAlignment.Near: verticalOffset = 0; break; case XLineAlignment.Center: verticalOffset = (maximumHeight - printRect.Height) / 2; break; case XLineAlignment.Far: verticalOffset = maximumHeight - printRect.Height; break; case XLineAlignment.BaseLine: throw new NotSupportedException("Not sure what this means"); default: throw new NotSupportedException($"The Alignment {verticalAlignment} is not supported."); } foreach (var(horizontalAlignment, lines) in paragraphs) { // now we calculate LineAlignment and print foreach (var line in lines.Where(x => x.Count > 0)) { var leftmost = line.Min(x => x.printPosition.X); var rightmost = line.Max(x => x.printPosition.X + x.size.Width); var width = rightmost - leftmost; double horizontalOffset; switch (horizontalAlignment) { case XLineAlignment.Near: horizontalOffset = 0; break; case XLineAlignment.Center: horizontalOffset = (maximumWidth - width) / 2; break; case XLineAlignment.Far: horizontalOffset = maximumWidth - width; break; case XLineAlignment.BaseLine: throw new NotSupportedException("Not sure what this means"); default: throw new NotSupportedException($"The Alignment {horizontalAlignment} is not supported."); } foreach (var print in line) { gfx.DrawString(print.textToPrint, print.font, print.brush, new XPoint(print.printPosition.X + horizontalOffset, print.printPosition.Y + verticalOffset), XStringFormats.TopLeft); } } } }
internal ImageRenderer(XGraphics gfx, RenderInfo renderInfo, FieldInfos fieldInfos) : base(gfx, renderInfo, fieldInfos) { _image = (Image)renderInfo.DocumentObject; }
private bool ExpandRuns(IChild <Run> child, Paragraph paragraph, XGraphics gfx, XRect frame, XPoint startPosition, ref XPoint currentPosition, List <List <(string textToPrint, XFont font, XBrush brush, XPoint printPosition, XLineAlignment alignment, XSize size)> > lines, List <(string textToPrint, XFont font, XBrush brush, XPoint printPosition, XLineAlignment alignment, XSize size)> currentLine, IXmlNamespaceResolver resolver, XElement context, double emScale)
/// <summary> /// Renders the bar code. /// </summary> protected internal override void Render(XGraphics gfx, XBrush brush, XFont font, XPoint position) { XGraphicsState state = gfx.Save(); BarCodeRenderInfo info = new BarCodeRenderInfo(gfx, brush, font, position); InitRendering(info); info.CurrPosInString = 0; //info.CurrPos = info.Center - this.size / 2; info.CurrPos = position - CodeBase.CalcDistance(AnchorType.TopLeft, this.anchor, this.size); if (TurboBit) RenderTurboBit(info, true); RenderStart(info); while (info.CurrPosInString < this.text.Length) { RenderNextChar(info); RenderGap(info, false); } RenderStop(info); if (TurboBit) RenderTurboBit(info, false); if (TextLocation != TextLocation.None) RenderText(info); gfx.Restore(state); }
public abstract void SetDocumentBody(PdfPage page, XGraphics gfx);
public XGraphicsPathItem(XGraphicsPathItemType type, params PointF[] points) { Type = type; Points = XGraphics.MakeXPointArray(points, 0, points.Length); }
/// <summary> /// When defined in a derived class renders the code. /// </summary> protected internal abstract void Render(XGraphics gfx, XBrush brush, XFont font, XPoint position);
public static void CreatePdfPage(Sheet sheet, PdfPage page) { page.Width = p(sheet.Width); //XUnit.FromInch((double)sheet.Width/100); //new XUnit((double)sheet.Width/100,XGraphicsUnit.Inch); page.Height = p(sheet.Height); //new XUnit((double)sheet.Height/100,XGraphicsUnit.Inch); if (sheet.IsLandscape) { page.Orientation = PageOrientation.Landscape; } XGraphics g = XGraphics.FromPdfPage(page); g.SmoothingMode = XSmoothingMode.HighQuality; //g.PageUnit=XGraphicsUnit. //wish they had pixel //XTextFormatter tf = new XTextFormatter(g);//needed for text wrap //tf.Alignment=XParagraphAlignment.Left; //pd.DefaultPageSettings.Landscape= //already done?:SheetUtil.CalculateHeights(sheet,g);//this is here because of easy access to g. XFont xfont; XFontStyle xfontstyle; //first, draw images-------------------------------------------------------------------------------------- foreach (SheetField field in sheet.SheetFields) { if (field.FieldType != SheetFieldType.Image) { continue; } string filePathAndName = ODFileUtils.CombinePaths(SheetUtil.GetImagePath(), field.FieldName); Bitmap bitmapOriginal = null; if (field.FieldName == "Patient Info.gif") { bitmapOriginal = Properties.Resources.Patient_Info; } else if (File.Exists(filePathAndName)) { bitmapOriginal = new Bitmap(filePathAndName); } else { continue; } Bitmap bitmapResampled = (Bitmap)bitmapOriginal.Clone(); if (bitmapOriginal.HorizontalResolution != 96 || bitmapOriginal.VerticalResolution != 96) //to avoid slowdown for other pdfs //The scaling on the XGraphics.DrawImage() function causes unreadable output unless the image is in 96 DPI native format. //We use GDI here first to convert the image to the correct size and DPI, then pass the second image to XGraphics.DrawImage(). { bitmapResampled.Dispose(); bitmapResampled = null; bitmapResampled = new Bitmap(field.Width, field.Height); Graphics gr = Graphics.FromImage(bitmapResampled); gr.DrawImage(bitmapOriginal, 0, 0, field.Width, field.Height); gr.Dispose(); } g.DrawImage(bitmapResampled, p(field.XPos), p(field.YPos), p(field.Width), p(field.Height)); bitmapResampled.Dispose(); bitmapResampled = null; bitmapOriginal.Dispose(); bitmapOriginal = null; } //then, drawings-------------------------------------------------------------------------------------------- XPen pen = new XPen(XColors.Black, p(2)); string[] pointStr; List <Point> points; Point point; string[] xy; foreach (SheetField field in sheet.SheetFields) { if (field.FieldType != SheetFieldType.Drawing) { continue; } pointStr = field.FieldValue.Split(';'); points = new List <Point>(); for (int j = 0; j < pointStr.Length; j++) { xy = pointStr[j].Split(','); if (xy.Length == 2) { point = new Point(PIn.Int(xy[0]), PIn.Int(xy[1])); points.Add(point); } } for (int i = 1; i < points.Count; i++) { g.DrawLine(pen, p(points[i - 1].X), p(points[i - 1].Y), p(points[i].X), p(points[i].Y)); } } //then, rectangles and lines---------------------------------------------------------------------------------- XPen pen2 = new XPen(XColors.Black, p(1)); foreach (SheetField field in sheet.SheetFields) { if (field.FieldType == SheetFieldType.Rectangle) { g.DrawRectangle(pen2, p(field.XPos), p(field.YPos), p(field.Width), p(field.Height)); } if (field.FieldType == SheetFieldType.Line) { g.DrawLine(pen2, p(field.XPos), p(field.YPos), p(field.XPos + field.Width), p(field.YPos + field.Height)); } } //then, draw text-------------------------------------------------------------------------------------------- Bitmap doubleBuffer = new Bitmap(sheet.Width, sheet.Height); Graphics gfx = Graphics.FromImage(doubleBuffer); foreach (SheetField field in sheet.SheetFields) { if (field.FieldType != SheetFieldType.InputField && field.FieldType != SheetFieldType.OutputText && field.FieldType != SheetFieldType.StaticText) { continue; } xfontstyle = XFontStyle.Regular; if (field.FontIsBold) { xfontstyle = XFontStyle.Bold; } xfont = new XFont(field.FontName, field.FontSize, xfontstyle); //xfont=new XFont(field.FontName,field.FontSize,xfontstyle); //Rectangle rect=new Rectangle((int)p(field.XPos),(int)p(field.YPos),(int)p(field.Width),(int)p(field.Height)); XRect xrect = new XRect(p(field.XPos), p(field.YPos), p(field.Width), p(field.Height)); //XStringFormat format=new XStringFormat(); //tf.DrawString(field.FieldValue,font,XBrushes.Black,xrect,XStringFormats.TopLeft); GraphicsHelper.DrawStringX(g, gfx, 1d / p(1), field.FieldValue, xfont, XBrushes.Black, xrect); } gfx.Dispose(); //then, checkboxes---------------------------------------------------------------------------------- XPen pen3 = new XPen(XColors.Black, p(1.6f)); foreach (SheetField field in sheet.SheetFields) { if (field.FieldType != SheetFieldType.CheckBox) { continue; } if (field.FieldValue == "X") { g.DrawLine(pen3, p(field.XPos), p(field.YPos), p(field.XPos + field.Width), p(field.YPos + field.Height)); g.DrawLine(pen3, p(field.XPos + field.Width), p(field.YPos), p(field.XPos), p(field.YPos + field.Height)); } } //then signature boxes---------------------------------------------------------------------- foreach (SheetField field in sheet.SheetFields) { if (field.FieldType != SheetFieldType.SigBox) { continue; } SignatureBoxWrapper wrapper = new SignatureBoxWrapper(); wrapper.Width = field.Width; wrapper.Height = field.Height; if (field.FieldValue.Length > 0) //a signature is present { bool sigIsTopaz = false; if (field.FieldValue[0] == '1') { sigIsTopaz = true; } string signature = ""; if (field.FieldValue.Length > 1) { signature = field.FieldValue.Substring(1); } string keyData = Sheets.GetSignatureKey(sheet); wrapper.FillSignature(sigIsTopaz, keyData, signature); } XImage sigBitmap = XImage.FromGdiPlusImage(wrapper.GetSigImage()); g.DrawImage(sigBitmap, p(field.XPos), p(field.YPos), p(field.Width - 2), p(field.Height - 2)); } }
protected void btnExportPdf_Click(object sender, EventArgs e) { // Populate report PopulateGrid(); var documentDirectory = String.Format("{0}\\Temp\\", System.AppDomain.CurrentDomain.BaseDirectory); var logoDirectory = String.Format("{0}\\img\\", System.AppDomain.CurrentDomain.BaseDirectory); string destName = string.Format("RCNS_{0}.pdf", DateTime.Now.ToString("yyyyMMddhhmmsss")); string destFile = string.Format("{0}{1}", documentDirectory, destName); string logoName = string.Format("SIAPS_USAID_Horiz.png"); string logoFile = string.Format("{0}{1}", logoDirectory, logoName); string fontFile = string.Format("{0}\\arial.ttf", System.AppDomain.CurrentDomain.BaseDirectory); var linePosition = 60; var columnPosition = 30; // Create document PdfDocument pdfDoc = new PdfDocument(); XmlNode rootNode; XmlNode filterNode; XmlNode contentHeadNode; XmlNode contentNode; XmlNode contentValueNode; XmlAttribute attrib; XmlComment comment; // Create a new page PdfPage page = pdfDoc.AddPage(); page.Orientation = PageOrientation.Landscape; // Get an XGraphics object for drawing XGraphics gfx = XGraphics.FromPdfPage(page); XTextFormatter tf = new XTextFormatter(gfx); XPen pen = new XPen(XColor.FromArgb(255, 0, 0)); // Logo XImage image = XImage.FromFile(logoFile); gfx.DrawImage(image, 10, 10); // Create a new font Uri fontUri = new Uri(fontFile); try { XPrivateFontCollection.Global.Add(fontUri, "#Arial"); } catch { } XFont fontb = new XFont("Calibri", 10, XFontStyle.Bold | XFontStyle.Underline); XFont fontr = new XFont("Calibri", 10, XFontStyle.Regular); // Write header pdfDoc.Info.Title = "Causality Report for " + DateTime.Now.ToString("yyyy-MM-dd hh:MM"); gfx.DrawString("Causality Report for " + DateTime.Now.ToString("yyyy-MM-dd hh:MM"), fontb, XBrushes.Black, new XRect(columnPosition, linePosition, page.Width.Point, 20), XStringFormats.TopLeft); // Write filter linePosition += 24; gfx.DrawString("Range From : " + txtSearchFrom.Value, fontr, XBrushes.Black, new XRect(columnPosition, linePosition, page.Width.Point, 20), XStringFormats.TopLeft); linePosition += 24; gfx.DrawString("Range To : " + txtSearchTo.Value, fontr, XBrushes.Black, new XRect(columnPosition, linePosition, page.Width.Point, 20), XStringFormats.TopLeft); // Write content var pageCount = 1; var rowCount = 0; var cellCount = 0; ArrayList headerArray = new ArrayList(); ArrayList widthArray = new ArrayList(); foreach (TableRow row in dt_basic.Rows) { rowCount += 1; cellCount = 0; linePosition += 24; columnPosition = 30; if (linePosition >= 480) { pageCount += 1; page = pdfDoc.AddPage(); page.Orientation = PageOrientation.Landscape; linePosition = 60; gfx = XGraphics.FromPdfPage(page); tf = new XTextFormatter(gfx); // Logo gfx.DrawImage(image, 10, 10); gfx.DrawString("Causality Report (Page " + pageCount.ToString() + ")", fontb, XBrushes.Black, new XRect(columnPosition, linePosition, page.Width.Point, 20), XStringFormats.TopLeft); linePosition += 24; /// rewrite column headers foreach (var header in headerArray) { cellCount += 1; var width = Convert.ToInt32(widthArray[cellCount - 1]); gfx.DrawString(header.ToString(), fontb, XBrushes.Black, new XRect(columnPosition, linePosition, width, 20), XStringFormats.TopLeft); columnPosition += width; } columnPosition = 30; linePosition += 24; cellCount = 0; } foreach (TableCell cell in row.Cells) { int[] ignore = { }; if (!ignore.Contains(cellCount)) { cellCount += 1; if (rowCount == 1) { widthArray.Add((int)cell.Width.Value * 8); headerArray.Add(cell.Text); gfx.DrawString(cell.Text, fontb, XBrushes.Black, new XRect(columnPosition, linePosition, cell.Width.Value * 8, 20), XStringFormats.TopLeft); columnPosition += (int)cell.Width.Value * 8; } else { var width = Convert.ToInt32(widthArray[cellCount - 1]); tf.DrawString(cell.Text, fontr, XBrushes.Black, new XRect(columnPosition, linePosition, width, 20), XStringFormats.TopLeft); columnPosition += width; } } } } pdfDoc.Save(destFile); Response.Clear(); Response.Buffer = true; Response.ContentEncoding = Encoding.UTF8; Response.ContentType = "application/pdf"; Response.AddHeader("content-disposition", String.Format("attachment;filename={0}", destName)); Response.Charset = ""; this.EnableViewState = false; Response.WriteFile(destFile); Response.End(); }
/// <summary> /// Creates the normal appearance form X object for the annotation that represents /// this acro form text field. /// </summary> void RenderAppearance() { #if true_ PdfFormXObject xobj = new PdfFormXObject(Owner); Owner.Internals.AddObject(xobj); xobj.Elements["/BBox"] = new PdfLiteral("[0 0 122.653 12.707]"); xobj.Elements["/FormType"] = new PdfLiteral("1"); xobj.Elements["/Matrix"] = new PdfLiteral("[1 0 0 1 0 0]"); PdfDictionary res = new PdfDictionary(Owner); xobj.Elements["/Resources"] = res; res.Elements["/Font"] = new PdfLiteral("<< /Helv 28 0 R >> /ProcSet [/PDF /Text]"); xobj.Elements["/Subtype"] = new PdfLiteral("/Form"); xobj.Elements["/Type"] = new PdfLiteral("/XObject"); string s = "/Tx BMC " + '\n' + "q" + '\n' + "1 1 120.653 10.707 re" + '\n' + "W" + '\n' + "n" + '\n' + "BT" + '\n' + "/Helv 7.93 Tf" + '\n' + "0 g" + '\n' + "2 3.412 Td" + '\n' + "(Hello ) Tj" + '\n' + "20.256 0 Td" + '\n' + "(XXX) Tj" + '\n' + "ET" + '\n' + "Q" + '\n' + "";//"EMC"; int length = s.Length; byte[] stream = new byte[length]; for (int idx = 0; idx < length; idx++) { stream[idx] = (byte)s[idx]; } xobj.CreateStream(stream); // Get existing or create new appearance dictionary PdfDictionary ap = Elements[PdfAnnotation.Keys.AP] as PdfDictionary; if (ap == null) { ap = new PdfDictionary(_document); Elements[PdfAnnotation.Keys.AP] = ap; } // Set XRef to normal state ap.Elements["/N"] = xobj.Reference; //// HACK //string m = //"<?xpacket begin=\"\" id=\"W5M0MpCehiHzreSzNTczkc9d\"?>" + '\n' + //"<x:xmpmeta xmlns:x=\"adobe:ns:meta/\" x:xmptk=\"Adobe XMP Core 4.0-c321 44.398116, Tue Aug 04 2009 14:24:39\"> " + '\n' + //" <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"> " + '\n' + //" <rdf:Description rdf:about=\"\" " + '\n' + //" xmlns:pdf=\"http://ns.adobe.com/pdf/1.3/\"> " + '\n' + //" <pdf:Producer>PDFsharp 1.40.2150-g (www.pdfsharp.com) (Original: Powered By Crystal)</pdf:Producer> " + '\n' + //" </rdf:Description> " + '\n' + //" <rdf:Description rdf:about=\"\" " + '\n' + //" xmlns:xap=\"http://ns.adobe.com/xap/1.0/\"> " + '\n' + //" <xap:ModifyDate>2011-07-11T23:15:09+02:00</xap:ModifyDate> " + '\n' + //" <xap:CreateDate>2011-05-19T16:26:51+03:00</xap:CreateDate> " + '\n' + //" <xap:MetadataDate>2011-07-11T23:15:09+02:00</xap:MetadataDate> " + '\n' + //" <xap:CreatorTool>Crystal Reports</xap:CreatorTool> " + '\n' + //" </rdf:Description> " + '\n' + //" <rdf:Description rdf:about=\"\" " + '\n' + //" xmlns:dc=\"http://purl.org/dc/elements/1.1/\"> " + '\n' + //" <dc:format>application/pdf</dc:format> " + '\n' + //" </rdf:Description> " + '\n' + //" <rdf:Description rdf:about=\"\" " + '\n' + //" xmlns:xapMM=\"http://ns.adobe.com/xap/1.0/mm/\"> " + '\n' + //" <xapMM:DocumentID>uuid:68249d89-baed-4384-9a2d-fbf8ace75c45</xapMM:DocumentID> " + '\n' + //" <xapMM:InstanceID>uuid:3d5f2f46-c140-416f-baf2-7f9c970cef1d</xapMM:InstanceID> " + '\n' + //" </rdf:Description> " + '\n' + //" </rdf:RDF> " + '\n' + //"</x:xmpmeta> " + '\n' + //" " + '\n' + //" " + '\n' + //" " + '\n' + //" " + '\n' + //" " + '\n' + //" " + '\n' + //" " + '\n' + //" " + '\n' + //" " + '\n' + //" " + '\n' + //"<?xpacket end=\"w\"?>"; //PdfDictionary mdict = (PdfDictionary)_document.Internals.GetObject(new PdfObjectID(32)); //length = m.Length; //stream = new byte[length]; //for (int idx = 0; idx < length; idx++) // stream[idx] = (byte)m[idx]; //mdict.Stream.Value = stream; #else PdfRectangle rect = Elements.GetRectangle(PdfAnnotation.Keys.Rect); XForm form = new XForm(_document, rect.Size); XGraphics gfx = XGraphics.FromForm(form); if (_backColor != XColor.Empty) { gfx.DrawRectangle(new XSolidBrush(BackColor), rect.ToXRect() - rect.Location); } string text = Text; if (text.Length > 0) { gfx.DrawString(Text, Font, new XSolidBrush(ForeColor), rect.ToXRect() - rect.Location + new XPoint(2, 0), XStringFormats.TopLeft); } form.DrawingFinished(); form.PdfForm.Elements.Add("/FormType", new PdfLiteral("1")); // Get existing or create new appearance dictionary. PdfDictionary ap = Elements[PdfAnnotation.Keys.AP] as PdfDictionary; if (ap == null) { ap = new PdfDictionary(_document); Elements[PdfAnnotation.Keys.AP] = ap; } // Set XRef to normal state ap.Elements["/N"] = form.PdfForm.Reference; PdfFormXObject xobj = form.PdfForm; string s = xobj.Stream.ToString(); // Thank you Adobe: Without putting the content in 'EMC brackets' // the text is not rendered by PDF Reader 9 or higher. s = "/Tx BMC\n" + s + "\nEMC"; xobj.Stream.Value = new RawEncoding().GetBytes(s); #endif }
/// <summary> /// Generates the pdf document containing the specified stickers. No specs of the sheet are /// provided with the system. It should be a good idea. /// </summary> /// <param name="pdfPath">The full path to the pdf folder.</param> /// <param name="numberOfStickersLeftInSheet">The number of stickers left on the sheet used.</param> /// <param name="stickers">The stickers to layout in the document.</param> /// <returns></returns> public static string GeneratePreview( string pdfPath, int numberOfStickersLeftInSheet, IEnumerable <StickerInfo> stickers) { var numberOfBlanks = MAX_NUMBER_OF_STICKERS_PER_SHEET - numberOfStickersLeftInSheet; var numberOfStickersLeft = stickers.Count(); var document = new PdfDocument(); var page = document.AddPage(); var gtx = XGraphics.FromPdfPage(page); var nbFormatInfo = new CultureInfo("fr-CA", false).NumberFormat; var firstLeftRect = new XRect( XUnit.FromCentimeter(0), XUnit.FromCentimeter(1.9), XUnit.FromCentimeter(10.2), XUnit.FromCentimeter(3.4) ); page.Size = PdfSharp.PageSize.Letter; page.TrimMargins = new TrimMargins() { Left = XUnit.FromMillimeter(4), Top = XUnit.FromCentimeter(2) + XUnit.FromMillimeter(1), Right = XUnit.FromMillimeter(4), Bottom = XUnit.FromCentimeter(2) + XUnit.FromMillimeter(1) }; // O(n^2) for (int currentColumn = 0; currentColumn < NUMBER_OF_COLUMNS && numberOfStickersLeft > 0; currentColumn++) { var currentXPos = currentColumn * (firstLeftRect.Width + XUnit.FromMillimeter(9)); for (int position = 0; position < MAX_NUMBER_OF_STICKERS_PER_COLUMN && numberOfStickersLeft > 0; position++) { if (numberOfBlanks == 0) { var sticker = stickers.ElementAt(stickers.Count() - numberOfStickersLeft); var LivrETSID = $"{sticker.FairLivrETSID}-{sticker.UserLivrETSID}-{sticker.ArticleLivrETSID}"; var barcode = GenerateLivrETSBarCode(LivrETSID); var padding = XUnit.FromMillimeter(2); var currentYPos = (firstLeftRect.Height + XUnit.FromMillimeter(2.5)) * position; var currentRect = new XRect( currentXPos, currentYPos, firstLeftRect.Width, firstLeftRect.Height ); var fairTextRect = new XRect( currentRect.Left + padding, currentRect.Top + padding, currentRect.Width / 2, XUnit.FromMillimeter(5) ); var livretsIdRect = new XRect( currentRect.Left, currentRect.Bottom - XUnit.FromMillimeter(4), currentRect.Width, XUnit.FromMillimeter(4) ); var barCodeRect = new XRect( currentRect.Left + padding, livretsIdRect.Top - XUnit.FromMillimeter(6.2), currentRect.Width - 2 * padding, XUnit.FromMillimeter(6) ); var priceRect = new XRect( fairTextRect.Right, currentRect.Top + padding, currentRect.Width / 2, fairTextRect.Height ); var titleRect = new XRect( currentRect.Left + padding, fairTextRect.Bottom, currentRect.Width - 2 * padding, barCodeRect.Top - fairTextRect.Bottom ); gtx.DrawString( $"Foire {sticker.FairLivrETSID}", new XFont("Arial", 8, XFontStyle.Regular), XBrushes.Black, fairTextRect, XStringFormats.TopLeft ); gtx.DrawString( sticker.OfferPrice.ToString("C", nbFormatInfo), new XFont("Arial", 12, XFontStyle.Regular), XBrushes.Black, priceRect, XStringFormats.TopLeft ); gtx.DrawString( sticker.ArticleTitle, new XFont("Arial", 10, XFontStyle.Regular), XBrushes.Black, titleRect, XStringFormats.TopLeft ); gtx.DrawImage( XImage.FromGdiPlusImage(barcode), barCodeRect ); gtx.DrawString( LivrETSID, new XFont("Arial", 9, XFontStyle.Regular), XBrushes.Black, livretsIdRect, XStringFormats.TopCenter ); numberOfStickersLeft--; } else { numberOfBlanks--; } } } return(FileSystemFacade.SaveStickersDocument(document, pdfPath)); }
/// <summary> /// Renders the content found in Text /// </summary> /// <param name="gfx"> /// XGraphics - Instance of the drawing surface /// </param> /// <param name="brush"> /// XBrush - Line and Color to draw the bar code /// </param> /// <param name="font"> /// XFont - Font to use to draw the text string /// </param> /// <param name="position"> /// XPoint - Location to render the bar code /// </param> protected internal override void Render(XGraphics gfx, XBrush brush, XFont font, XPoint position) { // Create the array to hold the values to be rendered this.Values = this.Code128Code == Code128Type.C ? new byte[this.text.Length / 2] : new byte[this.text.Length]; String buffer = String.Empty; for (Int32 index = 0; index < text.Length; index++) switch (this.Code128Code) { case Code128Type.A: if (text[index] < 32) this.Values[index] = (byte)(text[index] + 64); else if ((text[index] >= 32) && (text[index] < 64)) this.Values[index] = (byte)(text[index] - 32); else this.Values[index] = (byte)text[index]; break; case Code128Type.B: this.Values[index] = (byte)(text[index] - 32); break; case Code128Type.C: if ((text[index] >= '0') && (text[index] <= '9')) { buffer += text[index]; if (buffer.Length == 2) { this.Values[index / 2] = byte.Parse(buffer); buffer = String.Empty; } } else throw new ArgumentOutOfRangeException("Parameter text (string) can only contain numeric characters for Code 128 - Code C"); break; } if (this.Values == null) throw new InvalidOperationException("Text or Values must be set"); if (this.Values.Length == 0) throw new InvalidOperationException("Text or Values must have content"); for (int x = 0; x < this.Values.Length; x++) if (this.Values[x] > 102) throw new ArgumentOutOfRangeException(BcgSR.InvalidCode128(x)); XGraphicsState state = gfx.Save(); BarCodeRenderInfo info = new BarCodeRenderInfo(gfx, brush, font, position); this.InitRendering(info); info.CurrPosInString = 0; info.CurrPos = position - CodeBase.CalcDistance(AnchorType.TopLeft, this.anchor, this.size); this.RenderStart(info); foreach (byte c in this.Values) this.RenderValue(info, c); this.RenderStop(info); if (this.TextLocation != TextLocation.None) this.RenderText(info); gfx.Restore(state); }
void RenderAppearance() { var format = TextAlign == TextAlignment.Left ? XStringFormats.CenterLeft : TextAlign == TextAlignment.Center ? XStringFormats.Center : XStringFormats.CenterRight; for (var idx = 0; idx < Annotations.Elements.Count; idx++) { var widget = Annotations.Elements[idx]; if (widget == null) { continue; } var rect = widget.Rectangle; var xRect = new XRect(0, 0, rect.Width, rect.Height); var form = new XForm(_document, xRect); EnsureFonts(form); using (var gfx = XGraphics.FromForm(form)) { if (widget.BackColor != XColor.Empty) { gfx.DrawRectangle(new XSolidBrush(widget.BackColor), xRect); } // Draw Border if (!widget.BorderColor.IsEmpty) { gfx.DrawRectangle(new XPen(widget.BorderColor), xRect); } var lineHeight = Font.Size * 1.2; var y = 0.0; var startIndex = Math.Min(TopIndex, Options.Count - (int)(rect.Height / lineHeight)); for (var i = startIndex; i < Options.Count; i++) { var text = Options[i]; // offset and shrink a bit to not draw on top of the outer border var lineRect = new XRect(1, y + 1, rect.Width - 2, lineHeight - 1); var selected = false; if (text.Length > 0) { if (SelectedIndices.Contains(i)) { gfx.DrawRectangle(new XSolidBrush(HighlightColor), lineRect); selected = true; } lineRect.Inflate(-2, 0); gfx.DrawString(text, Font, new XSolidBrush(selected ? HighlightTextColor : ForeColor), lineRect, format); y += lineHeight; } } form.DrawingFinished(); var ap = new PdfDictionary(this._document); widget.Elements[PdfAnnotation.Keys.AP] = ap; // Set XRef to normal state ap.Elements["/N"] = form.PdfForm.Reference; widget.Elements.SetName(PdfAnnotation.Keys.AS, "/N"); // set appearance state // Set XRef to normal state ap.Elements["/N"] = form.PdfForm.Reference; var xobj = form.PdfForm; var s = xobj.Stream.ToString(); s = "/Tx BMC\n" + s + "\nEMC"; xobj.Stream.Value = new RawEncoding().GetBytes(s); } } }
/// <summary> /// When implemented in a derived class renders the 2D code. /// </summary> protected internal abstract void Render(XGraphics gfx, XBrush brush, XPoint center);
/// <summary> /// Initializes a new instance of the <see cref="XTextFormatter"/> class. /// </summary> public XTextFormatter(XGraphics gfx) { if (gfx == null) throw new ArgumentNullException("gfx"); _gfx = gfx; }